user2307236 user2307236 - 11 months ago 70
C# Question

XOR function for two Hex byte arrays

I am trying to perform the exclusive or of two byte arrays and return the result as a hex string. I have converted the two byte array to their corresponding binary string. Each byte will have bits since it has 8 bytes.

byte[] key = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 };
byte[] PAN = { 0x12, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x23 };

Till now I have a method that transforms the byte array into their corresponding binary string value. e.g. "10101010101". However when I perform the below method to get the XOR I am being returned with a string of bunch of smiley face which probably is some special ASCII character.

However I don't have any ideas how can I do this. I was thinking to convert the binary string to int however that not a good solution since it will not fit as an integer.
Any ideas please possibly with some sample code.

public static string exclusiveOR(string string_1, string string_2)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < string_1.Length; i++)
sb.Append((char)(string_1[i] ^ string_2[(i % string_2.Length)]));
String result = sb.ToString();

return result;

Answer Source

You are doing this correctly - your code XORs characters of the two strings, wrapping around the second one if the first one happens to be the longer one.

However, the property of XOR is such that only the bits that are different remain set in the output. Hence, when you XOR 0x11 and 0x12, you end up with 0x03, which looks like a heart when displayed on a console.