c语言实现AES加密解密算法
时间: 2023-08-13 20:05:31 浏览: 187
C语言实现AES加密解密算法可以使用现成的库,也可以自己实现。下面是一个使用OpenSSL库实现AES加密解密的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define 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 len = in_len;
unsigned char *padding = NULL;
if (len % BLOCK_SIZE != 0) {
padding = (unsigned char *)malloc(BLOCK_SIZE - len % BLOCK_SIZE);
memset(padding, BLOCK_SIZE - len % BLOCK_SIZE, BLOCK_SIZE - len % BLOCK_SIZE);
len += BLOCK_SIZE - len % BLOCK_SIZE;
}
int i = 0;
while (i < len) {
AES_encrypt(in + i, out + i, &aes_key);
i += BLOCK_SIZE;
}
if (padding != NULL) {
memcpy(out + len - BLOCK_SIZE, padding, BLOCK_SIZE - len % BLOCK_SIZE);
free(padding);
}
return 0;
}
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;
}
int len = in_len;
unsigned char *padding = NULL;
if (len % BLOCK_SIZE != 0) {
return -1;
}
int i = 0;
while (i < len) {
AES_decrypt(in + i, out + i, &aes_key);
i += BLOCK_SIZE;
}
return 0;
}
int main() {
unsigned char in[] = "Hello, world!";
unsigned char key[] = "0123456789abcdef";
unsigned char out[32] = {0};
aes_encrypt(in, strlen(in), key, out);
unsigned char dec[32] = {0};
aes_decrypt(out, 16, key, dec);
printf("in: %s\n", in);
printf("out: ");
for (int i = 0; i < 16; i++) {
printf("%02x", out[i]);
}
printf("\n");
printf("dec: %s\n", dec);
return 0;
}
```
在上面的代码中,使用了OpenSSL库提供的AES加密解密函数。需要注意的是,加密的数据长度必须为16的倍数,如果不足16个字节,需要进行填充。在示例中,使用了简单的尾部填充方式。另外,密钥长度为128位,可以根据需要进行修改。
阅读全文