Search code examples
c#stringcryptographyxorbytebuffer

Byte Conversion From Hex String Keeps Failing With Alphabet characters "G" and upwards in C#


I'm trying to build a simple XOR function that decrypts a hex key from a single character. It works with multiple characters and individual characters... but only from "A" through to "F". From "G" onwards, it keeps throwing a "FormatException".

Here's the problem function, passed with two strings:

    // For Reference:
    // strHexKey = "G";
    // strHexInput = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"

    private string SCXOR_Update(string strHexKey, string strHexInput)
    {
        byte[] buffer1 = hexbuffer(strHexInput);
        byte buffer2 = Convert.ToByte(Convert.ToInt32(strHexKey, 16));
        byte[] result = buffer1;

        for (int i = 0; i < (strHexInput.Length / 2); i++)
        {
            result[i] = (byte)(buffer1[i] ^ buffer2);
        }

        return BitConverter.ToString(result).Replace("-", "");
    }

The exception is thrown at the line "byte buffer2" and only happens when advancing from the letter "G" upwards.

Any idea what it is that I'm missing? It's got to be glaring me in the face?!

Thanks in advance!


Solution

  • Hex is a base 16 counting system. It only consists of the following digits - although lowercase characters are often used as well:

    0123456789ABCDEF