Crypto++:用Python加密,用C++解密
Crypto++ :Encrypt in Python ,decipher in C++
我正在尝试执行以下操作:在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
作为选项。
相关文章:
- AES加密到解密未正确输出
- 为什么这不是解密
- 通过 Openssl 命令行加密,通过 c++ 解密
- OpenSSL 解密功能无法正常工作
- 仿射密码解密,输出大小写不同
- 将加密消息从 php 发送到 C++ 应用程序,然后使用 CryptoPP 进行解密
- 私钥解密代码使用公共接口说明符到 BSAFE 库 v6.0?
- POCO C++加密/解密
- 从加密项目向量中解密任意选择的元素会导致无效的 PKCS #7 块错误
- 尝试从 Visual Studios C++ 中的加密字符串输出解密字符串时出现逻辑错误
- OpenSSL RSA 解密随机失败 C/C++
- 压缩天然气.AES.错误解密(可能加密)的文件
- C++ - 从文件解密字符串
- C++ - 如何从上到下制作 4x4 矩阵和 cout 列(需要解密字符串)
- 运行密钥密码解密知道密钥?
- 如何在c ++中使用XOR解密文件?
- 如何制作一个程序,它使用特定单词加密和解密消息?
- 基本加密和解密方法不起作用 C++ 11.
- 凯撒密码在C++中无法正确解密的问题
- 异或字符串加密/解密输出错误