I am trying to do the following:In a python script I use pycrypto lib to encrypt some text.Then I save it to file.Then I load that file and decode the encrypted text using the same key I used in Python.It fails at stfDecryptor.MessageEnd(); with the error:
"CryptoCPP::InvalidCiphertext at memory location [some memory]
Here is my code:
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.
From what I read these to endpoints should work as pycrypto just a wrapper for the CryptoCPP lib.May be I miss the padding on CPP side?
UPDATE:
Ok,I found that changing the padding scheme:
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) ,BlockPaddingSchemeDef::NO_PADDING);
decodes the string on CPP side.But the decoded string contains the padding chars. So if the original string was "aaaaaaaaaaaaaaaaa"
The decoded string looks like this:
"aaaaaaaaaaaaaaaaa{{{{{{{{{{{{{{{"
15 bytes were added to pad to 32 bytes.
Why Crypto++ doesn't remove those at decryption?
Your Python encryption code manually adds '{' characters to pad to the block size. This is not a defined padding mode, so the Crypto++ code will not be able to remove the padding using an integrated padding scheme. In other words, you should decrypt using NO_PADDING and then remove the padding yourself.
But it would be better to let the Python code use PKCS#7 padding, so you can use PKCS_PADDING as option within Crypto++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With