3

I'm using Cryptopp to generate a random string. This is the code:

const unsigned int BLOCKSIZE = 16 * 8;
byte pcbScratch[ BLOCKSIZE ];

// Construction
//   Using a ANSI approved Cipher
CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;

rng.GenerateBlock( pcbScratch, BLOCKSIZE );

// Output
std::cout << "The generated random block is:" << std::endl;
string str = "";

for( unsigned int i = 0; i < BLOCKSIZE; i++ )
{
    std::cout << "0x" << std::setbase(16) << std::setw(2) << std::setfill('0');
    std::cout << static_cast<unsigned int>( pcbScratch[ i ] ) << " ";
    str += pcbScratch[i];
}
std::cout << std::endl;
std::cout << str <<std::endl;

I've put int the code a new var: string str = "". Then in the for append for each result, the part of the string. But my output is dirty! I see only strange ASCII char. How can I set well the string?

Thank you.

3 Answers 3

1

You will want to some output encoding, e.g.

  • base64
  • hex

because what you are seeing is the raw binary data, interpreted as if it were text. Random characters are the consequence

AFAICT (google) you should be able to use something like this

#include <base64.h>

string base64encoded; 
StringSource(str, true, new Base64Encoder(new StringSink(base64encoded)));
1

Appending arbitrary bytes (chars) to the end of a string is going to result in that containing some non-printable characters:

http://en.wikipedia.org/wiki/Control_character

You don't mention what you wanted or expected. Did you want the string to be the same as what got sent to std::cout? If so, you can use a stringstream via #include <sstream>:

std::stringstream ss;
for( unsigned int i = 0; i < BLOCKSIZE; i++ )
{
    ss << "0x" << std::setbase(16) << std::setw(2) << std::setfill('0');
    ss << static_cast<unsigned int>(pcbScratch[i]);
}
str = ss.str();
0

You can also use Crypto++'s built in HexEncoder:

std::cout << "The generated random block is:" << std::endl;
string str = "0x";

StringSource ss(pcbScratch, BLOCKSIZE, true,
    new HexEncoder(
        new StringSink(str),
        true,   // uppercase
        2,      // grouping
        " 0x"   // separator
    ) // HexDecoder
); // StringSource

The StringSource 'owns' the HexEncoder, so there's no need to call delete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.