实现AES-256-CBC的C语言代码
时间: 2023-12-25 20:03:07 浏览: 211
golang实现aes-256-cbc
下面是一个使用C语言实现AES-256-CBC加密和解密的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
void encryptAES_CBC(const unsigned char *plaintext, const unsigned char *key, const unsigned char *iv, unsigned char *ciphertext, size_t length) {
AES_KEY aesKey;
AES_set_encrypt_key(key, 256, &aesKey);
AES_cbc_encrypt(plaintext, ciphertext, length, &aesKey, iv, AES_ENCRYPT);
}
void decryptAES_CBC(const unsigned char *ciphertext, const unsigned char *key, const unsigned char *iv, unsigned char *plaintext, size_t length) {
AES_KEY aesKey;
AES_set_decrypt_key(key, 256, &aesKey);
AES_cbc_encrypt(ciphertext, plaintext, length, &aesKey, iv, AES_DECRYPT);
}
int main() {
const unsigned char *plaintext = (unsigned char *)"Hello World!";
const unsigned char *key = (unsigned char *)"0123456789abcdef0123456789abcdef";
const unsigned char *iv = (unsigned char *)"1234567890abcdef";
size_t length = strlen((const char *)plaintext);
unsigned char ciphertext[length];
encryptAES_CBC(plaintext, key, iv, ciphertext, length);
printf("Ciphertext: ");
for (size_t i = 0; i < length; i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
unsigned char decrypted[length];
decryptAES_CBC(ciphertext, key, iv, decrypted, length);
printf("Decrypted: %s\n", decrypted);
return 0;
}
```
请确保您已经安装了OpenSSL库,并使用以下命令编译和运行代码:
```
gcc -o aes aes.c -lssl -lcrypto
./aes
```
这段代码使用了OpenSSL库中的函数来实现AES-256-CBC加密和解密。它首先定义了两个函数`encryptAES_CBC`和`decryptAES_CBC`,分别用于加密和解密操作。然后在`main`函数中,设置了明文、密钥、初始化向量(IV)和明文长度,并调用`encryptAES_CBC`函数进行加密,并打印出密文。接着,调用`decryptAES_CBC`函数进行解密,并打印出解密后的明文。
注意:这只是一个简单的示例,实际应用中需要更多的错误处理和安全考虑。
阅读全文