ge_double_scalarmult.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "ge.h"
  2. static void slide(signed char *r,const unsigned char *a)
  3. {
  4. int i;
  5. int b;
  6. int k;
  7. for (i = 0;i < 256;++i)
  8. r[i] = 1 & (a[i >> 3] >> (i & 7));
  9. for (i = 0;i < 256;++i)
  10. if (r[i]) {
  11. for (b = 1;b <= 6 && i + b < 256;++b) {
  12. if (r[i + b]) {
  13. if (r[i] + (r[i + b] << b) <= 15) {
  14. r[i] += r[i + b] << b; r[i + b] = 0;
  15. } else if (r[i] - (r[i + b] << b) >= -15) {
  16. r[i] -= r[i + b] << b;
  17. for (k = i + b;k < 256;++k) {
  18. if (!r[k]) {
  19. r[k] = 1;
  20. break;
  21. }
  22. r[k] = 0;
  23. }
  24. } else
  25. break;
  26. }
  27. }
  28. }
  29. }
  30. static ge_precomp Bi[8] = {
  31. #include "base2.h"
  32. } ;
  33. /*
  34. r = a * A + b * B
  35. where a = a[0]+256*a[1]+...+256^31 a[31].
  36. and b = b[0]+256*b[1]+...+256^31 b[31].
  37. B is the Ed25519 base point (x,4/5) with x positive.
  38. */
  39. void ge_double_scalarmult_vartime(ge_p2 *r,const unsigned char *a,const ge_p3 *A,const unsigned char *b)
  40. {
  41. signed char aslide[256];
  42. signed char bslide[256];
  43. ge_cached Ai[8]; /* A,3A,5A,7A,9A,11A,13A,15A */
  44. ge_p1p1 t;
  45. ge_p3 u;
  46. ge_p3 A2;
  47. int i;
  48. slide(aslide,a);
  49. slide(bslide,b);
  50. ge_p3_to_cached(&Ai[0],A);
  51. ge_p3_dbl(&t,A); ge_p1p1_to_p3(&A2,&t);
  52. ge_add(&t,&A2,&Ai[0]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[1],&u);
  53. ge_add(&t,&A2,&Ai[1]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[2],&u);
  54. ge_add(&t,&A2,&Ai[2]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[3],&u);
  55. ge_add(&t,&A2,&Ai[3]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[4],&u);
  56. ge_add(&t,&A2,&Ai[4]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[5],&u);
  57. ge_add(&t,&A2,&Ai[5]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[6],&u);
  58. ge_add(&t,&A2,&Ai[6]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[7],&u);
  59. ge_p2_0(r);
  60. for (i = 255;i >= 0;--i) {
  61. if (aslide[i] || bslide[i]) break;
  62. }
  63. for (;i >= 0;--i) {
  64. ge_p2_dbl(&t,r);
  65. if (aslide[i] > 0) {
  66. ge_p1p1_to_p3(&u,&t);
  67. ge_add(&t,&u,&Ai[aslide[i]/2]);
  68. } else if (aslide[i] < 0) {
  69. ge_p1p1_to_p3(&u,&t);
  70. ge_sub(&t,&u,&Ai[(-aslide[i])/2]);
  71. }
  72. if (bslide[i] > 0) {
  73. ge_p1p1_to_p3(&u,&t);
  74. ge_madd(&t,&u,&Bi[bslide[i]/2]);
  75. } else if (bslide[i] < 0) {
  76. ge_p1p1_to_p3(&u,&t);
  77. ge_msub(&t,&u,&Bi[(-bslide[i])/2]);
  78. }
  79. ge_p1p1_to_p2(r,&t);
  80. }
  81. }