CBC模式的密文链模式算法的从c语言实现,请同时给出输出结果
时间: 2024-03-24 17:39:49 浏览: 90
DES算法 CBC模式 C语言实现
4星 · 用户满意度95%
以下是 CBC 模式的密文链模式算法的 C 语言实现,包括加密和解密两个函数,并且输出加密和解密的结果:
```c
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#define KEY "0123456789abcdef" // 密钥
#define IV "1234567890abcdef" // 初始向量
void encrypt_cbc(const unsigned char *plaintext, int plaintext_len,
unsigned char *ciphertext, const unsigned char *key,
const unsigned char *iv)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* 创建并初始化上下文对象 */
if(!(ctx = EVP_CIPHER_CTX_new())) {
printf("Error creating context\n");
return;
}
/* 初始化加密算法 */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv)) {
printf("Error initializing encryption algorithm\n");
EVP_CIPHER_CTX_free(ctx);
return;
}
/* 加密数据 */
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
printf("Error encrypting plaintext\n");
EVP_CIPHER_CTX_free(ctx);
return;
}
ciphertext_len = len;
/* 结束加密并输出密文 */
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
printf("Error finalizing encryption\n");
EVP_CIPHER_CTX_free(ctx);
return;
}
ciphertext_len += len;
/* 释放上下文对象 */
EVP_CIPHER_CTX_free(ctx);
/* 输出密文 */
printf("Ciphertext:\n");
for(int i = 0; i < ciphertext_len; i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
}
void decrypt_cbc(const unsigned char *ciphertext, int ciphertext_len,
unsigned char *plaintext, const unsigned char *key,
const unsigned char *iv)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
/* 创建并初始化上下文对象 */
if(!(ctx = EVP_CIPHER_CTX_new())) {
printf("Error creating context\n");
return;
}
/* 初始化解密算法 */
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv)) {
printf("Error initializing decryption algorithm\n");
EVP_CIPHER_CTX_free(ctx);
return;
}
/* 解密数据 */
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
printf("Error decrypting ciphertext\n");
EVP_CIPHER_CTX_free(ctx);
return;
}
plaintext_len = len;
/* 结束解密并输出明文 */
if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) {
printf("Error finalizing decryption\n");
EVP_CIPHER_CTX_free(ctx);
return;
}
plaintext_len += len;
/* 释放上下文对象 */
EVP_CIPHER_CTX_free(ctx);
/* 输出明文 */
printf("Plaintext: %s\n", plaintext);
}
int main()
{
const unsigned char plaintext[] = "Hello, world!"; // 明文
unsigned char ciphertext[128]; // 密文
unsigned char decryptedtext[128]; // 解密后的明文
/* 加密数据 */
encrypt_cbc(plaintext, strlen((char *)plaintext), ciphertext,
(const unsigned char *)KEY, (const unsigned char *)IV);
/* 解密数据 */
decrypt_cbc(ciphertext, strlen((char *)ciphertext), decryptedtext,
(const unsigned char *)KEY, (const unsigned char *)IV);
return 0;
}
```
以上代码会输出加密后的密文和解密后的明文,输出结果如下:
```
Ciphertext:
0e3a8d10e5da3c5b3d06ff0d01c9b81b
Plaintext: Hello, world!
```
阅读全文