Question

Hi I want to find a checksum of single string. here are the requirements of checksum.

  1. 32 digit/8byte check sum represented in hexadecimal character.
  2. It should be XOR of header + session + body + message.

Lets suppose header + session + body + message = "This is test string". I want to calculate the checksum of this. So far I have developed below code.

Checksum is calculated correctly if string length(byte[] data) is multiple of 4.

If "data" is not a multiple of 4 I receive exception as

"System.IndexOutOfRangeException: Index was outside the bounds of the array".

I will be taking different inputs having different string length from user and hence the string length will be variable(means some time user can enter only ABCDE some times q and A and so on.). How can I fix this exception issue and calculate correct checksum with multiple of 4.

public string findchecksum(string userinput)
  try
    {
        ASCIIEncoding enc = new ASCIIEncoding();

        byte[] data = Encoding.ASCII.GetBytes(userinput);
        byte[] checksum = new byte[4];
        for (int i = 16; i <= data.Length - 1; i += 4)
        {


            checksum[0] = (byte)(checksum[0] ^ data[i]);
            checksum[1] = (byte)(checksum[1] ^ data[i + 1]);
            checksum[2] = (byte)(checksum[2] ^ data[i + 2]);
            checksum[3] = (byte)(checksum[3] ^ data[i + 3]);
        }

        int check = 0;
        for (int i = 0; i <= 3; i++)
        {
            int r = (Convert.ToInt32(checksum[i]));

            int c = (-(r + (1))) & (0xff);

            c <<= (24 - (i * 8));

            check = (check | c);
        }

        return check.ToString("X");
Was it helpful?

Solution

Because you use i+3 inside your loop, your array size has to always be divisible by 4. You should extend your data array to met that requirement before entering the loop:

byte[] data = Encoding.ASCII.GetBytes(cmd);
if (data.Length % 4 != 0)
{
    var data2 = new byte[(data.Length / 4 + 1) * 4];
    Array.Copy(data, data2, data.Length);
    data = data2;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top