C++ 使用 OpenSSL 实现 AES 解密 - Java 代码对应实现
#include <openssl/aes.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/err.h>
std::string decryptByAES(std::string input, std::string key) { std::string algorithm = 'AES'; std::string transformation = 'AES'; const EVP_CIPHER *cipher = EVP_get_cipherbyname(transformation.c_str()); if (!cipher) { throw std::runtime_error('Cipher not found.'); }
// Make sure the key is 16 bytes
if (key.length() != 16) {
throw std::runtime_error('Invalid key length.');
}
// Initialize the decryption context
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
throw std::runtime_error('Failed to create decryption context.');
}
if (!EVP_DecryptInit_ex(ctx, cipher, NULL, reinterpret_cast<const unsigned char*>(key.c_str()), NULL)) {
throw std::runtime_error('Failed to initialize decryption context.');
}
// Decrypt the input
const unsigned char* inputBytes = reinterpret_cast<const unsigned char*>(input.c_str());
int inputLength = input.length();
unsigned char* outputBytes = new unsigned char[inputLength];
int outputLength = 0;
if (!EVP_DecryptUpdate(ctx, outputBytes, &outputLength, inputBytes, inputLength)) {
throw std::runtime_error('Failed to decrypt input.');
}
int finalOutputLength = 0;
if (!EVP_DecryptFinal_ex(ctx, outputBytes + outputLength, &finalOutputLength)) {
throw std::runtime_error('Failed to finalize decryption.');
}
outputLength += finalOutputLength;
// Clean up and return the decrypted data
EVP_CIPHER_CTX_free(ctx);
std::string output(reinterpret_cast<char*>(outputBytes), outputLength);
delete[] outputBytes;
return output;
}
原文地址: https://www.cveoy.top/t/topic/nPUA 著作权归作者所有。请勿转载和采集!