openSSL实现AES加密
时间: 2024-05-03 10:18:24 浏览: 10
OpenSSL是一个开源的加密库,可以用来实现各种加密算法,包括AES加密。下面是一个使用OpenSSL实现AES加密的示例代码:
```c
#include <stdio.h>
#include <string.h>
#include <openssl/aes.h>
int main()
{
// 明文和密钥
const unsigned char plaintext[] = "Hello, world!";
const unsigned char key[] = "0123456789abcdef";
// 初始化AES加密上下文
AES_KEY aes_key;
AES_set_encrypt_key(key, 128, &aes_key);
// 加密
unsigned char ciphertext[16];
AES_encrypt(plaintext, ciphertext, &aes_key);
// 输出结果
printf("Plaintext: %s\n", plaintext);
printf("Ciphertext: ");
for (int i = 0; i < 16; i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
return 0;
}
```
这段代码使用了OpenSSL提供的AES加密函数,其中`AES_set_encrypt_key()`用于初始化加密上下文,`AES_encrypt()`用于进行加密操作。需要注意的是,AES算法对明文的长度有要求,一般要求为16字节的倍数,所以在实际使用中需要进行填充。