-1

I am trying to perform an Xor between a 64 bit key and a 64 bit unsigned char array and I keep getting very strange output. Is there an issue with the data type or the order of operations?

#include <iostream>

using namespace std;

int main() {
    unsigned char inputText = '7';
    unsigned char key = 'a';

    cout << "(input: 0x";
    cout << " " << inputText << ") ^ (";

    cout << "key: 0x";
    cout << " " << key << ") = ";

    cout << "0x ";
    cout << (inputText ^ key);
    cout << endl;
    return 0;
}

Here is the output:

(input: 0x 7) ^ (key: 0x a) = 0x 86

As you can see, xor is producing large integers, and no evidence that the hex values were xor'd. The correct output from xor should be:

0x d
steve
  • 119
  • 7
  • Minor, but what's the point of the `K` variable? You could eliminate it and just use `w`. – Bungo Feb 20 '21 at 04:06
  • It's part of a much larger encryption algorithm where the variables have significance – steve Feb 20 '21 at 04:08
  • I took it out for readability – steve Feb 20 '21 at 04:09
  • This doesn't address the question, but don't confound the **value** of a variable with the **representation** of that value on the screen. What you're after is simply xor-ing the **values** in the two variables. "Hex values" is how they're (sometimes) shown to the world. The compiler doesn't care whether they came in has hex, octal, text, or anything else. – Pete Becker Feb 20 '21 at 15:42
  • Yes, that did turn out to be an issue for me as I understood the solution better. Thanks Pete Becker – steve Feb 21 '21 at 03:31

1 Answers1

2

you are not xoring the hex numbers, but the ascii values of the characters.

input: '7', '3', '6', '5'

ascii: 55, 51, 54, 53

key: '0', 'f', 'f', 'a'

ascii: 48, 102, 102, 97

result: 55 ^ 48, 51 ^ 102, 54 ^ 102, 53 ^ 97

result: 7, 85, 80, 84

daseinpwt
  • 36
  • 3
  • can I fix that so it xors the hex values instead? – steve Feb 20 '21 at 04:06
  • @steve That's another question, but see [char - Hex character to int in C++ - Stack Overflow](https://stackoverflow.com/questions/6457551/hex-character-to-int-in-c) – user202729 Feb 20 '21 at 04:11
  • 1
    @steve Do you require the hex values to be stored as ascii characters? If not, the most straightforward solution would be to replace your arrays with `uint16_t inputText[4] = { 0x7365, 0x6375, 0x7269, 0x7479 };` and `uint16_t key[4] = { 0x0ffa, 0x331c, 0xc876, 0x5ddd };`. Then the xor will do what you want, and you can use the `std::hex`, `std::setw`, and `std::setfill` manipulators (or `std::printf` with the `%04x` format) to print them in the desired format. – Bungo Feb 20 '21 at 04:15
  • I tried changing the key to a different string of hex values and I got the exact same output, so it is not xoring the ascii values. – steve Feb 20 '21 at 04:23
  • @steve I suspect that it's rather because you forgot to recompile the program. – user202729 Feb 20 '21 at 04:27