【问题标题】:AES with padding pkcs7 c++ code带有填充 pkcs7 c++ 代码的 AES
【发布时间】:2011-05-29 08:50:28
【问题描述】:

我需要一个带有 aes-cbc256 和填充的字符串加密示例(在 C++ 中 -> 我正在使用 linux-Ubuntu):PKCS7 请帮忙。


对于以下代码,如何将 IV 设置为 0 并将键值设置为字符串值?我还想添加 pkcs7 填充。我正在使用 crypto++ 库(在 Linux 中)

// Driver.cpp   
//      

#include "stdafx.h"    
#include "cryptopp/dll.h"    
#include "cryptopp/default.h"    
#include "crypto++/osrng.h"    
using CryptoPP::AutoSeededRandomPool;    

#include <iostream>    
using std::cout;    
using std::cerr;       

#include <string>    
using std::string;       

#include "crypto++/cryptlib.h"    
using CryptoPP::Exception;        

#include "crypto++/hex.h"    
using CryptoPP::HexEncoder;    
using CryptoPP::HexDecoder;        

#include "crypto++/filters.h"    
using CryptoPP::StringSink;    
using CryptoPP::StringSource;    
using CryptoPP::StreamTransformationFilter;        

#include "crypto++/aes.h"    
using CryptoPP::AES;       

#include "crypto++/ccm.h"    
using CryptoPP::CBC_Mode;       

#include "assert.h"        

int main(int argc, char* argv[])    
{    
    AutoSeededRandomPool prng;        

    byte key[ AES::DEFAULT_KEYLENGTH ];    
    prng.GenerateBlock( key, sizeof(key) );        

    byte iv[ AES::BLOCKSIZE];    
    iv[AES::BLOCKSIZE] = 0;    
    //prng.GenerateBlock(iv,  sizeof(iv) );        

    string plain = "CBC Mode Test";    
    string cipher, encoded, recovered;       

    // Pretty print key    
    encoded.clear();    
    StringSource( key, sizeof(key), true,    
                  new HexEncoder(new StringSink( encoded )) // HexEncoder    
    ); // StringSource

    cout << "key: " << encoded << endl;        

    // Pretty print iv    
    encoded.clear();

    StringSource( iv, sizeof(iv), true,    
        new HexEncoder(new StringSink( encoded )) // HexEncoder    
    ); // StringSource

    cout << "iv: " << encoded << endl;       

    /*********************************\
    \*********************************/

    try    
    {    
        cout << "plain text: " << plain << endl;            
        CBC_Mode< AES >::Encryption e;    
        e.SetKeyWithIV( key, sizeof(key), iv );     

        // The StreamTransformationFilter adds padding    
        //  as required. ECB and CBC Mode must be padded    
        //  to the block size of the cipher.    
        StringSource( plain, true,     
            new StreamTransformationFilter( e,    
                new StringSink( cipher )    
            ) // StreamTransformationFilter          
        ); // StringSource    
    }    
    catch( CryptoPP::Exception& e )    
    {    
        cerr << "Caught Exception..." << endl;    
        cerr << e.what() << endl;    
        cerr << endl;    
    }    

    /*********************************\    
    \*********************************/    

    // Pretty print    
    encoded.clear();    
    StringSource( cipher, true,    
        new HexEncoder(    
            new StringSink( encoded )    
        ) // HexEncoder    
    ); // StringSource    
    cout << "cipher text: " << encoded << endl;    

    /*********************************\    
    \*********************************/    

    try    
    {    
        CBC_Mode< AES >::Decryption d;    
        d.SetKeyWithIV( key, sizeof(key), iv );    

        // The StreamTransformationFilter removes    
        //  padding as required.    
        StringSource s( cipher, true,     
            new StreamTransformationFilter( d,    
                new StringSink( recovered )    
            ) // StreamTransformationFilter    
        ); // StringSource    

        cout << "recovered text: " << recovered << endl;    
    }    
    catch( CryptoPP::Exception& e )    
    {    
        cerr << "Caught Exception..." << endl;    
        cerr << e.what() << endl;    
        cerr << endl;    
    }    

    /*********************************\    
    \*********************************/    

    assert( plain == recovered );    

    return 0;    
}

【问题讨论】:

  • 好的。 byteunsigned charAES::DEFAULT_KEYLENGTH 通常是 16。所以你有一个长度为 16 的无符号字符数组。只需将您的字符串复制到它将char 转换为unsigned char,然后填充 key 数组的其余部分具有已知值,例如0. 那就是:关键
  • 至于iv,你的意思是“全0”吗?如果是这样,只需用 0 或您喜欢的任何其他值填充它。
  • 所以 aes 是 128。你的意思是我必须改变 prng.GenerateBlock(key, sizeof(key)); with key[aes::default_keylenght]='hello0000000000'?..如果没有,你能写出正确的代码吗?我真的很感激:)。填充物呢?是PKCS7吗?我在哪里可以更改或查看价值?..THX 很多!
  • 还有一个问题。如何打印键值? cout

标签: c++ crypto++ pkcs#7


【解决方案1】:

OpenSSL 默认使用 PKCS7 填充。这种填充意味着当您的数据不是块大小的倍数时,您填充值 nn 个字节,其中 n 有很多您需要达到块大小的字节数。 AES 的块大小为 16。

这是一个关于如何使用 AES256-cbc 和 OpenSSL 加密字符串的示例。 OpenSSL 文档也有examples,尽管它们使用不同的密码。此示例不进行错误检查。

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <cassert>

#include <openssl/evp.h>

int main()
{
    // ctx holds the state of the encryption algorithm so that it doesn't
    // reset back to its initial state while encrypting more than 1 block.
    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);

    unsigned char key[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
                   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f};
    unsigned char iv[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    assert(sizeof(key) == 32);  // AES256 key size
    assert(sizeof(iv) == 16);   // IV is always the AES block size

    // If data isn't a multiple of 16, the default behavior is to pad with
    // n bytes of value n, where n is the number of padding bytes required
    // to make data a multiple of the block size.  This is PKCS7 padding.
    // The output then will be a multiple of the block size.
    std::string plain("encrypt me");
    std::vector<unsigned char> encrypted;
    size_t max_output_len = plain.length() + 16 - (plain.length() % 16);
    encrypted.resize(max_output_len);

    // Enc is 1 to encrypt, 0 to decrypt, or -1 (see documentation).
    EVP_CipherInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv, 1);

    // EVP_CipherUpdate can encrypt all your data at once, or you can do
    // small chunks at a time.
    int actual_size = 0;
    EVP_CipherUpdate(&ctx,
             &encrypted[0], &actual_size,
             reinterpret_cast<unsigned char *>(&plain[0]), plain.size());

    // EVP_CipherFinal_ex is what applies the padding.  If your data is
    // a multiple of the block size, you'll get an extra AES block filled
    // with nothing but padding.
    int final_size;
    EVP_CipherFinal_ex(&ctx, &encrypted[actual_size], &final_size);
    actual_size += final_size;

    encrypted.resize(actual_size);

    for( size_t index = 0; index < encrypted.size(); ++index )
    {
        std::cout << std::hex << std::setw(2) << std::setfill('0') <<
            static_cast<unsigned int>(encrypted[index]);
    }
    std::cout << "\n";

    EVP_CIPHER_CTX_cleanup(&ctx);

    return 0;
}

将其命名为 encrypt.cpp 并编译:

g++ encrypt.cpp -o encrypt -lcrypto -lssl -Wall

你会得到这个输出:

338d2a9e28208cad84c457eb9bd91c81

您可以通过从命令提示符运行 OpenSSL 命令行实用程序来验证正确性:

$ echo -n "encrypt me" > to_encrypt
$ openssl enc -in to_encrypt -out encrypted -e -aes-256-cbc \
-K 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f \
-iv 00000000000000000000000000000000
$ hexdump -C encrypted

而且 hexdump 将显示与 c++ 程序相同的字节。

00000000  33 8d 2a 9e 28 20 8c ad  84 c4 57 eb 9b d9 1c 81  |3.*.( ....W.....|

【讨论】:

  • 非常感谢!!!它确实帮助了我你的例子:) THX !!祝你有美好的一天,圣诞快乐!
  • 如何解密编码的字符串?我也必须在加密后添加base64。我如何将 openssl 用于第二个选项:base64?谢谢:)....!很抱歉提出愚蠢的问题,但对我来说,这在这个领域是全新的:)......例子太少了:(。再次感谢!!:)
  • 代码是一样的。我只需要换行: EVP_CipherInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv, 1); 0 不是 1,不是吗?
  • 在我的代码中,密钥是一个名为 hello 的密码。我有以下错误: int main(): Assertion `sizeof(key) == 32' failed。中止
  • @she:是的,我认为您只需将 EVP_CipherInit_ex 中的 1 更改为 0 即可解密。至于断言,一个 AES256 密钥是 32 个字节。在这个EVP_Cipher_* API 中它必须是 32 字节。有一个 OpenSSL API,它可以获取密码并生成 AES256 密钥,但我不确定它是什么。我知道有这样一个 API,因为您可以使用这样的命令行实用程序来做到这一点:openssl aes-256-cbc -iv 00000000000000000000000000000000 -e -in plain_text_file -out encrypted_file,然后它会要求输入密码。也许发布另一个问题,询问如何做到这一点。
【解决方案2】:

也看看我对this question的回答

我建议查看cryptopp。这是一个代码示例:

CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption encryptor;
byte* key;
size_t keylen;
// ... acquire key

encryptor.SetKey( key, keylen );

std::string input;
std::string result;
// read input ...

StringSource( input, true,
       new StreamTransformationFilter( encryptor, new StringSink( result ),
     StreamTransformationFilter::PKCS_PADDING));

StreamTransformationFilter 中填充模式的值可以是:

BlockPaddingScheme { 
  NO_PADDING, ZEROS_PADDING, PKCS_PADDING, ONE_AND_ZEROS_PADDING, 
  DEFAULT_PADDING 
}

编辑:将示例中的填充模式替换为 pkcs

【讨论】:

  • 非常感谢。如果您能给我一个链接,我将不胜感激,其中给出了一个用 aes、cbc 和 pkcs 填充对字符串进行编码的 c++ 代码作为示例:d。谢谢...:D
  • 我无法打开 cryptoop 页面:(....我确实在互联网上搜索了很多...但我真的没有找到一个简单的示例,其中还包含 pkcs7 填充字符串用 aes 加密。
  • @she:很奇怪 - 它对我来说可以正常打开...实际上,我在这里提供的示例似乎可以满足您的需要 - 我对其进行了一些编辑以更改填充值并添加了设置键.无论如何,这是 cryptopp wiki 上的一个示例:cryptopp.com/wiki/CBC,您只需要添加可选的填充参数,在他们的示例中省略。
  • 非常感谢:)...你给的前任是在 Windows 平台上的。我正在使用 linux:ubuntu 9.10 ....我无法测试代码
  • @she:不,只是他们附加的代码示例包括 MSVC 项目文件。我自己在 Linux 上工作 - 我只是把它们(.dsp)扔掉,代码在 Linux(CentOS)上编译并完美运行
猜你喜欢
  • 2020-12-28
  • 1970-01-01
  • 2021-04-17
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 2023-03-17
  • 2015-08-22
相关资源
最近更新 更多