Crypto++:用Python加密,用C++解密

Crypto++ :Encrypt in Python ,decipher in C++

本文关键字:C++ 解密 Python Crypto++ 加密      更新时间:2023-10-16

我正在尝试执行以下操作:在python脚本中,我使用pycrypto-lib来加密一些文本。然后我把它保存到文件中。然后我加载该文件,并使用我在Python中使用的相同密钥对加密文本进行解码。它在stfDecryptor.MessageEnd()处失败;错误:

"CryptoCPP::InvalidCiphertext位于内存位置[某些内存]

这是我的代码:

Python:

from Crypto.Cipher import AES
BLOCK_SIZE = 16
PADDING = '{'
# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: c.encrypt(pad(s))
secret = 'MyKey123456789ab' 
# create a cipher object using the random secret
cipher = AES.new(secret)
# encode a string
encoded = EncodeAES(cipher, textIn)
#save to file
fileOut = open("enc_shader.vert","w")
fileOut.write(encoded)
fileOut.close()

CPP:

 std::string key = "MyKey123456789ab";
 std::string iv = "aaaaaaaaaaaaaaaa";
 std::ifstream fileIn("enc_shader.vert");
std::stringstream buffer;
buffer << fileIn.rdbuf();
std::string ciphertext1 = buffer.str();
CryptoPP::AES::Decryption aesDecryption((byte*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, (byte*)iv.c_str() );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext1.c_str() ), ciphertext1.size() );
stfDecryptor.MessageEnd();//fails here.

从我读到的内容来看,端点应该像pycrypto一样工作——只是CryptoCPP库的包装器。我可能错过了CPP侧的填充物吗?

更新:

好的,我发现改变填充方案:

 CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) ,BlockPaddingSchemeDef::NO_PADDING);

对CPP侧的字符串进行解码。但是解码后的字符串包含填充字符。因此,如果原始字符串是"aaaaaaaaaa"

解码后的字符串如下所示:

"aaaaaaaaaa"

将15个字节添加到32个字节。

为什么Crypto++在解密时不删除这些?

您的Python加密代码手动将"{"个字符添加到块大小中。这不是一个定义的填充模式,因此Crypto++代码将无法使用集成的填充方案删除填充。换句话说,您应该使用NO_PADDING解密,然后自己删除填充。

但最好让Python代码使用PKCS#7填充,这样您就可以在Crypto++中使用PKCS_PADDING作为选项。