用c++使用openssl库写一个aes加解密
时间: 2023-11-03 08:05:56 浏览: 80
好的,很高兴为您解答。关于使用 OpenSSL 库写 AES 加解密的问题,以下是一份示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
int aes_encrypt(const unsigned char *in, int in_len, unsigned char *key, unsigned char *iv, unsigned char *out)
{
AES_KEY aes_key;
if (AES_set_encrypt_key(key, 128, &aes_key) < 0)
return -1;
AES_cbc_encrypt(in, out, in_len, &aes_key, iv, AES_ENCRYPT);
return 0;
}
int aes_decrypt(const unsigned char *in, int in_len, unsigned char *key, unsigned char *iv, unsigned char *out)
{
AES_KEY aes_key;
if (AES_set_decrypt_key(key, 128, &aes_key) < 0)
return -1;
AES_cbc_encrypt(in, out, in_len, &aes_key, iv, AES_DECRYPT);
return 0;
}
int main()
{
unsigned char key[] = "0123456789abcdef"; // 密钥必须是 16/24/32 字节
unsigned char iv[] = "1234567890abcdef"; // 向量必须是 16 字节
unsigned char in[] = "hello, world!";
unsigned char out[64];
unsigned char dec[64];
// 加密
aes_encrypt(in, strlen(in), key, iv, out);
printf("加密后的数据: %s\n", out);
// 解密
aes_decrypt(out, sizeof(out), key, iv, dec);
printf("解密后的数据: %s\n", dec);
return 0;
}
```
希望这份代码对您有所帮助。如果您还有其他问题,请继续问我吧!
阅读全文