C语言如何通过AES128加密
时间: 2024-05-01 09:23:07 浏览: 9
C语言可以通过OpenSSL库来实现AES128加密。下面是一个简单的示例:
```c
#include <stdio.h>
#include <openssl/aes.h>
int main()
{
unsigned char key[] = "0123456789abcdef"; // 128位密钥
unsigned char iv[] = "1234567890abcdef"; // 128位初始化向量
unsigned char plaintext[] = "Hello world!"; // 明文
unsigned char ciphertext[AES_BLOCK_SIZE]; // 密文
AES_KEY aes_key;
// 初始化AES key
AES_set_encrypt_key(key, 128, &aes_key);
// 加密
AES_cbc_encrypt(plaintext, ciphertext, sizeof(plaintext), &aes_key, iv, AES_ENCRYPT);
// 输出密文
printf("Ciphertext: ");
for (int i = 0; i < sizeof(ciphertext); i++) {
printf("%02x ", ciphertext[i]);
}
printf("\n");
return 0;
}
```
在上面的示例中,我们使用了AES CBC模式进行加密。其中,`key`和`iv`分别是128位的密钥和初始化向量,需要根据具体的情况进行设置。`plaintext`是要加密的明文,`ciphertext`是输出的密文。`AES_key`是AES_KEY类型的结构体,用于保存加密所需的信息。
我们首先使用`AES_set_encrypt_key()`函数初始化AES key,然后使用`AES_cbc_encrypt()`函数进行加密。最后输出密文即可。