base64 decode with openssl BIO block by block

base64 decode with openssl BIO block by block

本文关键字:block by BIO openssl decode with base64      更新时间:2023-10-16

我在用以下代码中解码base64编码的数据有问题。我有大约3.5 MB的数据进行解码。它的工作原理几乎很好,直到缺少某些东西的最后。

以下代码读取100 kb源数据块,将其写入bio_s_mem,然后将数据读取的数据读取1024个字节多次。当无需阅读时,再检索并再次使用100 kb的块。直到收到最后一个块为止。它没有完整的100 kb(只有25685个字节(。我将其写给Bio,获得18次解码1024字节,然后再进行435个字节,仅此而已。但这不是全部。仍缺少大约100字节的解码数据。

所有编码数据都已正确接收(将它们保存到文件并手动从shell命令中解码提供了完整的输出(。我应该如何从简历中获得其余的?我想我应该以某种方式说这就是全部。我尝试了例如Bio_flush多种方式,一些标志,将newline添加到编码数据,尚无成功。

BIO *bmem, *b64;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
BIO_push(b64, bmem);
vector<char> buf(1024);
while (!end) {
    end = task->nextChunk(chunk, chunkSize); // this reads encoded data block
    BIO_write(bmem, (void*)chunk, chunkSize);
    cout << "Chunk size: " << chunkSize << endl;
    if (end || chunkSize == 0) {
        BIO_flush(bmem); // I tried multiple things
        BIO_flush(b64); // flush here and there, nothing helped
        BIO_set_close(bmem, BIO_CLOSE); // and other things... ;-)
    }
    string result;
    int nread;
    while ((nread = BIO_read(b64, buf.data(), buf.size())) > 0) {
        cout << "Decoded bytes read: " << nread << endl;
        result.append(buf.data(), nread);
    }
    ret->appendRaw(result.c_str(), result.size()); // store result somehow
}

最后输出序列:

Chunk size: 25685
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 1024
Decoded bytes read: 435
Chunk size: 0

再次:解码输出是二进制文件。它是正确编码的,正确发送到我的代码,但没有解码,最后一个大约100个字节丢失了。谢谢您的任何提示。

技巧是在最终的bio_read序列之前添加以下两行:

        BIO_write(bmem, "n", 1);
        BIO_set_mem_eof_return(bmem, BIO_NOCLOSE);
相关文章: