fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <math.h>
  4. #include <stdint.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7.  
  8.  
  9. // Additive constant
  10. uint8_t c[8]= {1,1,0,0,0,1,1,0};
  11.  
  12. //Global S Box
  13. uint8_t sbox[256] = {0};
  14.  
  15. //Powers of
  16. int powersoftwo[11]= {1,2,4,8,16,32,64,128,256,512,1024};
  17.  
  18. //Calculates x such that ax mod m = 1 using extended euclid's algorithm.
  19. int modInverse(int a, int m){
  20. int x, y;
  21. int g = gcdExtended(a, m,&x,&y);
  22. if (g != 1)
  23. printf("no inverse\n");
  24. else{
  25. int res = (x%m + m) % m;
  26. return res;
  27. }
  28. }
  29.  
  30. int gcdExtended(int a, int b, int *x, int *y)
  31. {
  32. if (a == 0){
  33. *x = 0, *y = 1;
  34. return b;
  35. }
  36. int x1, y1; // To store results of recursive call
  37. int gcd = gcdExtended(b%a, a, &x1, &y1);
  38. // Update x and y using results of recursive
  39. // call
  40. *x = y1 - (b/a) * x1;
  41. *y = x1;
  42. return gcd;
  43. }
  44.  
  45. void getbinary(uint8_t n,uint8_t *a){
  46. int i=0;
  47. while(n > 0){
  48. a[i++] = n%2;
  49. n = n/2;
  50. }
  51. return;
  52. }
  53.  
  54. int getdecimal(uint8_t *a){
  55. int i,n=0;
  56. for(i=0;i<8;i++)
  57. n = n + a[i]*powersoftwo[i];
  58. return n;
  59. }
  60.  
  61. //generates sbox
  62. void generate_sbox(){
  63. int i,j;
  64. //loop for all 0-255 entries.
  65. //special case = 0
  66. for(i=1;i!=16*16;i++){
  67. uint8_t tmp[8] = {0}; //stores binary of inverse.
  68. uint8_t y;
  69. int inv = modInverse(i,283); //inverse.
  70. getbinary(inv,tmp);
  71. uint8_t newtmp[8];
  72. //Affine transformation
  73. for(j=0;j<8;j++)
  74. newtmp[j] = (tmp[j]^tmp[(j+4)%8]^tmp[(j+5)%8]^tmp[(j+6)%8]^tmp[(j+7)%8]^c[j]);
  75. //decimal to binary conversion.
  76. int num = getdecimal(newtmp);
  77. sbox[i] = num;
  78. }
  79. return ;
  80. }
  81.  
  82.  
  83. int main(){
  84. generate_sbox();
  85. return 0;
  86. }
Success #stdin #stdout 0s 9296KB
stdin
Standard input is empty
stdout
Standard output is empty