aes c++实现
时间: 2023-07-27 12:06:08 浏览: 46
以下是使用 C++ 实现 AES 加密的示例代码:
```
#include <iostream>
#include <cstring>
#include <openssl/aes.h> // 需要安装 OpenSSL 库
int main() {
// 原始数据和密钥
unsigned char plaintext[] = "Hello, world!";
unsigned char key[] = "0123456789abcdef";
const int plaintext_len = strlen((char*)plaintext);
const int key_len = strlen((char*)key);
// 初始化 AES 上下文
AES_KEY aes_key;
AES_set_encrypt_key(key, key_len*8, &aes_key);
// 分配加密后数据的缓冲区
unsigned char ciphertext[plaintext_len + AES_BLOCK_SIZE];
memset(ciphertext, 0, sizeof(ciphertext));
// 加密
AES_encrypt(plaintext, ciphertext, &aes_key);
// 输出加密后数据
std::cout << "Ciphertext: ";
for (int i = 0; i < plaintext_len + AES_BLOCK_SIZE; ++i) {
std::cout << std::hex << (int)ciphertext[i];
}
std::cout << std::endl;
return 0;
}
```
这里使用 OpenSSL 库中的 AES 函数,需要在编译时链接 OpenSSL 库。该示例代码对 "Hello, world!" 进行加密,密钥为 "0123456789abcdef",输出加密后的数据。