c++ - OpenSSL 内存 BIO 和部分密码 block

标签 c++ encryption openssl

我在需要我在本地执行加密和解密的架构中使用 OpenSSL。

解密函数获得一个缓冲区,该缓冲区在连接的另一端被加密。 加密/解密过程通常工作正常,但对于缓冲区包含部分密码 block 的情况。

我想我的问题归结为: 令 s 为 SSL 对象,buf 为内存缓冲区或加密数据。 我为解密它所做的工作(减去错误处理、线程安全、内存安全等)是按照

int decDataBufSize = 1000000; //approximation of length of decrypted data
int8_t* decData = (int8_t*)malloc(decDataBufSize*sizeof(int8_t)); //room for the decrypted data to be written into
BIO* bio = BIO_new_mem_buf(encData, decDataBufSize); //set up BIO pointing to the encrypted data
int decDataLength;
BIO_set_close(bio, BIO_NOCLOSE); //This means OpenSSL doesn't try to free the encrypted data buffer
int totalDecData = 0;
for(int remaining_length = buffie->getBuffer()->limit() ; remaining_length > 0 ; )
{
    SSL_set_bio(ssl, bio, bio);
    remaining_length -= BIO_pending(bio);
    int decDataLength = SSL_read(ssl, decData + totalDecData, decDataBufSize - totalDecData);
    totalDecData += decDataLength;
    remaining_length += BIO_pending(bio);
}
return decData;

这似乎工作正常,但对于我在缓冲区中有一部分块的情况。 我知道,如果我使用套接字而不是内存 BIO,我会得到一个 SSL_ERROR_WANT_READ,但在我的例子中,我得到一个最简洁的 SSL_ERROR_SSL(解密失败或错误记录 mac)。

有什么方法可以提前验证我是否有一个完整的 block ?

提前致谢

最佳答案

显然,解决方案在于 BIO_get_mem_data。

大致是这样的: #define DEC_BUF_SIZE 1000000 静态 int buffer_length; static int8_t* partial_block;

int8_t* decrypt(int8_t* ecnData) { 
    int decDataBufSize = 1000000; //approximation of length of decrypted data
    int8_t* decData = (int8_t*)malloc(decDataBufSize*sizeof(int8_t)); //room for the decrypted data to be written into
    if (buffer_length == 0) /*prepend the contents of partial_block to encData somehow*/;
    BIO* bio = BIO_new_mem_buf(encData, decDataBufSize); //set up BIO pointing to the encrypted data
    int decDataLength;
    BIO_set_close(bio, BIO_NOCLOSE); //This means OpenSSL doesn't try to free the encrypted data buffer
    int totalDecData = 0;
    for(int remaining_length = buffie->getBuffer()->limit() ; remaining_length > 0 ; ) {
        buffer_length = BIO_get_mem_data(bio,&partial_block);
        SSL_set_bio(ssl, bio, bio);
        remaining_length -= BIO_pending(bio);
        int decDataLength = SSL_read(ssl, decData + totalDecData, decDataBufSize - totalDecData);
        totalDecData += decDataLength;
        remaining_length += BIO_pending(bio);
    }
return decData;
}

关于c++ - OpenSSL 内存 BIO 和部分密码 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627333/

相关文章:

c# - 如何正确地将长生命周期缓冲区从 C# 发送到 C++

bash - 暴力破解 16 个字符的 key 需要多长时间

encryption - "key container"到底是什么?

c - 如何在 openssl 中将证书文件转换为 const char certBuffer[CERTIFICATE_SIZE]?

java - PrivateKey由 OpenSSL 生成为 RSACRTPrivateKey 对象

vector 的 C++ 初始化

c++ - Boost 堆栈跟踪不显示函数名称和行号

C++如何在不使用排序的情况下打印大小为n的数组中的最小数字

C# 和 C++ 套接字数据加密

google-cloud-platform - Google 负载均衡器拒绝自签名证书