group.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include <stdint.h>
  3. #include <gmp.h>
  4. /**
  5. * p is our prime modulus, and is 2^n - g
  6. * where g is referred to as "gamma" (built-in function in C, so transliterated)
  7. */
  8. extern const char* p_str;
  9. extern mpz_t p, q;
  10. extern const uint64_t gg;
  11. void group_init();
  12. void group_clear();
  13. /* some gmp internal funcitons to speed up modulus… */
  14. #define SIZ(x) ((x)->_mp_size)
  15. #define PTR(x) ((x)->_mp_d)
  16. #define MPN_NORMALIZE(DST, NLIMBS) \
  17. do { \
  18. while (1) \
  19. { \
  20. if ((DST)[(NLIMBS) - 1] != 0) \
  21. break; \
  22. (NLIMBS)--; \
  23. } \
  24. } while (0)
  25. static inline
  26. void remp(mpz_t rop)
  27. {
  28. int32_t limbs = SIZ(rop) - 24;
  29. while (limbs > 0) {
  30. /* note: this declarations MUST happen after checking
  31. * for positivity of limbs. */
  32. uint64_t a[limbs+1];
  33. /* copy the most significant part of rop into a,
  34. * then set it to zero */
  35. for (int i = 24; i < SIZ(rop); i++) {
  36. a[i-24] = PTR(rop)[i];
  37. PTR(rop)[i] = 0;
  38. }
  39. a[limbs] = 0;
  40. mpn_addmul_1(PTR(rop), a, limbs+1, gg);
  41. MPN_NORMALIZE(PTR(rop), SIZ(rop));
  42. limbs = SIZ(rop) - 24;
  43. }
  44. if (mpn_cmp(PTR(rop), PTR(p), SIZ(rop)) >= 0) {
  45. mpn_sub(PTR(rop), PTR(rop), 24, PTR(p), 24);
  46. MPN_NORMALIZE(PTR(rop), SIZ(rop));
  47. }
  48. }
  49. void powmp_ui(mpz_t rop, const mpz_t base, uint64_t exp);
  50. #define mpz_mul_modp(rop, op1, op2) mpz_mul(rop, op1, op2); remp(rop);