Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encoding fails

Tags:

c++

crypto++

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?

like image 782
john-charles Avatar asked Feb 20 '26 12:02

john-charles


1 Answers

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)));
like image 192
Fraser Avatar answered Feb 23 '26 01:02

Fraser