#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/aes.h>
unsigned char* aes_encrypt(unsigned char* key, unsigned char* iv, unsigned char* plaintext, int plaintext_len, int* ciphertext_len) {
EVP_CIPHER_CTX* ctx;
unsigned char* ciphertext;
int len;
int ciphertext_len_local;
// 創建並初始化加密上下文
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv);
// 分配輸出緩沖區
ciphertext = (unsigned char*)malloc(plaintext_len + AES_BLOCK_SIZE);
// 加密數據
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len);
ciphertext_len_local = len;
// 結束加密操作
EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
ciphertext_len_local += len;
// 釋放加密上下文
EVP_CIPHER_CTX_free(ctx);
// 返回密文和密文長度
*ciphertext_len = ciphertext_len_local;
return ciphertext;
}
unsigned char* aes_decrypt(unsigned char* key, unsigned char* iv, unsigned char* ciphertext, int ciphertext_len, int* plaintext_len) {
EVP_CIPHER_CTX* ctx;
unsigned char* plaintext;
int len;
int plaintext_len_local;
// 創建並初始化解密上下文
ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv);
// 分配輸出緩沖區
plaintext = (unsigned char*)malloc(ciphertext_len);
// 解密數據
EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len);
plaintext_len_local = len;
// 結束解密操作
EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
plaintext_len_local += len;
// 釋放解密上下文
EVP_CIPHER_CTX_free(ctx);
// 返回明文和明文長度
*plaintext_len = plaintext_len_local;
return plaintext;
}
int main() {
// 密鑰和IV
unsigned char* key = (unsigned char*)"0123456789012345";
unsigned char* iv = (unsigned char*)"0123456789012345";
// 明文
unsigned char* plaintext = (unsigned char*)"hello, world";
int plaintext_len = strlen((char*)plaintext);
// 加密操作
int ciphertext_len;
unsigned char* ciphertext = aes_encrypt(key, iv, plaintext, plaintext_len, &ciphertext_len);
// 輸出密文
printf("ciphertext: ");
for (int i = 0; i < ciphertext_len; i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
// 解密操作
int plaintext_len2;
unsigned char* plaintext2 = aes_decrypt(key, iv, ciphertext, ciphertext_len, &plaintext_len2);
// 輸出明文
printf("plaintext: %s\n", plaintext2);
// 釋放內存
free(ciphertext);
free(plaintext2);
return 0;
}
需要註意的是,上述代碼只是壹個大致的實現思路,實際應用時還需要根據具體情況進行修改和優化。