使用openssl 中的EVP库函数写一个加解密例子程序 c语言的
时间: 2024-05-02 10:19:39 浏览: 91
好的,这是一个关于加解密的技术问题,我可以回答。下面是一个简单的例子程序:
```c
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#define MAX_BUF_SIZE 1024
// 加密函数
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;
if(!(ctx = EVP_CIPHER_CTX_new())) return -1;
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
return -1;
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
return -1;
ciphertext_len = len;
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) return -1;
ciphertext_len += len;
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;
int ret;
if(!(ctx = EVP_CIPHER_CTX_new())) return -1;
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
return -1;
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
return -1;
plaintext_len = len;
ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
EVP_CIPHER_CTX_free(ctx);
if(ret > 0) {
plaintext_len += len;
return plaintext_len;
} else {
return -1;
}
}
int main() {
unsigned char plaintext[MAX_BUF_SIZE] = "Hello, world!";
unsigned char key[EVP_MAX_KEY_LENGTH] = "01234567890123456789012345678901";
unsigned char iv[EVP_MAX_IV_LENGTH] = "0123456789012345";
unsigned char ciphertext[MAX_BUF_SIZE] = {0};
unsigned char decryptedtext[MAX_BUF_SIZE] = {0};
int decryptedtext_len, ciphertext_len;
ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key, iv, ciphertext);
printf("Ciphertext is:\n");
BIO_dump_fp(stdout, (char *)ciphertext, ciphertext_len);
decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
decryptedtext[decryptedtext_len] = '\0';
printf("Decrypted text is:\n");
printf("%s\n", decryptedtext);
return 0;
}
```
这个程序使用了 OpenSSL 的 EVP 库函数,用 AES-256 CBC 算法加密和解密数据。注意,这个程序中的密钥和 IV 都是硬编码的,实际应用中应该使用更安全的方式来保存和传输密钥和 IV。
阅读全文