起因
第一次使用OpenSSL库,想用用里面的算法,发现在使用AES_decrypt时会直接将解密后的内存尾部的四字节全部清0
原本这里在malloc分配内存时应该有相应的信息标志,也就是4个0xfd,但是在调用完之后会给我清空了,这就导致我直接free这块内存直接失败
解决方案与代码
既然它给我们清空了,那我们就自己修复吧,在它解密完后的字符串末尾再增加4个0xfd,于是代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define AES_KEY_SIZE 128 // AES密钥长度
#define AES_BLOCK_SIZE 16 // AES分块大小
// 加密函数
void aes_encrypt(const unsigned char* plaintext, unsigned char* ciphertext, const unsigned char* key) {
AES_KEY aes_key;
AES_set_encrypt_key(key, AES_KEY_SIZE, &aes_key);
AES_encrypt(plaintext, ciphertext, &aes_key);
}
// 解密函数
void aes_decrypt(const unsigned char* ciphertext, unsigned char* plaintext, const unsigned char* key) {
AES_KEY aes_key;
AES_set_decrypt_key(key, AES_KEY_SIZE, &aes_key);
AES_decrypt(ciphertext, plaintext, &aes_key);
}
int main() {
// 明文密码
const char* plaintext_password = "my_password";
size_t plaintext_password_len = strlen(plaintext_password);
// AES密钥
const unsigned char aes_key[] = { 0x7b, 0xf3, 0x5c, 0xd6, 0x9c, 0x47, 0x5d, 0x5e, 0x6f, 0x1d, 0x7a, 0x23, 0x18, 0x7b, 0xf9, 0x34 };
// 分配加密后的密文空间
size_t ciphertext_password_len = ((plaintext_password_len + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
unsigned char* ciphertext_password = malloc(ciphertext_password_len);
// 对明文密码进行AES加密
aes_encrypt((const unsigned char*)plaintext_password, ciphertext_password, aes_key);
// 输出加密后的密码
printf("加密后的密码:\n");
for (size_t i = 0; i < ciphertext_password_len; i++) {
printf("%02x", ciphertext_password[i]);
}
printf("\n");
// 分配解密后的明文空间
unsigned char* decrypted_password = malloc(plaintext_password_len);
// 对密文密码进行AES解密
aes_decrypt(ciphertext_password, decrypted_password, aes_key);
// 输出解密后的密码
printf("解密后的密码:%s\n", decrypted_password);
// 释放空间
free(ciphertext_password);
/* 将下面的代码注释去掉进行修复bug
for (int i = 0; i < 4; i++)
{
decrypted_password[i + plaintext_password_len] = 0xfd;
}
*/
free(decrypted_password);
system("pause");
return 0;
}