cryptoPP AES,奇怪的加密输出

cryptoPP AES, weird encryption output

本文关键字:加密 输出 AES cryptoPP      更新时间:2023-10-16

我是新的并测试出cryptoPP,我尝试使用cryptoPP一次加密单个字符,我注意到一些字符不能正确加密并表现出奇怪的行为,如多于或少于16个字符,或奇怪的安排。

我使用的代码是:

std::string data;
std::cin >> data;
std::string plaintext = data;
std::string ciphertext;
byte key[16 ] = {1,2,3,5,6,7,8,9,0,1,2,3,4,5,6} ; 
byte iv[ 16 ]={1,2,3,5,6,7,8,9,0,1,2,3,4,5,6};
memset( key, 0, sizeof(key));
memset( iv, 0, sizeof(iv) );
CryptoPP::AES::Encryption aesEncryption(key, 16);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length());
stfEncryptor.MessageEnd();
std::cout << ciphertext << std::endl;
std::ofstream file("d:\log.txt", std::ofstream::out | std::ofstream::app);
file.write(ciphertext.c_str(), ciphertext.size());
file.close();
system("PAUSE");

解密代码如下:

byte key[16 ] = {1,2,3,5,6,7,8,9,0,1,2,3,4,5,6} ; 
byte iv[ 16 ]={1,2,3,5,6,7,8,9,0,1,2,3,4,5,6};
memset( key, 0, 16  );
memset( iv, 0, 16 );
std::string decryptedtext;
std::string test = get_file_contents("d:\log.txt");
for (int i = 0; i < test.length() ; i += 16)  {
    std::string block = test.substr(i, i + 16);
    test.replace(i, i + 16, block);
    CryptoPP::AES::Decryption aesDecryption(key, 16);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( block.c_str() ), 16 );
    stfDecryptor.MessageEnd();
}
std::cout << decryptedtext << std::endl;
std::ofstream fout("d:\aesencrypt.txt");
fout << decryptedtext;

如果我不输入某些字符,它会工作。当我输入字符"c"或"r"时发生问题,它变得奇怪,当我解密时我无法解析16个字符。解密将失败,因为加密文本不对齐或多于或少于16个字符。

我完全运行你的代码没有写/读/从文件,它的工作。(它也适用于"c"answers"r")。我把这两个片段合二为一,去掉文件,分配给test = ciphertext;。也许问题出在读/写文件上…

加密一个或多个字符并不重要:如果输入不是块大小的倍数,CBC模式会添加填充。