diff --git a/prime.php b/prime.php index fb4233fe..de823bb6 100644 --- a/prime.php +++ b/prime.php @@ -72,7 +72,55 @@ class PrimeModule return true; } + // taken from https://github.com/enricostara/telegram-mt-node/blob/master/lib/security/pq-finder.js + public function factorization($num) { + $zero = new \phpseclib\Math\BigInteger(0); + $one = new \phpseclib\Math\BigInteger(1); + $two = new \phpseclib\Math\BigInteger(2); + $three = new \phpseclib\Math\BigInteger(3); + $prime = new \phpseclib\Math\BigInteger(); + + for ($i = 0; $i < 3; $i++) { + $q = new \phpseclib\Math\BigInteger((random_int(0, 128) & 15) + 17); + $x = new \phpseclib\Math\BigInteger(random_int(0, 1000000000) + 1); + $y = $x; + $lim = 1 << ($i + 18); + for ($j = 1; $j < $lim; $j++) { + $a = $x; + $b = $x; + $c = $q; + while (!$b->equals($zero)) { + if (b.repr[0] & 1) { + c.addEquals(a); + if (c.gt(num)) { + c = c.subtract(num); + } + } + a.addEquals(a); + if (a.gt(num)) { + a = a.subtract(num); + } + b = b.shiftRight(1); + } + $x = $c; + $z = $y.gt(x) ? y.subtract(x) : x.subtract(y); + $prime = z.gcd(num, a, b); + if (!prime.eql(BigInteger.One())) { + break; + } + if ((j & (j - 1)) === 0) { + $y = $x; + } + } + if (prime.gt(BigInteger.One())) { + break; + } + } + $cofactor = num.divide(prime)[0]; + $_pq = cofactor.gt(prime) ? [prime, cofactor] : [cofactor, prime]; + return _$pq; + } public function pollard_brent($n) { $zero = new \phpseclib\Math\BigInteger(0); @@ -214,78 +262,4 @@ class PrimeModule return floor(abs(($a * $b)) / $this->gcd($a, $b)); } -/* -function pqPrimeLeemon ($what) { - $minBits = 64; - $minLen = ceil($minBits / $bpe) + 1; - $it = 0 - $a = new Array(minLen) - $b = new Array(minLen) - $c = new Array(minLen) - $g = new Array(minLen) - $z = new Array(minLen) - $x = new Array(minLen) - $y = new Array(minLen) - - for ($i = 0; $i < 3; $i++) { - $q = (nextRandomInt(128) & 15) + 17 - copyInt_(x, nextRandomInt(1000000000) + 1) - copy_(y, x) - lim = 1 << (i + 18) - - for (j = 1; j < lim; j++) { - ++it - copy_(a, x) - copy_(b, x) - copyInt_(c, q) - - while (!isZero(b)) { - if (b[0] & 1) { - add_(c, a) - if (greater(c, what)) { - sub_(c, what) - } - } - add_(a, a) - if (greater(a, what)) { - sub_(a, what) - } - rightShift_(b, 1) - } - - copy_(x, c) - if (greater(x, y)) { - copy_(z, x) - sub_(z, y) - } else { - copy_(z, y) - sub_(z, x) - } - eGCD_(z, what, g, a, b) - if (!equalsInt(g, 1)) { - break - } - if ((j & (j - 1)) == 0) { - copy_(y, x) - } - } - if (greater(g, one)) { - break - } - } - - divide_(what, g, x, y) - - if (greater(g, x)) { - P = x - Q = g - } else { - P = g - Q = x - } - - // console.log(dT(), 'done', bigInt2str(what, 10), bigInt2str(P, 10), bigInt2str(Q, 10)) - - return [bytesFromLeemonBigInt(P), bytesFromLeemonBigInt(Q), it] -}*/ }