我需要一个带有 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;
}