react / wstein / node_modules / browserify / node_modules / crypto-browserify / node_modules / diffie-hellman / node_modules / miller-rabin / lib / mr.js
80559 viewsvar bn = require('bn.js');1var brorand = require('brorand');23function MillerRabin(rand) {4this.rand = rand || new brorand.Rand();5}6module.exports = MillerRabin;78MillerRabin.create = function create(rand) {9return new MillerRabin(rand);10};1112MillerRabin.prototype._rand = function _rand(n) {13var len = n.bitLength();14var buf = this.rand.generate(Math.ceil(len / 8));1516// Set low bits17buf[0] |= 3;1819// Mask high bits20var mask = len & 0x7;21if (mask !== 0)22buf[buf.length - 1] >>= 7 - mask;2324return new bn(buf);25}2627MillerRabin.prototype.test = function test(n, k, cb) {28var len = n.bitLength();29var red = bn.mont(n);30var rone = new bn(1).toRed(red);3132if (!k)33k = Math.max(1, (len / 48) | 0);3435// Find d and s, (n - 1) = (2 ^ s) * d;36var n1 = n.subn(1);37var n2 = n1.subn(1);38for (var s = 0; !n1.testn(s); s++) {}39var d = n.shrn(s);4041var rn1 = n1.toRed(red);4243var prime = true;44for (; k > 0; k--) {45var a = this._rand(n2);46if (cb)47cb(a);4849var x = a.toRed(red).redPow(d);50if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)51continue;5253for (var i = 1; i < s; i++) {54x = x.redSqr();5556if (x.cmp(rone) === 0)57return false;58if (x.cmp(rn1) === 0)59break;60}6162if (i === s)63return false;64}6566return prime;67};6869MillerRabin.prototype.getDivisor = function getDivisor(n, k) {70var len = n.bitLength();71var red = bn.mont(n);72var rone = new bn(1).toRed(red);7374if (!k)75k = Math.max(1, (len / 48) | 0);7677// Find d and s, (n - 1) = (2 ^ s) * d;78var n1 = n.subn(1);79var n2 = n1.subn(1);80for (var s = 0; !n1.testn(s); s++) {}81var d = n.shrn(s);8283var rn1 = n1.toRed(red);8485for (; k > 0; k--) {86var a = this._rand(n2);8788var g = n.gcd(a);89if (g.cmpn(1) !== 0)90return g;9192var x = a.toRed(red).redPow(d);93if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)94continue;9596for (var i = 1; i < s; i++) {97x = x.redSqr();9899if (x.cmp(rone) === 0)100return x.fromRed().subn(1).gcd(n);101if (x.cmp(rn1) === 0)102break;103}104105if (i === s) {106x = x.redSqr();107return x.fromRed().subn(1).gcd(n);108}109}110111return false;112};113114115