Skip to content

Commit

Permalink
Merge pull request from GHSA-5h4j-qrvg-9xhw
Browse files Browse the repository at this point in the history
  • Loading branch information
bifurcation authored Feb 8, 2023
1 parent e95481a commit 901d915
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/deps/ecc/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ function barrettRevert(x) { return x; }

// x = x mod m (HAC 14.42)
function barrettReduce(x) {
if (x.s < 0) { throw Error("Barrett reduction on negative input"); }
x.drShiftTo(this.m.t-1,this.r2);
if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
Expand Down
9 changes: 9 additions & 0 deletions lib/deps/forge.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,13 @@ modeRaw.prototype.decrypt = function(input, output, finish) {
forge.cipher.registerAlgorithm(name, factory);
})();

// Ensure that the jsbn modInverse function always returns a positive result
const originalModInverse = forge.jsbn.BigInteger.prototype.modInverse;
const positiveModInverse = function(m) {
const inv = originalModInverse.apply(this, [m]);
return inv.mod(m);
}

forge.jsbn.BigInteger.prototype.modInverse = positiveModInverse;

module.exports = forge;
29 changes: 29 additions & 0 deletions test/algorithms/ecc-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*!
*
* Copyright (c) 2015 Cisco Systems, Inc. See LICENSE file.
*/
"use strict";

var assert = require("chai").assert;

const CURVES = require('../../lib/deps/ecc/curves.js');
const BigInteger = require('../../lib/deps/forge').jsbn.BigInteger;

describe("ecc/positive", function() {
const negativeModInverseCases = [
'101067240514044546216936289506154965497874315269115226505131909313278720169941',
'47260992668897782856940293132731814279826643476197468731642996160637470667669',
]

const p = CURVES["P-256"].curve.p;

const runner = () => {
for (const kStr of negativeModInverseCases) {
const k = new BigInteger(kStr);
const kinv = k.modInverse(p);
assert.isAtLeast(kinv.s, 0, "Negative mod inverse");
}
};

it('normalizes negative modular inverses', runner);
})

0 comments on commit 901d915

Please sign in to comment.