3

我正在使用 Crypto++ 来满足其他加密需求;但是,我还需要将二进制信息存储为 ascii 文本。为此,我将 Crypto++ 的 base 64 过滤器的示例合成到以下代码块中。

bool saveData(const unsigned char * buffer, size_t length)
{

    int lenb64 = (ceil(length / 3.0) * 4) + 1;
    unsigned char * temp_str = (unsigned char *)malloc(lenb64);

    CryptoPP::ArraySource as(buffer, length, new CryptoPP::Base64Encoder(
        new CryptoPP::ArraySink(temp_str, lenb64)));

    //do something with temp_str.
    free(temp_str); //Then free the tempstr.
    //Return true if do something worked, else false.
}

我遇到的问题是,在此操作之后 temp_str 仍然充满垃圾。我环顾四周,除了我上面所做的之外,找不到任何其他示例。有什么我想念的吗?

4

2 回答 2

2

CryptoPP::ArraySource是一个typedef。的相关构造函数CryptoPP::StringSource的签名是:StringSource

StringSource(const byte *string,
             size_t length,
             bool pumpAll,
             BufferedTransformation *attachment=NULL);

因此,作为指向 a 的指针的第三个参数CryptoPP::Base64Encoder被强制转换为 a bool,而第四个参数是默认值NULL

要解决此问题,只需执行以下操作:

CryptoPP::ArraySource(buffer, length, true,
    new CryptoPP::Base64Encoder(
        new CryptoPP::ArraySink(temp_str, lenb64)));
于 2013-09-30T19:12:39.487 回答
0

我遇到的问题是,在此操作之后 temp_str 仍然充满垃圾。

正如弗雷泽指出的那样,它实际上是未初始化的数据。

Crypto++ wiki 在Missing Data有一个涵盖该主题的页面。


您还可以通过以下方式避免大小计算和缓冲区管理:

string base64;
CryptoPP::ArraySource as(buffer, length, true,
    new CryptoPP::Base64Encoder(
        new CryptoPP::StringSink(base64)));
于 2015-05-02T21:32:19.043 回答