The generated encrypted string does not have the same size in PyCrypto and Crypto ++

I recently used a Python script to encrypt a string. But failed to decrypt it in C ++ using Crypto ++. I simply compared the generated encrypted strings and found that they did not match. Can anybody help?

Here is my Python code:

key = "0123456789abcdef" data = "ccccccccccccccccdddddddddddddddd" iv = "aaaaaaaaaaaaaaaa" encryptor = AES.new(key, AES.MODE_CBC, iv) enc = encryptor.encrypt(data) print enc 

Here is my C ++ code:

 std::string key = "0123456789abcdef"; std::string iv = "aaaaaaaaaaaaaaaa"; std::string plaintext = "ccccccccccccccccdddddddddddddddd"; std::string ciphertext; std::string decryptedtext; std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl; std::cout << plaintext; std::cout << std::endl << std::endl; CryptoPP::AES::Encryption aesEncryption((byte *)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH); CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, (byte *)iv.c_str() ); CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) ); stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() + 1 ); stfEncryptor.MessageEnd(); std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl; for( int i = 0; i < ciphertext.size(); i++ ) { std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " "; } 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*>( ciphertext.c_str() ), ciphertext.size() ); stfDecryptor.MessageEnd(); std::cout << "Decrypted Text: " << std::endl; std::cout << decryptedtext; std::cout << std::endl << std::endl; 
+4
source share
1 answer

By default, Crypto ++ uses the PKCS5 add-on for plaintext strings. This adds an addition to the end of the line to make sure the line is a multiple of the block size, which for AES is 16 bytes. If the plaintext is already a multiple of 16, Crypto ++ adds another 16 bytes of padding to the plaintext and then encrypts it all. PyCrypto does not add an additional add-on, leaving it to the user to ensure the correct block size. Please note that when decrypting Crypto ++ encrypted text, the add-on is automatically deleted.

+4
source

Source: https://habr.com/ru/post/1334738/


All Articles