Search code examples
c#encryptionxor

Xor-ing two letters in C#, not symmetric


So, I have this basic encrypting function, and I'm really stuck.

String result = "";
....
result += ((char)('A' + ((message[i]) - 'A') ^ (key[j] - 'A')));

The idea is, A = 0, B = 1, C = 2, etc., and to the message with the key symbol by symbol. For some reason, if I xor 'B' and 'A', and 'A' and 'B' I get different results. Why am I getting that?


Solution

  • Addition has higher precedence than XOR. You're missing a pair of parentheses around the XOR operation.

    result += (char)('A' + ((message[i] - 'A') ^ (key[j] - 'A')));