Click here to Skip to main content
15,891,707 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have two hex strings and I need to do the XOR operation to that strings. I try with some methods but it not work well for me.

Eg:

C#
string PinBlock = "042241FFFFFFFFFF";
string CardBlock = "0000665702007894";


and the result shoud me afet XOR (Expected Result)
0422 27A8 FDFF 876B


This is what I tried so far

C#
public static string xorIt(string key, string input)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < input.Length; i++)
                sb.Append((char)(input[i] ^ key[(i % key.Length)]));
            String result = sb.ToString();

            return result;
        }

        public string ASCIITOHex(string ascii)
        {

            StringBuilder sb = new StringBuilder();

            byte[] inputBytes = Encoding.UTF8.GetBytes(ascii);

            foreach (byte b in inputBytes)
            {

                sb.Append(string.Format("{0:x2}", b));

            }

            return sb.ToString();

        }



But from this I get below result

000402020207737176747676717e7f72
Posted
Comments
Tomas Takac 13-Mar-15 4:30am    
The problem is you are XORing the char values. You need to convert them to numbers (ints) first then xor them then convert to chars (hex digit representation).

C#
string hex1 = "042241FFFFFFFFFF";
          string hex2 = "0000665702007894";
          long dec1 = Convert.ToInt64(hex1, 16);
          long dec2 = Convert.ToInt64(hex2, 16);
          long result = dec1 ^ dec2;
          string hexResult = result.ToString("X");
 
Share this answer
 
Comments
Soft009 13-Mar-15 4:31am    
Thanks a lot
Quote:
sb.Append((char)(input[i] ^ key[(i % key.Length)]));

This line is wrong: you should not XOR the hexadecimal representation of the numbers, you have to XOR their actual values.

For instance,
0xF ^ 0x3 = 0xC (good)
while
'F' ^ '3' = 0x46 ^ 0x33 = 0x75 (not so good)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900