基于openssl库实现AES128算法全代码
时间: 2024-10-27 20:09:06 浏览: 26
在使用OpenSSL库实现AES128加密算法时,首先需要包含必要的头文件,并初始化OpenSSL环境。以下是一个简单的基于AES-128的CBC模式加密的C++示例:
```cpp
#include <openssl/aes.h>
#include <openssl/cipher.h>
#include <string>
std::string aes_encrypt(const std::string &plaintext, const std::string &key) {
AES_KEY aes_key;
unsigned char iv[AES_BLOCK_SIZE] = {0}; // 初始化向量
// 加密前设置AES key和IV
AES_set_encrypt_key(reinterpret_cast<const unsigned char*>(key.c_str()), 128, &aes_key);
AES_cbc_encrypt(reinterpret_cast<const unsigned char*>(plaintext.c_str()),
reinterpret_cast<unsigned char*>(iv), // 输出缓冲区
plaintext.length(), &aes_key, iv, AES_ENCRYPT); // CBC模式
// 返回加密后的数据加上初始化向量
std::string ciphertext = std::string(reinterpret_cast<char*>(iv), AES_BLOCK_SIZE) + std::string(reinterpret_cast<char*>(iv), plaintext.length());
return ciphertext;
}
std::string aes_decrypt(const std::string &ciphertext, const std::string &key) {
AES_KEY aes_key;
unsigned char iv[AES_BLOCK_SIZE];
AES_set_decrypt_key(reinterpret_cast<const unsigned char*>(key.c_str()), 128, &aes_key);
size_t block_size = AES_BLOCK_SIZE;
size_t data_length = ciphertext.size() - block_size;
// 提取IV和实际加密的数据
std::copy(ciphertext.begin(), ciphertext.begin() + block_size, iv);
AES_cbc_encrypt(reinterpret_cast<const unsigned char*>(ciphertext.c_str() + block_size),
reinterpret_cast<unsigned char*>(iv), // 输入缓冲区
data_length, &aes_key, iv, AES_DECRYPT);
return std::string(reinterpret_cast<char*>(iv), data_length);
}
阅读全文