关于OpenSSL1.1.1版本AES_decrypt奇怪问题

文章讨论了在使用OpenSSL库中的AES_decrypt函数时遇到的问题,即解密后内存尾部四字节被清零,这导致free操作失败。为了解决这个问题,作者在解密后手动在字符串末尾添加了4个0xfd,以恢复内存的正确状态,从而成功释放内存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

起因

第一次使用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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值