首页 文章

加密:在Python中加密,在C中解密

提问于
浏览
1

我正在尝试执行以下操作:在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.

从我读到的内容到 endpoints 应该像pycrypto一样只是CryptoCPP lib的包装器 . 我可以错过CPP端的填充吗?

UPDATE:

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

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

解码CPP端的字符串 . 但解码后的字符串包含填充字符 . 所以如果原来的字符串是“aaaaaaaaaaaaaaaa”

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

“aaaaaaaaaaaaaaaaa {{{{{{{{{{{{{{{”

添加了15个字节以填充到32个字节 .

为什么Crypto不会在解密时删除它们?

1 回答

  • 2

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

    但是让Python代码使用PKCS#7填充会更好,所以你可以在Crypto中使用 PKCS_PADDING 作为选项 .

相关问题