rsafill.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "os.h"
  2. #include <mp.h>
  3. #include <libsec.h>
  4. RSApriv*
  5. rsafill(mpint *n, mpint *e, mpint *d, mpint *p, mpint *q)
  6. {
  7. mpint *c2, *kq, *kp, *x;
  8. RSApriv *rsa;
  9. // make sure we're not being hoodwinked
  10. if(!probably_prime(p, 10) || !probably_prime(q, 10)){
  11. werrstr("rsafill: p or q not prime");
  12. return nil;
  13. }
  14. x = mpnew(0);
  15. mpmul(p, q, x);
  16. if(mpcmp(n, x) != 0){
  17. werrstr("rsafill: n != p*q");
  18. mpfree(x);
  19. return nil;
  20. }
  21. c2 = mpnew(0);
  22. mpsub(p, mpone, c2);
  23. mpsub(q, mpone, x);
  24. mpmul(c2, x, x);
  25. mpmul(e, d, c2);
  26. mpmod(c2, x, x);
  27. if(mpcmp(x, mpone) != 0){
  28. werrstr("rsafill: e*d != 1 mod (p-1)*(q-1)");
  29. mpfree(x);
  30. mpfree(c2);
  31. return nil;
  32. }
  33. // compute chinese remainder coefficient
  34. mpinvert(p, q, c2);
  35. // for crt a**k mod p == (a**(k mod p-1)) mod p
  36. kq = mpnew(0);
  37. kp = mpnew(0);
  38. mpsub(p, mpone, x);
  39. mpmod(d, x, kp);
  40. mpsub(q, mpone, x);
  41. mpmod(d, x, kq);
  42. rsa = rsaprivalloc();
  43. rsa->pub.ek = mpcopy(e);
  44. rsa->pub.n = mpcopy(n);
  45. rsa->dk = mpcopy(d);
  46. rsa->kp = kp;
  47. rsa->kq = kq;
  48. rsa->p = mpcopy(p);
  49. rsa->q = mpcopy(q);
  50. rsa->c2 = c2;
  51. mpfree(x);
  52. return rsa;
  53. }