rsafill.c 1.5 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. RSApriv*
  13. rsafill(mpint *n, mpint *e, mpint *d, mpint *p, mpint *q)
  14. {
  15. mpint *c2, *kq, *kp, *x;
  16. RSApriv *rsa;
  17. // make sure we're not being hoodwinked
  18. if(!probably_prime(p, 10) || !probably_prime(q, 10)){
  19. werrstr("rsafill: p or q not prime");
  20. return nil;
  21. }
  22. x = mpnew(0);
  23. mpmul(p, q, x);
  24. if(mpcmp(n, x) != 0){
  25. werrstr("rsafill: n != p*q");
  26. mpfree(x);
  27. return nil;
  28. }
  29. c2 = mpnew(0);
  30. mpsub(p, mpone, c2);
  31. mpsub(q, mpone, x);
  32. mpmul(c2, x, x);
  33. mpmul(e, d, c2);
  34. mpmod(c2, x, x);
  35. if(mpcmp(x, mpone) != 0){
  36. werrstr("rsafill: e*d != 1 mod (p-1)*(q-1)");
  37. mpfree(x);
  38. mpfree(c2);
  39. return nil;
  40. }
  41. // compute chinese remainder coefficient
  42. mpinvert(p, q, c2);
  43. // for crt a**k mod p == (a**(k mod p-1)) mod p
  44. kq = mpnew(0);
  45. kp = mpnew(0);
  46. mpsub(p, mpone, x);
  47. mpmod(d, x, kp);
  48. mpsub(q, mpone, x);
  49. mpmod(d, x, kq);
  50. rsa = rsaprivalloc();
  51. rsa->pub.ek = mpcopy(e);
  52. rsa->pub.n = mpcopy(n);
  53. rsa->dk = mpcopy(d);
  54. rsa->kp = kp;
  55. rsa->kq = kq;
  56. rsa->p = mpcopy(p);
  57. rsa->q = mpcopy(q);
  58. rsa->c2 = c2;
  59. mpfree(x);
  60. return rsa;
  61. }