1
0

sc25519_from32bytes.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #include "sc25519.h"
  2. /*Arithmetic modulo the group order n = 2^252 + 27742317777372353535851937790883648493
  3. * = 7237005577332262213973186563042994240857116359379907606001950938285454250989
  4. */
  5. /* Contains order, 2*order, 4*order, 8*order, each represented in 4 consecutive unsigned long long */
  6. static const unsigned long long order[16] = {0x5812631A5CF5D3EDULL, 0x14DEF9DEA2F79CD6ULL,
  7. 0x0000000000000000ULL, 0x1000000000000000ULL,
  8. 0xB024C634B9EBA7DAULL, 0x29BDF3BD45EF39ACULL,
  9. 0x0000000000000000ULL, 0x2000000000000000ULL,
  10. 0x60498C6973D74FB4ULL, 0x537BE77A8BDE7359ULL,
  11. 0x0000000000000000ULL, 0x4000000000000000ULL,
  12. 0xC09318D2E7AE9F68ULL, 0xA6F7CEF517BCE6B2ULL,
  13. 0x0000000000000000ULL, 0x8000000000000000ULL};
  14. static unsigned long long smaller(unsigned long long a,unsigned long long b)
  15. {
  16. unsigned long long atop = a >> 32;
  17. unsigned long long abot = a & 4294967295;
  18. unsigned long long btop = b >> 32;
  19. unsigned long long bbot = b & 4294967295;
  20. unsigned long long atopbelowbtop = (atop - btop) >> 63;
  21. unsigned long long atopeqbtop = ((atop ^ btop) - 1) >> 63;
  22. unsigned long long abotbelowbbot = (abot - bbot) >> 63;
  23. return atopbelowbtop | (atopeqbtop & abotbelowbbot);
  24. }
  25. void sc25519_from32bytes(sc25519 *r, const unsigned char x[32])
  26. {
  27. unsigned long long t[4];
  28. unsigned long long b;
  29. unsigned long long mask;
  30. int i, j;
  31. /* assuming little-endian */
  32. r->v[0] = *(unsigned long long *)x;
  33. r->v[1] = *(((unsigned long long *)x)+1);
  34. r->v[2] = *(((unsigned long long *)x)+2);
  35. r->v[3] = *(((unsigned long long *)x)+3);
  36. for(j=3;j>=0;j--)
  37. {
  38. b=0;
  39. for(i=0;i<4;i++)
  40. {
  41. b += order[4*j+i]; /* no overflow for this particular order */
  42. t[i] = r->v[i] - b;
  43. b = smaller(r->v[i],b);
  44. }
  45. mask = b - 1;
  46. for(i=0;i<4;i++)
  47. r->v[i] ^= mask & (r->v[i] ^ t[i]);
  48. }
  49. }