c语言实现 aes-128 cbc 加密
时间: 2023-08-08 14:09:57 浏览: 265
好的,下面是示例代码,使用 OpenSSL 库进行 AES-CBC 加密和解密:
加密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
void aes_encrypt_cbc(const unsigned char *plaintext, int plaintext_len,
const unsigned char *key, const unsigned char *iv,
unsigned char *ciphertext) {
AES_KEY aes_key;
AES_set_encrypt_key(key, 128, &aes_key);
AES_cbc_encrypt(plaintext, ciphertext, plaintext_len, &aes_key, iv, AES_ENCRYPT);
}
int main() {
const unsigned char *plaintext = (const unsigned char *)"待加密的明文";
const unsigned char *key = (const unsigned char *)"密钥";
const unsigned char *iv = (const unsigned char *)"初始化向量";
unsigned char ciphertext[AES_BLOCK_SIZE * ((strlen((const char *)plaintext) + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE)];
memset(ciphertext, 0, sizeof(ciphertext));
aes_encrypt_cbc(plaintext, strlen((const char *)plaintext), key, iv, ciphertext);
printf("加密结果:");
for (int i = 0; i < sizeof(ciphertext); i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
return 0;
}
```
解密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
void aes_decrypt_cbc(const unsigned char *ciphertext, int ciphertext_len,
const unsigned char *key, const unsigned char *iv,
unsigned char *plaintext) {
AES_KEY aes_key;
AES_set_decrypt_key(key, 128, &aes_key);
AES_cbc_encrypt(ciphertext, plaintext, ciphertext_len, &aes_key, iv, AES_DECRYPT);
}
int main() {
const unsigned char *ciphertext = (const unsigned char *)"待解密的密文";
const unsigned char *key = (const unsigned char *)"密钥";
const unsigned char *iv = (const unsigned char *)"初始化向量";
unsigned char plaintext[AES_BLOCK_SIZE * ((strlen((const char *)ciphertext) + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE)];
memset(plaintext, 0, sizeof(plaintext));
aes_decrypt_cbc(ciphertext, strlen((const char *)ciphertext), key, iv, plaintext);
printf("解密结果:%s\n", plaintext);
return 0;
}
```
需要注意的是,以上代码使用的是 CBC 模式和 PKCS7 填充方式。同时,需要在编译时链接 OpenSSL 库,可以使用以下命令进行编译:
```
gcc aes_cbc_encrypt.c -o aes_cbc_encrypt -lcrypto
gcc aes_cbc_decrypt.c -o aes_cbc_decrypt -lcrypto
```
其中,`-lcrypto` 参数表示链接 OpenSSL 库。
阅读全文
相关推荐













