C语言openssl实现aes加密
时间: 2023-10-19 08:05:57 浏览: 178
要在C语言中使用OpenSSL库实现AES加密,你需要按照以下步骤进行操作:
1. 包含必要的头文件:
```c
#include <openssl/aes.h>
#include <openssl/rand.h>
```
2. 生成随机密钥:
```c
unsigned char key[AES_BLOCK_SIZE];
if (!RAND_bytes(key, sizeof(key))) {
// 生成密钥失败
}
```
3. 初始化AES加密上下文:
```c
AES_KEY aes_key;
if (AES_set_encrypt_key(key, 128, &aes_key) < 0) {
// 初始化加密上下文失败
}
```
4. 加密数据:
```c
unsigned char plaintext[AES_BLOCK_SIZE] = "Hello, AES!";
unsigned char ciphertext[AES_BLOCK_SIZE];
AES_encrypt(plaintext, ciphertext, &aes_key);
```
5. 解密数据:
```c
unsigned char decrypted[AES_BLOCK_SIZE];
AES_decrypt(ciphertext, decrypted, &aes_key);
```
完整的示例代码如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
void print_hex(const unsigned char *buf, size_t len) {
for (size_t i = 0; i < len; i++) {
printf("%02X", buf[i]);
}
printf("\n");
}
int main() {
unsigned char plain_text[AES_BLOCK_SIZE] = "Hello, AES!";
unsigned char key[AES_BLOCK_SIZE];
// 生成密钥
if (!RAND_bytes(key, sizeof(key))) {
fprintf(stderr, "生成密钥失败!\n");
return 1;
}
printf("原始数据:");
print_hex(plain_text, sizeof(plain_text));
// 加密
AES_KEY aes_key;
if (AES_set_encrypt_key(key, 128, &aes_key) < 0) {
fprintf(stderr, "初始化加密上下文失败!\n");
return 1;
}
unsigned char cipher_text[AES_BLOCK_SIZE];
AES_encrypt(plain_text, cipher_text, &aes_key);
printf("加密后的数据:");
print_hex(cipher_text, sizeof(cipher_text));
// 解密
if (AES_set_decrypt_key(key, 128, &aes_key) < 0) {
fprintf(stderr, "初始化解密上下文失败!\n");
return 1;
}
unsigned char decrypted[AES_BLOCK_SIZE];
AES_decrypt(cipher_text, decrypted, &aes_key);
printf("解密后的数据:");
print_hex(decrypted, sizeof(decrypted));
return 0;
}
```
以上代码将生成一个随机的128位密钥,使用该密钥对明文进行AES加密,并将加密后的结果进行解密。输出结果将打印出原始数据、加密后的数据和解密后的数据的十六进制表示形式。
请确保已经正确安装了OpenSSL库,并通过编译器链接该库进行编译。
阅读全文
相关推荐
















