Вопрос

I am using Crypto++ for other encryption needs; however, I also need to store binary information as ascii text. To do that I have synthesized examples of Crypto++'s base 64 filter into the following block of code.

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.
}

The problem I'm having is that after this operation temp_str is still filled with garbage. I have looked around, and cannot find any examples that do anything other than what I've done above. Is there something I'm missing?

Это было полезно?

Решение

CryptoPP::ArraySource is a typedef of CryptoPP::StringSource. The signature of StringSource's relevant constructor is:

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

So your third argument which is a pointer to a CryptoPP::Base64Encoder is being cast to a bool, and the fourth argument is the default NULL.

To resolve this, just do:

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

Другие советы

The problem I'm having is that after this operation temp_str is still filled with garbage.

Its actually unintialized data as Fraser pointed out.

The Crypto++ wiki has a page covering the topic at Missing Data.


You can also avoid the size calculation and buffer management with:

string base64;
CryptoPP::ArraySource as(buffer, length, true,
    new CryptoPP::Base64Encoder(
        new CryptoPP::StringSink(base64)));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top