You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var bn = require('bn.js');
  2. var randomBytes = require('randombytes');
  3. module.exports = crt;
  4. function blind(priv) {
  5. var r = getr(priv);
  6. var blinder = r.toRed(bn.mont(priv.modulus))
  7. .redPow(new bn(priv.publicExponent)).fromRed();
  8. return {
  9. blinder: blinder,
  10. unblinder:r.invm(priv.modulus)
  11. };
  12. }
  13. function crt(msg, priv) {
  14. var blinds = blind(priv);
  15. var len = priv.modulus.byteLength();
  16. var mod = bn.mont(priv.modulus);
  17. var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
  18. var c1 = blinded.toRed(bn.mont(priv.prime1));
  19. var c2 = blinded.toRed(bn.mont(priv.prime2));
  20. var qinv = priv.coefficient;
  21. var p = priv.prime1;
  22. var q = priv.prime2;
  23. var m1 = c1.redPow(priv.exponent1);
  24. var m2 = c2.redPow(priv.exponent2);
  25. m1 = m1.fromRed();
  26. m2 = m2.fromRed();
  27. var h = m1.isub(m2).imul(qinv).umod(p);
  28. h.imul(q);
  29. m2.iadd(h);
  30. return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
  31. }
  32. crt.getr = getr;
  33. function getr(priv) {
  34. var len = priv.modulus.byteLength();
  35. var r = new bn(randomBytes(len));
  36. while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
  37. r = new bn(randomBytes(len));
  38. }
  39. return r;
  40. }