Skip to content

Commit 28cb4ba

Browse files
committed
Fix input overflow handling during negation
1 parent 55c2388 commit 28cb4ba

3 files changed

Lines changed: 23 additions & 2 deletions

File tree

lib/elliptic/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ exports.privateKeyExport = function (privateKey, compressed) {
7474

7575
exports.privateKeyNegate = function (privateKey) {
7676
var bn = new BN(privateKey)
77-
return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).toArrayLike(Buffer, 'be', 32)
77+
return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32)
7878
}
7979

8080
exports.privateKeyModInverse = function (privateKey) {

lib/js/index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,18 @@ exports.privateKeyExport = function (privateKey, compressed) {
2121

2222
exports.privateKeyNegate = function (privateKey) {
2323
var bn = BN.fromBuffer(privateKey)
24-
return bn.isZero() ? Buffer.alloc(32) : BN.n.sub(bn).toBuffer()
24+
25+
if (bn.isZero()) {
26+
return Buffer.alloc(32)
27+
}
28+
29+
if (bn.ucmp(BN.n) !== 0) {
30+
while (bn.isOverflow()) {
31+
bn.isub(BN.n)
32+
}
33+
}
34+
35+
return BN.n.sub(bn).toBuffer()
2536
}
2637

2738
exports.privateKeyModInverse = function (privateKey) {

test/privatekey.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,16 @@ module.exports = function (t, secp256k1) {
149149
t.end()
150150
})
151151

152+
t.test('private key overflow', function (t) {
153+
var privateKey = util.ec.curve.n.addn(10).toArrayLike(Buffer, 'be', 32)
154+
155+
var expected = util.ec.curve.n.subn(10).toArrayLike(Buffer, 'be', 32)
156+
var result = secp256k1.privateKeyNegate(privateKey)
157+
t.same(result, expected)
158+
159+
t.end()
160+
})
161+
152162
util.repeat(t, 'random tests', util.env.repeat, function (t) {
153163
var privateKey = util.getPrivateKey()
154164

0 commit comments

Comments
 (0)