我正在尝试加密一个简单的字符串,例如“Hello World!” 通过 Crypto++,并通过 Crypto++ 解密成功。但是通过 OpenSSL 命令解密 Crypto++ 加密结果时出现错误。
我的 C++ 代码:
#include <iostream>
#include <aes.h>
#include <base64.h>
#include <modes.h>
std::string aes_encrypt(std::string key, std::string plain)
{
std::string result;
CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption ecb_encryptor((byte *)key.c_str(), CryptoPP::AES::MAX_KEYLENGTH);
auto encryptor = new CryptoPP::StreamTransformationFilter(ecb_encryptor,
new CryptoPP::Base64Encoder(new CryptoPP::StringSink(result), false),
CryptoPP::StreamTransformationFilter::ZEROS_PADDING);
CryptoPP::StringSource(plain, true, encryptor);
return result;
}
std::string aes_decrypt(std::string key, std::string cipher)
{
std::string result;
CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption ecb_decryptor((byte *)key.c_str(), CryptoPP::AES::MAX_KEYLENGTH);
auto decryptor = new CryptoPP::Base64Decoder(new CryptoPP::StreamTransformationFilter(ecb_decryptor,
new CryptoPP::StringSink(result),
CryptoPP::StreamTransformationFilter::ZEROS_PADDING));
CryptoPP::StringSource(cipher, true, decryptor);
return result;
}
int main(int argc, char **argv)
{
const char *key = "1234567890";
const char *plain = "Hello World!";
std::cout << "plain: " << plain << std::endl;
std::string cipher = aes_encrypt(key, plain);
std::cout << "cipher: " << aes_encrypt(key, plain) << std::endl;
std::cout << "plain: " << aes_decrypt(key, cipher) << std::endl;
return 0;
}
输出:
plain: Hello World!
cipher: bVgt4KsCOTULujusMJvhhw==
plain: Hello World!
OpenSSL 命令:
xxx@xxxdeMacBook-Pro ~ $ echo -n 'Hello World!' | openssl enc -e -aes-256-ecb -nosalt -a -A -pass pass:1234567890
7sQWFmxUUQ8DpoXh9DXS8g==
xxx@xxxdeMacBook-Pro ~ $ echo -n '7sQWFmxUUQ8DpoXh9DXS8g==' | openssl enc -d -aes-256-ecb -nosalt -a -A -pass pass:1234567890
Hello World!
尝试使用 OpenSSL 解密 Crypto++ 结果失败:
xxx@xxxdeMacBook-Pro ~ $ echo -n 'bVgt4KsCOTULujusMJvhhw==' | openssl enc -d -aes-256-ecb -nosalt -a -A -pass pass:1234567890
bad decrypt
78710:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64.50.6/src/crypto/evp/evp_enc.c:330: