使用c语言实现aes-cbc模式的加解密
时间: 2023-09-16 19:13:35 浏览: 256
C语言 实现AES-CBC-128-ZeroPadding 加解密算法 完整可编译工程
以下是使用 OpenSSL 库实现 AES-CBC 加解密的示例代码。请注意,此示例仅用于学习目的,不适用于生产环境。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define AES_BLOCK_SIZE 16
void print_hex(unsigned char *buf, int len) {
for(int i = 0; i < len; i++) {
printf("%02x ", buf[i]);
}
printf("\n");
}
void aes_encrypt_cbc(unsigned char *key, unsigned char *iv, unsigned char *in, unsigned char *out, size_t len) {
AES_KEY aes_key;
AES_set_encrypt_key(key, 128, &aes_key);
AES_cbc_encrypt(in, out, len, &aes_key, iv, AES_ENCRYPT);
}
void aes_decrypt_cbc(unsigned char *key, unsigned char *iv, unsigned char *in, unsigned char *out, size_t len) {
AES_KEY aes_key;
AES_set_decrypt_key(key, 128, &aes_key);
AES_cbc_encrypt(in, out, len, &aes_key, iv, AES_DECRYPT);
}
int main() {
unsigned char key[] = "0123456789abcdef";
unsigned char iv[] = "fedcba9876543210";
unsigned char plaintext[] = "Hello, world!";
int plaintext_len = strlen((char *)plaintext);
int padded_len = plaintext_len + (AES_BLOCK_SIZE - (plaintext_len % AES_BLOCK_SIZE));
unsigned char *ciphertext = malloc(padded_len);
unsigned char *decryptedtext = malloc(padded_len);
memset(ciphertext, 0, padded_len);
memset(decryptedtext, 0, padded_len);
aes_encrypt_cbc(key, iv, plaintext, ciphertext, padded_len);
printf("Ciphertext: ");
print_hex(ciphertext, padded_len);
aes_decrypt_cbc(key, iv, ciphertext, decryptedtext, padded_len);
decryptedtext[plaintext_len] = '\0';
printf("Decryptedtext: %s\n", decryptedtext);
free(ciphertext);
free(decryptedtext);
return 0;
}
```
在运行此程序之前,请确保已经安装 OpenSSL 库,并使用以下命令进行编译:
```bash
gcc -o aes-cbc aes-cbc.c -lssl -lcrypto
```
然后,您可以使用以下命令运行程序:
```bash
./aes-cbc
```
输出应该类似于以下内容:
```
Ciphertext: 02 2f d8 84 3d a2 2c 83 7b 44 80 4a 9c 5f 13 48
Decryptedtext: Hello, world!
```
阅读全文