whirlgen.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <stdio.h>
  2. unsigned E[16] = { 1, 0xb, 9, 0xc, 0xd, 6, 0xf, 3, 0xe, 8, 7, 4, 0xa, 2, 5, 0 };
  3. unsigned Ei[16];
  4. unsigned R[16] = { 7, 0xc, 0xb, 0xd, 0xe, 4, 9, 0xf, 6, 3, 8, 0xa, 2, 5, 1, 0 };
  5. unsigned cir[8][8] = {
  6. {1, 1, 4, 1, 8, 5, 2, 9 },
  7. };
  8. unsigned gf_mul(unsigned a, unsigned b)
  9. {
  10. unsigned r;
  11. r = 0;
  12. while (a) {
  13. if (a & 1) r ^= b;
  14. a >>= 1;
  15. b = (b << 1) ^ (b & 0x80 ? 0x11d : 0x00);
  16. }
  17. return r;
  18. }
  19. unsigned sbox(unsigned x)
  20. {
  21. unsigned a, b, w;
  22. a = x >> 4;
  23. b = x & 15;
  24. a = E[a]; b = Ei[b];
  25. w = a ^ b; w = R[w];
  26. a = E[a ^ w]; b = Ei[b ^ w];
  27. return (a << 4) | b;
  28. }
  29. int main(void)
  30. {
  31. unsigned x, y;
  32. for (x = 0; x < 16; x++) Ei[E[x]] = x;
  33. // for (x = 0; x < 16; x++) printf("%2x ", sbox(x));
  34. for (y = 1; y < 8; y++) {
  35. for (x = 0; x < 8; x++) {
  36. cir[y][x] = cir[y-1][(x-1)&7];
  37. }
  38. }
  39. /*
  40. printf("\n");
  41. for (y = 0; y < 8; y++) {
  42. for (x = 0; x < 8; x++) printf("%2d ", cir[y][x]);
  43. printf("\n");
  44. }
  45. */
  46. for (y = 0; y < 8; y++) {
  47. printf("static const ulong64 sbox%d[] = {\n", y);
  48. for (x = 0; x < 256; ) {
  49. printf("CONST64(0x%02x%02x%02x%02x%02x%02x%02x%02x)",
  50. gf_mul(sbox(x), cir[y][0]),
  51. gf_mul(sbox(x), cir[y][1]),
  52. gf_mul(sbox(x), cir[y][2]),
  53. gf_mul(sbox(x), cir[y][3]),
  54. gf_mul(sbox(x), cir[y][4]),
  55. gf_mul(sbox(x), cir[y][5]),
  56. gf_mul(sbox(x), cir[y][6]),
  57. gf_mul(sbox(x), cir[y][7]));
  58. if (x < 255) printf(", ");
  59. if (!(++x & 3)) printf("\n");
  60. }
  61. printf("};\n\n");
  62. }
  63. printf("static const ulong64 cont[] = {\n");
  64. for (y = 0; y <= 10; y++) {
  65. printf("CONST64(0x");
  66. for (x = 0; x < 8; x++) {
  67. printf("%02x", sbox((8*y + x)&255));
  68. }
  69. printf("),\n");
  70. }
  71. printf("};\n\n");
  72. return 0;
  73. }
  74. /* ref: $Format:%D$ */
  75. /* git commit: $Format:%H$ */
  76. /* commit time: $Format:%ai$ */