简体   繁体   中英

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

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM