Skip to content

Instantly share code, notes, and snippets.

@BobBurns
Created December 30, 2015 19:35
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/977c8577f67d9b7fdf86 to your computer and use it in GitHub Desktop.
Save BobBurns/977c8577f67d9b7fdf86 to your computer and use it in GitHub Desktop.
Rijndail S-box the long way
#include <stdio.h>
/* Rijndael Field S-box transformation
* part of the AES encryption algorythm 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 GF(256) <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;
}
// a = 83; /* 0x53 */
if (a == 0) {
result = 0;
} else {
result = anti_log[(255 - glog[a])];
}
printf("multiplicitave inverse = %x\n", result);
/* affine transformation the long way */
int j, i;
unsigned char r[8], p, m = 248, af = 0;
r[0] = 0;
for (j = 7;j >= 0;j--) {
r[j] = 0;
p = m & result;
for (i = 0;i < 8;i++) {
r[j] ^= ((p >> i) & 0x01);
}
m = (m >> 1) | (m << 7); /* rotate right 1 */
}
for (i = 0;i < 8;i++) {
af = af | (r[i] << i);
}
af ^= 99; /* 0x63 */
printf("affine trans = %x\n", af);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment