openssl进行AES加密
时间: 2023-10-24 09:25:32 浏览: 166
使用 OpenSSL 进行 AES 加密可以按照以下步骤进行:
1. 导入 OpenSSL 库:
```
#include <openssl/aes.h>
```
2. 定义 AES 加密的密钥和明文:
```
unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
unsigned char *plaintext = (unsigned char *)"This is the plaintext.";
```
3. 定义 AES 加密的向量(IV):
```
unsigned char *iv = (unsigned char *)"0123456789012345";
```
4. 定义 AES 上下文结构体:
```
AES_KEY aes_key;
```
5. 初始化 AES 上下文:
```
AES_set_encrypt_key(key, 256, &aes_key);
```
6. 定义加密后的密文缓冲区:
```
unsigned char ciphertext[128];
```
7. 进行 AES 加密:
```
AES_cbc_encrypt(plaintext, ciphertext, strlen(plaintext), &aes_key, iv, AES_ENCRYPT);
```
完整的示例代码如下:
```
#include <openssl/aes.h>
#include <stdio.h>
#include <string.h>
int main()
{
unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
unsigned char *plaintext = (unsigned char *)"This is the plaintext.";
unsigned char *iv = (unsigned char *)"0123456789012345";
AES_KEY aes_key;
AES_set_encrypt_key(key, 256, &aes_key);
unsigned char ciphertext[128];
AES_cbc_encrypt(plaintext, ciphertext, strlen(plaintext), &aes_key, iv, AES_ENCRYPT);
printf("Plaintext: %s\n", plaintext);
printf("Ciphertext: ");
for(int i = 0; i < strlen(plaintext); i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
return 0;
}
```
需要注意的是,上述示例代码中使用的是 AES-256 加密,如果需要使用其他加密长度,可以根据需要调整相关参数。同时,还需要注意密钥和向量的长度要符合 AES 加密标准。
阅读全文