aes加解密c语言实现
时间: 2023-09-04 17:08:26 浏览: 97
AES是一种高级加密标准,它是一种对称加密算法,也就是说AES加密和解密使用的是同一套算法。下面是使用C语言实现AES加解密的示例代码(使用openssl库):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define AES_BLOCK_SIZE 16
int aes_encrypt(unsigned char *in, int in_len, unsigned char *key, unsigned char *out)
{
AES_KEY aes_key;
if (AES_set_encrypt_key(key, 128, &aes_key) < 0) {
return -1;
}
int padding_len = AES_BLOCK_SIZE - (in_len % AES_BLOCK_SIZE);
int total_len = in_len + padding_len;
unsigned char *padded_in = malloc(total_len);
if (!padded_in) {
return -1;
}
memcpy(padded_in, in, in_len);
memset(padded_in + in_len, padding_len, padding_len);
for (int i = 0; i < total_len / AES_BLOCK_SIZE; i++) {
AES_encrypt(padded_in + i * AES_BLOCK_SIZE, out + i * AES_BLOCK_SIZE, &aes_key);
}
free(padded_in);
return total_len;
}
int aes_decrypt(unsigned char *in, int in_len, unsigned char *key, unsigned char *out)
{
AES_KEY aes_key;
if (AES_set_decrypt_key(key, 128, &aes_key) < 0) {
return -1;
}
for (int i = 0; i < in_len / AES_BLOCK_SIZE; i++) {
AES_decrypt(in + i * AES_BLOCK_SIZE, out + i * AES_BLOCK_SIZE, &aes_key);
}
int padding_len = out[in_len - 1];
return in_len - padding_len;
}
int main()
{
unsigned char key[16] = "0123456789abcdef";
unsigned char in[] = "hello world";
unsigned char out[256];
int len = aes_encrypt(in, strlen(in), key, out);
printf("encrypt: %s\n", out);
int out_len = aes_decrypt(out, len, key, in);
in[out_len] = '\0';
printf("decrypt: %s\n", in);
return 0;
}
```
注意,在加密时需要对输入进行padding,以保证长度是16的倍数。在解密时需要去除padding。
阅读全文