使用CBC的密文链模式算法的c语言代码
时间: 2024-03-24 22:39:32 浏览: 16
以下是使用CBC模式进行加密和解密的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#define KEY_SIZE 16
#define IV_SIZE 16
void handleErrors(void);
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext);
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext);
int main(void)
{
/* 初始化OpenSSL库 */
OpenSSL_add_all_algorithms();
OPENSSL_config(NULL);
/* 输入明文和密钥 */
unsigned char plaintext[] = "Hello, World!";
unsigned char key[KEY_SIZE];
unsigned char iv[IV_SIZE];
printf("Enter the 16-byte key: ");
scanf("%s", key);
printf("Enter the 16-byte IV: ");
scanf("%s", iv);
/* 加密明文 */
int len = strlen((char *)plaintext);
unsigned char ciphertext[len + EVP_MAX_BLOCK_LENGTH];
int ciphertext_len = encrypt(plaintext, len, key, iv, ciphertext);
printf("Ciphertext is: ");
for (int i = 0; i < ciphertext_len; i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
/* 解密密文 */
unsigned char decryptedtext[len];
int decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
decryptedtext[decryptedtext_len] = '\0';
printf("Decrypted text is: %s\n", decryptedtext);
/* 清理OpenSSL库 */
EVP_cleanup();
ERR_free_strings();
return 0;
}
void handleErrors(void)
{
printf("Encryption/Decryption failed\n");
exit(1);
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* 创建并初始化Cipher上下文 */
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* 初始化加密操作 */
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv))
handleErrors();
/* 加密明文 */
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
/* 完成加密操作 */
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
/* 清理Cipher上下文 */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
/* 创建并初始化Cipher上下文 */
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* 初始化解密操作 */
if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv))
handleErrors();
/* 解密密文 */
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
/* 完成解密操作 */
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
plaintext_len += len;
/* 清理Cipher上下文 */
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
```
注:以上代码使用OpenSSL库进行加密和解密。编译时需要链接OpenSSL库,例如:
```
gcc -o cbc_encrypt_decrypt cbc_encrypt_decrypt.c -lcrypto
```