python - C++ 中的 Crypto++ :Encrypt in Python , 解密

标签 python c++ encryption

我正在尝试执行以下操作:在 python 脚本中,我使用 pycrypto lib 来加密一些文本。然后我将它保存到文件。然后我加载该文件并使用我在 Python 中使用的相同 key 解码加密文本。它在 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 端解码字符串。但解码后的字符串包含填充字符。 所以如果原始字符串是“aaaaaaaaaaaaaaaaa”

解码后的字符串是这样的:

"aaaaaaaaaaaaaaaaa{{{{{{{{{{{{{{{"

15 个字节被添加到 pad 到 32 个字节。

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

最佳答案

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

但最好让 Python 代码使用 PKCS#7 填充,因此您可以使用 PKCS_PADDING 作为 Crypto++ 中的选项。

关于python - C++ 中的 Crypto++ :Encrypt in Python , 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649485/

相关文章:

Python win32crypt.CryptProtectData 2.5 和 3.1 之间的区别?

Python Unicode 警告 : Unicode equal comparison failed to convert both arguments to Unicode

尝试制作更大/更小的窗口时,python gtk.window.resize 不起作用

python - PyUnit - 如何对某个输入进入无限循环的方法进行单元测试?

c++ - 使用 ucnv_convert() 时为韩语显示垃圾字符

带模板的 C++ 工厂模式

javascript - 如何使用 RSA 公钥加密 Javascript 中的数据?

C++ With Initializer List 一个东西,什么时候使用普通构造函数?

java - 加密mongodb中的密码字段

java - 加密文本文件以防止可读