Encryption openssl中的Malloc

Encryption openssl中的Malloc,encryption,openssl,malloc,aes,free,Encryption,Openssl,Malloc,Aes,Free,使用aes加密对数据进行加密时遇到问题。 这是源代码: std::string aes_encrypt( std::string text, std::string password ){ EVP_CIPHER_CTX ectx; std::string key = sha256(password); std::string iv = sha256("aes_iv_"+password); int size = text.size(); unsig

使用aes加密对数据进行加密时遇到问题。 这是源代码:

    std::string aes_encrypt( std::string text, std::string password ){
    EVP_CIPHER_CTX ectx;
    std::string key = sha256(password);
    std::string iv = sha256("aes_iv_"+password);
    int size = text.size();
    unsigned char* out = (unsigned char*)malloc( size );
    int outlen = 0;
    int tlen = 0;

    EVP_CIPHER_CTX_init( &ectx );
    EVP_EncryptInit( &ectx, EVP_aes_256_cbc(), (const unsigned char*)key.c_str(), (const unsigned char*)iv.c_str() );
    EVP_EncryptUpdate( &ectx, out, &outlen, (const unsigned char*)text.c_str(), text.size() );
    tlen += outlen;
    EVP_EncryptFinal( &ectx, out+tlen, &outlen );
    tlen += outlen;
    EVP_CIPHER_CTX_cleanup( &ectx );

    std::string data( (const char*)out, tlen );
    free( out );
    return data;
}
我的应用程序将在以下行崩溃:free(out);
有解决此问题的方法吗?

在“out=(unsigned char*)malloc(size)”行中,您假设输出永远不会比输入长。事实并非如此(openssl文档说您必须添加块大小之类的内容),因此我相信在加密过程中,malloc’ed缓冲区中存在缓冲区溢出,这会导致空闲时崩溃(…)调用——当您通过溢出malloc缓冲区来破坏malloc/空闲数据结构时,这是非常常见的事情。

您需要检查
malloc
的返回值。如果为空,则分配失败。另外,您不需要强制转换结果。另外,您要将加密的结果存储在
std::string
?如果加密缓冲区中间有一个空字节,会发生什么情况?我不确定,但是我认为构造器将停止复制字节。@ JonathonReinhart,这是C++,我认为你需要在这种情况下进行转换。我知道这在C.paxdiablo中是不明智的。啊,你可能是对的。妈的,我就不投了!OpenSSL在处理这个缓冲区时确实非常棘手。建议超额分配。对我来说,即使是双倍的长度也不够!