I made a simple program to perform Galois Finite Field Multiplication but somehow the program is stuck in a loop.
#include<stdio.h>
int GaloisMult(int a, int b){
int i,j=0,h=0,k,abits[8],bbits[8];
for (i = 0; i < 8; i++){
if(((a >> i) & 1) == 1) abits[j++] = i;
if(((b >> i) & 1) == 1) bbits[h++] = i;
}
for (i = 0; i < j; i++) printf("%d ",abits[i]);
printf("\n");
for (i = 0; i < h; i++) printf("%d ",bbits[i]);
int dbits[11] = {0};
//here
for (k = 0; k < h; k++) {
for (i = 0; i < j; i++){
int index = abits[i] + bbits[k];
dbits[index] = (dbits[index] + 1) % 2;
}
}
int val = 0;
for (i = 10; i >= 0; i--) val = (val << 1) | dbits[i];
while(val > 0xff) val ^= 0x11b;
return val;
}
int main(){
int a = 0xac;
int b = 0x0e;
printf("\n%02X * %02X = %02X",a,b,GaloisMult(a,b));
}
the program never ends somehow stuck in the 2d for loop.
So the problem was not with the for
loop but with the XOR logic in the While
loop.
the Galois Field XOR calculation goes like this, suppose we have 2 variables
11010001000
and 100011011
. then we have to perform the XOR until the resulting bits has no 1
above 8th
position.
11010001000
100011011
-----------
01011100100
the result has 1
in the 10th
position so we XOR that with the 2nd variable again but this time we remove the leading 0
.
1011100100
100011011
----------
0011010010
this time the result has no 1
above 8th
position so this is the final result we want.
the problem with doing XOR like result = a ^ b
will do
11010001000
100011011
-----------
11110010011
which doesn't work. the correct logic i implemented is this
#include<stdio.h>
int intFromBits(int bits[]){
int val = 0,i;
for (i = 0; i < 15; i++) val = (val << 1) | bits[i];
return val;
}
void xor(int d[15],int c[15],int* r){
int i=0,j=0;
while(d[i++] != 1) j++;
for (i = 0; i < 15; i++) r[i] = d[i] ^ c[(i-j+15) % 15];
}
int GaloisMult(int a, int b){
int i,j=0,h=0,k,abits[8],bbits[8],dbits[15] = {0},cons[] = {1,0,0,0,1,1,0,1,1,0,0,0,0,0,0};
for (i = 0; i < 8; i++){
if(((a >> i) & 1) == 1) abits[j++] = i;
if(((b >> i) & 1) == 1) bbits[h++] = i;
}
for (k = 0; k < h; k++) for (i = 0; i < j; i++) dbits[14 - (abits[i] + bbits[k])] = (dbits[14 - (abits[i] + bbits[k])] + 1) % 2;
while(intFromBits(dbits) > 0xFF) xor(dbits,cons,dbits);
return intFromBits(dbits);
}
int main(){
int a = 0xff;
int b = 0xff;
printf("\n%02X * %02X = %02X",a,b,GaloisMult(a,b));
}
the custom XOR function shifts the 2nd variable to adjust the trailing and leading 0s to perform the correct XOR logic required to do Galois Multiplication XOR.
Note: this GaloisMult
only works for 2^8
Fields.