scalar.c 2.0 KB

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