我在一个需要我在本地执行加密和解密的架构中使用OpenSSL。
解密函数获取在连接另一端加密的缓冲区。 加密/解密过程通常可以正常工作,但对于缓冲区包含部分密码块的情况。
我想我的问题归结为: 设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)。
我有什么方法可以提前确认我有一个完整的块吗?
提前致谢
答案 0 :(得分:1)
显然解决方案在于BIO_get_mem_data。
以下内容: #define DEC_BUF_SIZE 1000000 static 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;
}