From 4c1202868cbe4c7074adeb9475ae3bc1e92012e2 Mon Sep 17 00:00:00 2001 From: Tilman Vogel Date: Thu, 14 Nov 2024 17:11:47 +0100 Subject: [PATCH] ecdsa-modified: fix getBigRandom() this replaces the previously remainder-based limiting of the random number which caused bias toward small numbers and excluded zero altogether by simple filtering as proposed frequently in https://github.com/kjur/jsrsasign/issues/221 and because the performance in most cases is actually faster than in the present implementation; also, an adaptation of https://github.com/swiftlang/swift/pull/39143 has been considered but it performed significantly slower for large integers; --- src/ecdsa-modified-1.0.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/ecdsa-modified-1.0.js b/src/ecdsa-modified-1.0.js index 7a8d947c..6fc310b5 100644 --- a/src/ecdsa-modified-1.0.js +++ b/src/ecdsa-modified-1.0.js @@ -95,11 +95,15 @@ KJUR.crypto.ECDSA = function(params) { //=========================== // PUBLIC METHODS //=========================== + /* + * Generate uniformly distributed big random integer in 0 <= x < limit + */ this.getBigRandom = function (limit) { - return new _BigInteger(limit.bitLength(), rng) - .mod(limit.subtract(_BigInteger.ONE)) - .add(_BigInteger.ONE) - ; + var bitLength = limit.subtract(_BigInteger.ONE).bitLength(); + do { + var result = new _BigInteger(bitLength, rng); + } while (result.compareTo(limit) >= 0); + return result; }; this.setNamedCurve = function(curveName) {