rsadecrypt.c 749 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #include "os.h"
  2. #include <mp.h>
  3. #include <libsec.h>
  4. // decrypt rsa using garner's algorithm for the chinese remainder theorem
  5. // seminumerical algorithms, knuth, pp 253-254
  6. // applied cryptography, menezes et al, pg 612
  7. mpint*
  8. rsadecrypt(RSApriv *rsa, mpint *in, mpint *out)
  9. {
  10. mpint *v1, *v2;
  11. if(out == nil)
  12. out = mpnew(0);
  13. // convert in to modular representation
  14. v1 = mpnew(0);
  15. mpmod(in, rsa->p, v1);
  16. v2 = mpnew(0);
  17. mpmod(in, rsa->q, v2);
  18. // exponentiate the modular rep
  19. mpexp(v1, rsa->kp, rsa->p, v1);
  20. mpexp(v2, rsa->kq, rsa->q, v2);
  21. // out = v1 + p*((v2-v1)*c2 mod q)
  22. mpsub(v2, v1, v2);
  23. mpmul(v2, rsa->c2, v2);
  24. mpmod(v2, rsa->q, v2);
  25. mpmul(v2, rsa->p, out);
  26. mpadd(v1, out, out);
  27. mpfree(v1);
  28. mpfree(v2);
  29. return out;
  30. }