1 #include <stdio.h> 2 3 unsigned E[16] = { 1, 0xb, 9, 0xc, 0xd, 6, 0xf, 3, 0xe, 8, 7, 4, 0xa, 2, 5, 0 }; 4 unsigned Ei[16]; 5 unsigned R[16] = { 7, 0xc, 0xb, 0xd, 0xe, 4, 9, 0xf, 6, 3, 8, 0xa, 2, 5, 1, 0 }; 6 unsigned cir[8][8] = { 7 {1, 1, 4, 1, 8, 5, 2, 9 }, 8 }; 9 10 11 unsigned gf_mul(unsigned a, unsigned b) 12 { 13 unsigned r; 14 15 r = 0; 16 while (a) { 17 if (a & 1) r ^= b; 18 a >>= 1; 19 b = (b << 1) ^ (b & 0x80 ? 0x11d : 0x00); 20 } 21 return r; 22 } 23 24 unsigned sbox(unsigned x) 25 { 26 unsigned a, b, w; 27 28 a = x >> 4; 29 b = x & 15; 30 31 a = E[a]; b = Ei[b]; 32 w = a ^ b; w = R[w]; 33 a = E[a ^ w]; b = Ei[b ^ w]; 34 35 36 return (a << 4) | b; 37 } 38 39 int main(void) 40 { 41 unsigned x, y; 42 43 for (x = 0; x < 16; x++) Ei[E[x]] = x; 44 45 // for (x = 0; x < 16; x++) printf("%2x ", sbox(x)); 46 for (y = 1; y < 8; y++) { 47 for (x = 0; x < 8; x++) { 48 cir[y][x] = cir[y-1][(x-1)&7]; 49 } 50 } 51 52 /* 53 printf("\n"); 54 for (y = 0; y < 8; y++) { 55 for (x = 0; x < 8; x++) printf("%2d ", cir[y][x]); 56 printf("\n"); 57 } 58 */ 59 60 for (y = 0; y < 8; y++) { 61 printf("static const ulong64 sbox%d[] = {\n", y); 62 for (x = 0; x < 256; ) { 63 printf("CONST64(0x%02x%02x%02x%02x%02x%02x%02x%02x)", 64 gf_mul(sbox(x), cir[y][0]), 65 gf_mul(sbox(x), cir[y][1]), 66 gf_mul(sbox(x), cir[y][2]), 67 gf_mul(sbox(x), cir[y][3]), 68 gf_mul(sbox(x), cir[y][4]), 69 gf_mul(sbox(x), cir[y][5]), 70 gf_mul(sbox(x), cir[y][6]), 71 gf_mul(sbox(x), cir[y][7])); 72 if (x < 255) printf(", "); 73 if (!(++x & 3)) printf("\n"); 74 } 75 printf("};\n\n"); 76 } 77 78 printf("static const ulong64 cont[] = {\n"); 79 for (y = 0; y <= 10; y++) { 80 printf("CONST64(0x"); 81 for (x = 0; x < 8; x++) { 82 printf("%02x", sbox((8*y + x)&255)); 83 } 84 printf("),\n"); 85 } 86 printf("};\n\n"); 87 return 0; 88 89 } 90 91 92 93 /* $Source: /cvs/libtom/libtomcrypt/notes/etc/whirlgen.c,v $ */ 94 /* $Revision: 1.2 $ */ 95 /* $Date: 2005/05/05 14:35:58 $ */ 96