gensafeprime.c 741 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include "os.h"
  2. #include <mp.h>
  3. #include <libsec.h>
  4. // find a prime p of length n and a generator alpha of Z^*_p
  5. // Alg 4.86 Menezes et al () Handbook, p.164
  6. void
  7. gensafeprime(mpint *p, mpint *alpha, int n, int accuracy)
  8. {
  9. mpint *q, *b;
  10. q = mpnew(n-1);
  11. while(1){
  12. genprime(q, n-1, accuracy);
  13. mpleft(q, 1, p);
  14. mpadd(p, mpone, p); // p = 2*q+1
  15. if(probably_prime(p, accuracy))
  16. break;
  17. }
  18. // now find a generator alpha of the multiplicative
  19. // group Z*_p of order p-1=2q
  20. b = mpnew(0);
  21. while(1){
  22. mprand(n, genrandom, alpha);
  23. mpmod(alpha, p, alpha);
  24. mpmul(alpha, alpha, b);
  25. mpmod(b, p, b);
  26. if(mpcmp(b, mpone) == 0)
  27. continue;
  28. mpexp(alpha, q, p, b);
  29. if(mpcmp(b, mpone) != 0)
  30. break;
  31. }
  32. mpfree(b);
  33. mpfree(q);
  34. }