Skip to content

Instantly share code, notes, and snippets.

@BobBurns
Created December 28, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BobBurns/ec82e51a94a17cc1876c to your computer and use it in GitHub Desktop.
Save BobBurns/ec82e51a94a17cc1876c to your computer and use it in GitHub Desktop.
program to calculate the multiplicative inverse in Rijndal's Galois Feild.
#include <stdio.h>
/* program to demonstrate how to find multiplicative inverse in Rijndal's Galois Field
* part of the AES encryption algorithm or Rijndal's block cipher.
*
* code expanded on blog @ www.samiam/galois.html
*/
/* global vars */
unsigned char anti_log[256];
unsigned char glog[256];
/* functions */
unsigned char
gmul(unsigned char a, unsigned char b) {
unsigned char p = 0;
unsigned char counter;
unsigned char hi_bit_set;
for (counter = 0;counter < 8;counter++) {
if ((b & 1) == 1)
p ^= a;
hi_bit_set = (a & 0x80);
a <<= 1;
if (hi_bit_set == 0x80)
a ^= 0x1b;
b >>= 1;
}
return p;
}
int
init() {
int i;
unsigned char p;
anti_log[0]=0;
p=1;
printf("\n");
for (i = 1;i < 256; i++) {
p = gmul(p, 0xe5);
anti_log[i] = p;
}
for (i = 1;i < 257; i++) {
printf("%02x ",anti_log[i-1]);
if (i % 16 == 0)
printf("\n");
}
printf("\n");
printf("*** log table ***\n");
/* now map log table */
unsigned char temp;
glog[0] = 0;
glog[1] = 1;
for (i = 1;i < 256;i++) {
temp = anti_log[i];
glog[temp]=i;
}
glog[1]=0x00;
printf("\n");
for (i = 1;i < 257;i++) {
printf("%02x ",glog[i-1]);
if (i % 16 == 0)
printf("\n");
}
printf("\n");
}
/* main entry */
int
main() {
init();
/* try and multiply with log tables */
int a;
unsigned char result;
printf("Enter number to calculate multiplicative inverse <0x00 - 0xff>? ");
if (scanf("%x", &a) < 0) {
printf("\nincorrect usage\n");
return 1;
}
if (a > 255 || a < 0) {
printf("number between 0-ff please!\n");
return 1;
}
if (a == 0) {
result = 0;
} else {
result = anti_log[(255 - glog[a])];
}
printf("result = %x\n", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment