-1

There is a ciphertext without any extension which has 32 bytes size. Therefore, I can get its hex values with hex editor, and its hex values are;

a3 0b 35 8f 14 4e fe 5e 27 5a bd 8c 53 8b a0 cb ae da d3 fc 87 8b 51 0b d6 37 3e 91 86 9f f3 c9

I tried to read these values from ciphertext with my code which is,

ifstream stream;
unsigned char c;
char arr[2];
char cipherhex[65];
int i=0;
stream.open("ciphertext2");
while (!stream.eof()) {
    stream >> c;
    sprintf(arr, "%02x", c);
    cout << arr[0] << arr[1] << " ";
    cipherhex[i] = arr[0];
    cipherhex[i+1] = arr[1];
    i += 2;
}

However, when I run this code, although there is a condition for 0x kind of hex values, it can read these hex values;

a3 35 8f 14 4e fe 5e 27 5a bd 8c 53 8b a0 cb ae da d3 fc 87 8b 51 d6 37 3e 91 86 9f f3 c9 c9

The code cannot read 0b, 09, 0c , but for different ciphertexts it can read 03 or 0e . I could not understand how it can read 03 and 0e but cannot 09 or 0b. Thanks in advance.

Generally, there is no problem with reading hex values, but there is problem with reading specific values that I mentioned above.

finesttea
  • 19
  • 6

1 Answers1

0

Your code has several mistakes in it:

  • not opening the file in binary mode.

  • using operator>> to read formatted characters, which ignores whitespace characters.

  • not allocating enough memory for arr[], causing a buffer overflow in sprintf().

  • using !eof() as your loop condition.

  • not null-terminating cipherhex after reading is done (optional).

Try this instead:

ifstream stream;
char c, arr[3], cipherhex[65];
int cypherhexlen = 0;
stream.open("ciphertext2");
while ((cypherhexlen < 64) && stream.get(c)) {
    sprintf(arr, "%02x", static_cast<unsigned char>(c));
    cout << arr[0] << arr[1] << " ";
    cipherhex[cypherhexlen] = arr[0];
    cipherhex[cypherhexlen+1] = arr[1];
    cypherhexlen += 2;
}
cipherhex[cypherhexlen] = '\0';
// use cipherhex as needed...

Alternatively, I would opt for something more like this instead:

ifstream stream;
unsigned char cipher[32];
stream.open("ciphertext2");
stream.read(reinterpret_cast<char*>(cipher), 32);
int cypherlen = stream.gcount();
for(int i = 0; i < cypherlen; ++i) {
    cout << hex << noshowbase << setw(2) << cipher[i] << " ";
}
// use cipher as needed...
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620