rsadecrypt.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. // decrypt rsa using garner's algorithm for the chinese remainder theorem
  13. // seminumerical algorithms, knuth, pp 253-254
  14. // applied cryptography, menezes et al, pg 612
  15. mpint*
  16. rsadecrypt(RSApriv *rsa, mpint *in, mpint *out)
  17. {
  18. mpint *v1, *v2;
  19. if(out == nil)
  20. out = mpnew(0);
  21. // convert in to modular representation
  22. v1 = mpnew(0);
  23. mpmod(in, rsa->p, v1);
  24. v2 = mpnew(0);
  25. mpmod(in, rsa->q, v2);
  26. // exponentiate the modular rep
  27. mpexp(v1, rsa->kp, rsa->p, v1);
  28. mpexp(v2, rsa->kq, rsa->q, v2);
  29. // out = v1 + p*((v2-v1)*c2 mod q)
  30. mpsub(v2, v1, v2);
  31. mpmul(v2, rsa->c2, v2);
  32. mpmod(v2, rsa->q, v2);
  33. mpmul(v2, rsa->p, out);
  34. mpadd(v1, out, out);
  35. mpfree(v1);
  36. mpfree(v2);
  37. return out;
  38. }