C语言中,AES算法的加密
时间: 2023-11-25 22:10:33 浏览: 32
在C语言中实现AES算法的加密,通常需要使用一个AES库,如OpenSSL或mbed TLS。以下是一个使用OpenSSL库的示例代码:
```c
#include <openssl/aes.h>
int main()
{
AES_KEY key;
unsigned char plaintext[] = "Hello world!"; // 要加密的明文
unsigned char ciphertext[AES_BLOCK_SIZE]; // 存放密文的缓冲区
unsigned char aes_key[] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c};
// 128位密钥
AES_set_encrypt_key(aes_key, 128, &key); // 设置加密密钥
AES_encrypt(plaintext, ciphertext, &key); // 加密明文
// 输出密文
printf("Ciphertext: ");
for(int i = 0; i < AES_BLOCK_SIZE; i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
return 0;
}
```
此代码使用128位密钥对字符串"Hello world!"进行AES加密,并输出加密后的密文。请注意,此示例仅用于演示目的,实际上使用AES时需要更加谨慎和安全。