dsagen.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. DSApriv*
  13. dsagen(DSApub *opub)
  14. {
  15. DSApub *pub;
  16. DSApriv *priv;
  17. mpint *exp;
  18. mpint *g;
  19. mpint *r;
  20. int bits;
  21. priv = dsaprivalloc();
  22. pub = &priv->pub;
  23. if(opub != nil){
  24. pub->p = mpcopy(opub->p);
  25. pub->q = mpcopy(opub->q);
  26. } else {
  27. pub->p = mpnew(0);
  28. pub->q = mpnew(0);
  29. DSAprimes(pub->q, pub->p, nil);
  30. }
  31. bits = Dbits*pub->p->top;
  32. pub->alpha = mpnew(0);
  33. pub->key = mpnew(0);
  34. priv->secret = mpnew(0);
  35. // find a generator alpha of the multiplicative
  36. // group Z*p, i.e., of order n = p-1. We use the
  37. // fact that q divides p-1 to reduce the exponent.
  38. //
  39. // This isn't very efficient. If anyone has a better
  40. // idea, mail presotto@closedmind.org
  41. exp = mpnew(0);
  42. g = mpnew(0);
  43. r = mpnew(0);
  44. mpsub(pub->p, mpone, exp);
  45. mpdiv(exp, pub->q, exp, r);
  46. if(mpcmp(r, mpzero) != 0)
  47. sysfatal("dsagen foul up");
  48. while(1){
  49. mprand(bits, genrandom, g);
  50. mpmod(g, pub->p, g);
  51. mpexp(g, exp, pub->p, pub->alpha);
  52. if(mpcmp(pub->alpha, mpone) != 0)
  53. break;
  54. }
  55. mpfree(g);
  56. mpfree(exp);
  57. // create the secret key
  58. mprand(bits, genrandom, priv->secret);
  59. mpmod(priv->secret, pub->p, priv->secret);
  60. mpexp(pub->alpha, priv->secret, pub->p, pub->key);
  61. return priv;
  62. }