scalar.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * File: dclxvi-20130329/scalar.c
  3. * Author: Ruben Niederhagen, Peter Schwabe
  4. * Public Domain
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <assert.h>
  9. #include "scalar.h"
  10. #ifndef NEW_PARAMETERS
  11. void scalar_setrandom(scalar_t rop, const scalar_t bound)
  12. {
  13. int i;
  14. FILE *urand = fopen("/dev/urandom", "r");
  15. if (urand == NULL)
  16. {
  17. fprintf(stderr, "Could not open device file /dev/urandom");
  18. exit(1);
  19. }
  20. do
  21. {
  22. for(i=0;i<32;i++)
  23. i[(unsigned char*)rop] = fgetc(urand);
  24. }
  25. while(!scalar_lt_vartime(rop,bound));
  26. fclose(urand);
  27. }
  28. void scalar_set_lluarray(scalar_t rop, unsigned long long v[4])
  29. {
  30. int i;
  31. for(i=0;i<4;i++) rop[i] = v[i];
  32. }
  33. int scalar_getbit(const scalar_t s, unsigned int pos)
  34. {
  35. assert(pos < 256);
  36. return (s[pos >> 6] >> (pos & 0x3f)) & 1;
  37. }
  38. // Returns the position of the most significant set bit
  39. int scalar_scanb(const scalar_t s)
  40. {
  41. int i;
  42. unsigned int pos = 0;
  43. for(i=255;i>0;i--)
  44. if(scalar_getbit(s,i) && pos == 0) pos = i;
  45. return pos;
  46. }
  47. int scalar_iszero_vartime(const scalar_t s)
  48. {
  49. return ((s[0] | s[1] | s[2] | s[3]) == 0);
  50. }
  51. void scalar_window4(signed char r[65], const scalar_t s)
  52. {
  53. char carry;
  54. int i;
  55. for(i=0;i<16;i++)
  56. r[i] = (s[0] >> (4*i)) & 15;
  57. for(i=0;i<16;i++)
  58. r[i+16] = (s[1] >> (4*i)) & 15;
  59. for(i=0;i<16;i++)
  60. r[i+32] = (s[2] >> (4*i)) & 15;
  61. for(i=0;i<16;i++)
  62. r[i+48] = (s[3] >> (4*i)) & 15;
  63. /* Making it signed */
  64. carry = 0;
  65. for(i=0;i<64;i++)
  66. {
  67. r[i] += carry;
  68. r[i+1] += r[i] >> 4;
  69. r[i] &= 15;
  70. carry = r[i] >> 3;
  71. r[i] -= carry << 4;
  72. }
  73. r[64] = carry;
  74. }
  75. // Returns 1 if a < b, 0 otherwise
  76. int scalar_lt_vartime(const scalar_t a, const scalar_t b)
  77. {
  78. if(a[3] < b[3]) return 1;
  79. if(a[3] > b[3]) return 0;
  80. if(a[2] < b[2]) return 1;
  81. if(a[2] > b[2]) return 0;
  82. if(a[1] < b[1]) return 1;
  83. if(a[1] > b[1]) return 0;
  84. if(a[0] < b[0]) return 1;
  85. if(a[0] > b[0]) return 0;
  86. return 0;
  87. }
  88. void scalar_print(FILE *fh, const scalar_t t)
  89. {
  90. int i;
  91. fprintf(fh, "{0x%llx,\t", t[0]);
  92. for(i=1;i<=2;i++)
  93. {
  94. fprintf(fh, "0x%llx,\t", t[i]);
  95. }
  96. fprintf(fh, "0x%llx};\n", t[3]);
  97. }
  98. #endif