openssl 各版本下载
https://openssl-library.org/source/old/index.html
#include <stdio.h>
#include <string.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#define AES_KEY_BITS 128
#define GCM_IV_SIZE 12
#define GCM_TAG_SIZE 16
int aes_cbc_encrypt(const unsigned char *plaintext,
int plaintext_len, const unsigned char *aad,
int aad_len, const unsigned char *key,
unsigned char *ciphertext, unsigned char *tag)
{
EVP_CIPHER_CTX *ctx = NULL;
int len = 0;
int ciphertext_len = 0;
// 创建并初始化 EVP_CIPHER_CTX 对象
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, NULL, NULL);
// 设置加密密钥
EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL);
// 加密明文数据
if (EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len) > 0)
{
ciphertext_len = len;
}
else
{
printf("Error! \n");
}
// 结束加密过程,并生成认证标签
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
ciphertext_len += len;
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, GCM_TAG_SIZE, tag);
// 释放EVP_CIPHER_CTX对象
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int aes_cbc_decrypt(const unsigned char *ciphertext,
int ciphertext_len, const