tags:

views:

74

answers:

2

There is a function in the AES algorithm, to multiply a byte by 2 in Galois Field.

This is the function given in a website

private static byte gfmultby02(byte b)
    {
      if (b < 0x80)
        return (byte)(int)(b <<1);
      else
        return (byte)( (int)(b << 1) ^ (int)(0x1b) );
    }

This is the function i wrote.

private static byte MulGF2(byte x)
            {
            if (x < 0x80)
                return (byte)(x << 1);
            else
            {
                return (byte)((x << 1) ^ 0x1b);

            }

}

What i need to know is, given any byte whether this will perform in the same manner. Actually I am worried about the extra cast to int and then again to byte. So far I have tested and it looks fine. Does the extra cast to int and then to byte make a difference in rare cases?

+1  A: 

I think it's correct, but:

The best way to make sure is to simply test it; there are only 256 cases and it shouldn't take many minutes to write the test case.

unwind
Unless big-endian/little-endian makes a difference?
Dan McGrath
@Dan McG: Nope, this is all in direct calculations, on byte-sized data even. No endianness issues should affect the results here.
unwind
Indeed, I just threw it on a Solaris/Sparc and an Linux/Intel box with c++ it both behaved exactly the same.
Dan McGrath
+2  A: 

I think in this case the cast to int does nothing, cause the cast is done after the left shift. So let's take a little example:

byte b = 0x1000;

//temp1 == 0x00000000;
int temp1 = (int)(b << 1);
//temp2 == 0x00010000;
int temp2 = ((int)b) << 1);

So as you can see the parentheses have a big impact on the result, but if took the formula from the website right, your code should behave the same.

Oliver