密文长度不是 CryptoPP 中块大小的倍数

ciphertext length is not a multiple of block size in cryptopp

本文关键字:CryptoPP 密文      更新时间:2023-10-16

我的程序可以加密文本并将其保存在文件中,并从文件获取后解密密文。

但是我一直收到此错误

terminate called after throwing an instance of 'CryptoPP::InvalidCiphertext'
what(): StreamTransformationFilter: ciphertext length is not a multiple of block size

从文件中读取数据时,我得到的文件大小为密文长度,但内容大小较小,可能是错误的。

法典:

std::string key = "0123456789abcdef";
std::string plaintext = "name macmilan age 24 ciy bonn country germany";
std::string ciphertext;
std::string decryptedtext;
CryptoPP::AES::Encryption aesEncryption((byte *)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::ECB_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption);
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() + 1 );
stfEncryptor.MessageEnd();
CryptoPP::AES::Decryption aesDecryption((byte *)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::ECB_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption);
std::cout << "ciphertext Text:"<<ciphertext.c_str()<<"length"<<ciphertext.length()<< std::endl;
FILE *ptr = fopen("temp.txt", "w");
if(ptr){
    fprintf(ptr, "%s",ciphertext.c_str());
    fclose(ptr);
    ptr = NULL;
}
ptr = fopen("temp.txt", "r");
if(ptr){
    fseek(ptr, 0, SEEK_END);
    size_t size = ftell(ptr);
    std::cout << "file size"<<size<< std::endl;
    char* temp = new char[size];
    rewind(ptr);
    fscanf(ptr,"%s",temp);
    ciphertext = temp;
    delete[] temp;
    ptr = NULL;
}
std::cout << "ciphertext Text:"<<ciphertext.c_str()<<"length"<<ciphertext.length() << std::endl;
try{
    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();
}
catch(CryptoPP::Exception &e)
{
    std::cout << "Decrypted Text:"<<e.what();
}
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
system("pause");
return 0;

输出:

ciphertext Text:î4¬■◄vqù┼Ä╢óΣ*₧z┐É;'!ìy─ªú√@╕╡Oh∙2♠ε→ktáäì╘aÄδ▌length48
file size48
ciphertext Text:î4¬■◄vqù┼Ä╢óΣ*₧z┐É;'!ìy─ªú√@╕╡Oh∙2♠εlength37
Decrypted Text:StreamTransformationFilter: ciphertext length is not a multiple o
f block sizeDecrypted Text:
name macmilan ag

在加密中可能会出现各种字符,包括 null (0)。因此,当您在文件中写入加密字符串时,您也会写入 null。检索加密值读取器时会获取空字符,并假定该字符串已终止。所以它会更短。要解决,您必须使用 Base64 或 MD5 等编码,或者打开文件并以二进制模式读取

您可能

希望以二进制模式读取和写入文件 - 在调用fopen时使用"wb"和"rb"。

此外,您可能还想使用 fwritefread . fscanf会停在空白处,这对你没有帮助。

读取和写入二进制文件时,要fopenmode参数必须"rb""wb",否则文件中不可打印的字符可能会被解释为控制字符。在这里,您的数据中似乎有一个 Ctrl-Z(十六进制0x1a),它是文本文件中的文件结束标记。