Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/crypto-1.1.js
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ KJUR.crypto.Util.getRandomBigIntegerZeroToMax = function(biMax) {
var bitLenMax = biMax.bitLength();
while (1) {
var biRand = KJUR.crypto.Util.getRandomBigIntegerOfNbits(bitLenMax);
if (biMax.compareTo(biRand) != -1) return biRand;
if (biMax.compareTo(biRand) >= 0) return biRand;
}
};

Expand All @@ -415,7 +415,7 @@ KJUR.crypto.Util.getRandomBigIntegerZeroToMax = function(biMax) {
*/
KJUR.crypto.Util.getRandomBigIntegerMinToMax = function(biMin, biMax) {
var flagCompare = biMin.compareTo(biMax);
if (flagCompare == 1) throw "biMin is greater than biMax";
if (flagCompare > 0) throw "biMin is greater than biMax";
if (flagCompare == 0) return biMin;

var biDiff = biMax.subtract(biMin);
Expand Down
32 changes: 32 additions & 0 deletions test/qunit-do-crypto.html
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,22 @@
equal(n, 1000, "1000 times success:" + n0 + ":" + n1 + ":" + n2 + ":" + n3);
});

test("Util.getRandomBigIntegerZeroToMax rejects out-of-range candidate", function() {
var fOrig = KJUR.crypto.Util.getRandomBigIntegerOfNbits;
var aBiRand = [new BigInteger("200", 10), new BigInteger("42", 10)];
var idx = 0;
KJUR.crypto.Util.getRandomBigIntegerOfNbits = function(n) {
return aBiRand[idx++];
};
try {
var bi = KJUR.crypto.Util.getRandomBigIntegerZeroToMax(new BigInteger("100", 10));
equal(bi.toString(10), "42", "returns in-range value");
equal(idx >= 2, true, "retries when out-of-range candidate appears");
} finally {
KJUR.crypto.Util.getRandomBigIntegerOfNbits = fOrig;
}
});

test("Util.getRandomBigIntegerMinToMax", function() {
var bi15 = new BigInteger("15", 10);
var bi18 = new BigInteger("18", 10);
Expand Down Expand Up @@ -270,6 +286,22 @@
equal(new BigInteger("-13", 10).modInverse(biM2).toString(10), "82", "-13 mod 97");
});

test("Util.getRandomBigIntegerMinToMax throws for any positive compareTo", function() {
var biMin = {
compareTo: function(a) { return 2; }
};
var biMax = {
subtract: function(a) { throw "subtract must not be called"; }
};
var ex = null;
try {
KJUR.crypto.Util.getRandomBigIntegerMinToMax(biMin, biMax);
} catch (err) {
ex = err;
}
equal(ex, "biMin is greater than biMax", "throws before subtraction");
});

test("MessageDigest test", function() {
expect(10);
var md1 = new KJUR.crypto.MessageDigest({"alg": "sha1", "prov": "cryptojs"});
Expand Down
Loading