How to decrypt string data in C++ with Crypto++ where the original string encrypted in Python with pyCrypto

StackOverflow https://stackoverflow.com/questions/4593793

  •  15-10-2019
  •  | 
  •  

Question

I've just encrypted a data string with pyCrypto easily, but don't know how to decrypt it in crypto++. Anybody can help with a sample decryption code in C++ with crypto++? Here is my python code:

key = '0123456789abcdef' 
data = "aaaaaaaaaaaaaaaa" 
iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16)) 
encryptor = AES.new(key, AES.MODE_CBC, iv) 
enc = encryptor.encrypt(data)
Was it helpful?

Solution

This code is from an example from 2005, but it should give you a good starting point:

std::string ciphertext = "..."; // what Python encryption produces
std::string decryptedtext;

byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];

// populate key and iv with the correct values

CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();

// it's all in decryptedText now

OTHER TIPS

same approach as @Jon, a bit simplified

std::string ciphertext = "..."; // what Python encryption produces
std::string decryptedtext;

byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];

// populate key and iv with the correct values

CryptoPP::CBC_Mode< CryptoPP::AES >::Decryption decryptor;
decryptor.SetKeyWithIV(key, sizeof(key), iv);


CryptoPP::StringSource(ciphertext, true,
        new CryptoPP::StreamTransformationFilter( decryptor,
            new CryptoPP::StringSink( decryptedtext )
        )
);

The true parameter to CryptoPP::StringSource means "consume the whole input"

Note that (obviously) you need your C++ decryptor to know the IV you used for encryption. Since you generate a random IV in python, the popular technique is to prepend the IV to the encrypted text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top