Skip to content

Commit 9bb8d67

Browse files
Kr0emerdavidlehn
authored andcommitted
fix(jsbn): prevent modInverse hang for zero input
1 parent ceb5fa0 commit 9bb8d67

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

lib/jsbn.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,7 @@ function bnpModInt(n) {
11221122

11231123
// (public) 1/this % m (HAC 14.61)
11241124
function bnModInverse(m) {
1125+
if(this.signum() == 0) return BigInteger.ZERO;
11251126
var ac = m.isEven();
11261127
if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
11271128
var u = m.clone(), v = this.clone();

tests/unit/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
require('./forge');
2+
require('./jsbn');
23
require('./util');
34
require('./md5');
45
require('./sha1');

tests/unit/jsbn.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
var ASSERT = require('assert');
2+
3+
(function() {
4+
if(typeof process === 'undefined' ||
5+
!process.versions || !process.versions.node) {
6+
return;
7+
}
8+
9+
var moduleRequire = module.require ? module.require.bind(module) : require;
10+
var PATH = moduleRequire('path');
11+
var spawnSync = moduleRequire('child_process').spawnSync;
12+
13+
describe('jsbn', function() {
14+
it('should return 0 for BigInteger(0).modInverse(3) without hanging', function() {
15+
var script = [
16+
'var JSBN = require("./lib/jsbn");',
17+
'var BigInteger = JSBN.BigInteger;',
18+
'var zero = new BigInteger("0", 10);',
19+
'var mod = new BigInteger("3", 10);',
20+
'var inv = zero.modInverse(mod);',
21+
'process.stdout.write(inv.toString());'
22+
].join('\n');
23+
24+
var result = spawnSync(process.execPath, ['-e', script], {
25+
cwd: PATH.join(__dirname, '../..'),
26+
encoding: 'utf8',
27+
timeout: 2000
28+
});
29+
30+
if(result.error) {
31+
if(result.error.code === 'EPERM') {
32+
this.skip();
33+
return;
34+
}
35+
if(result.error.code === 'ETIMEDOUT') {
36+
ASSERT.fail('BigInteger(0).modInverse(3) timed out.');
37+
}
38+
throw result.error;
39+
}
40+
41+
ASSERT.equal(result.status, 0, result.stderr);
42+
ASSERT.equal(result.stdout, '0');
43+
});
44+
});
45+
})();

0 commit comments

Comments
 (0)