gensafeprime.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include "os.h"
  10. #include <mp.h>
  11. #include <libsec.h>
  12. // find a prime p of length n and a generator alpha of Z^*_p
  13. // Alg 4.86 Menezes et al () Handbook, p.164
  14. void
  15. gensafeprime(mpint *p, mpint *alpha, int n, int accuracy)
  16. {
  17. mpint *q, *b;
  18. q = mpnew(n-1);
  19. while(1){
  20. genprime(q, n-1, accuracy);
  21. mpleft(q, 1, p);
  22. mpadd(p, mpone, p); // p = 2*q+1
  23. if(probably_prime(p, accuracy))
  24. break;
  25. }
  26. // now find a generator alpha of the multiplicative
  27. // group Z*_p of order p-1=2q
  28. b = mpnew(0);
  29. while(1){
  30. mprand(n, genrandom, alpha);
  31. mpmod(alpha, p, alpha);
  32. mpmul(alpha, alpha, b);
  33. mpmod(b, p, b);
  34. if(mpcmp(b, mpone) == 0)
  35. continue;
  36. mpexp(alpha, q, p, b);
  37. if(mpcmp(b, mpone) != 0)
  38. break;
  39. }
  40. mpfree(b);
  41. mpfree(q);
  42. }