-3

This is a simple question I think. I'm messing around with the Crypto++ lib and a sample which I found on SO. So I tried to cout the text/ASCII characters (instead of hex) at the "Dump cipher text" part.

This part (original):

//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

for( int i = 0; i < ciphertext.size(); i++ ) {

    std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
}

std::cout << std::endl << std::endl;

And I've noticed something odd... the ciphertext.size() returns a different number of bytes after I tried to do this:

My edited part:

//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl; // returns 16 bytes.

int num = ciphertext.size(); // num returns 16 here

for (int i = 0; i < ciphertext.size(); i++) {

    std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
}

std::cout << std::endl << std::endl;

std::cout << "Ciphertext size: " << ciphertext.size() << std::endl; // now it's 10 bytes?

std::cout << "num: " << num; // returns 10 bytes?! what the hell...

std::cout << std::endl << std::endl;

So I bumped into this because I tried to print the ASCII characters instead of the hex bytes, and it worked but I just can't understand why...

Because this:

std::cout << "To Text: ";
for (int x = 0; x < ciphertext.size(); x++)
{
    std::cout << ciphertext[x];
}

Prints all the ASCII chars (instead of hex), but... since ciphertext.size() returns 10, it shouldn't print all the chars (because it was first defined as 16 instead of 10) but yet, it does print them all perfectly.... I'm really confused here. How can a variable redefine itself EVEN if I placed/copied it in a int to make sure it doesn't get changed?

jww
  • 97,681
  • 90
  • 411
  • 885
user5062925
  • 75
  • 10

2 Answers2

2

std::hex changes the base used to represent the numbers to 16 (hex). All the numbers inserted into std::cout after std::cout << std::hex are represented in base 16.

ciphertext.size() still returns 16 but, because of the std::hex previously sent to output, it is displayed in base 16 and its hex representation is, of course, 10.

Try this:

std::cout << std::dec << "Ciphertext size: " << ciphertext.size() << std::endl;

It sets 10 as base for numbers representation again and makes the value returned by ciphertext.size() to be displayed as 16.

axiac
  • 68,258
  • 9
  • 99
  • 134
1

Encryption output is binary bytes with values ranging from 0 to 255. ASCII printable characters range from 32 to 127. Perhaps you can see the problem at this point.

Not all byte values are representable in ASCII, not even extended ASCII or unicode, that is why Hexadecimal and Base64 are used for encrypted output.

See ASCII character values.

zaph
  • 111,848
  • 21
  • 189
  • 228