生成的加密字符串在PyCrypto和Crypto ++中的大小不同

时间:2011-01-08 07:54:10

标签: c++ python aes crypto++ pycrypto

我最近使用Python脚本来加密字符串。但无法使用Crypto ++在C ++中解密它。我只是比较生成的加密字符串,发现它们不一样。有人可以帮忙吗?

这是我的Python代码:

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

这是我的C ++代码:

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;

1 个答案:

答案 0 :(得分:4)

默认情况下,Crypto ++使用PKCS5填充到明文字符串。此将填充添加到字符串的结尾,以确保字符串是块大小的倍数,对于AES,为16字节。如果明文已经是16的倍数,那么Crypto ++会在明文中添加另外16个字节的填充,然后对整个内容进行加密。 PyCrypto不会添加这个额外的填充,而是由用户决定以确保正确的块大小。请注意,当您解密Crypto ++加密的密文时,会自动删除额外的填充。