Skip to content

Commit 55c2388

Browse files
committed
Fix negating a zero private key in JS, add more tests
1 parent b1b2e56 commit 55c2388

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 ecparams.n.sub(bn).toArrayLike(Buffer, 'be', 32)
77+
return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).toArrayLike(Buffer, 'be', 32)
7878
}
7979

8080
exports.privateKeyModInverse = function (privateKey) {

lib/js/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ exports.privateKeyExport = function (privateKey, compressed) {
2020
}
2121

2222
exports.privateKeyNegate = function (privateKey) {
23-
return BN.n.sub(BN.fromBuffer(privateKey)).toBuffer()
23+
var bn = BN.fromBuffer(privateKey)
24+
return bn.isZero() ? Buffer.alloc(32) : BN.n.sub(bn).toBuffer()
2425
}
2526

2627
exports.privateKeyModInverse = function (privateKey) {

test/privatekey.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,26 @@ module.exports = function (t, secp256k1) {
129129
t.end()
130130
})
131131

132+
t.test('private key is 0', function (t) {
133+
var privateKey = util.BN_ZERO.toArrayLike(Buffer, 'be', 32)
134+
135+
var expected = Buffer.alloc(32)
136+
var result = secp256k1.privateKeyNegate(privateKey)
137+
t.same(result, expected)
138+
139+
t.end()
140+
})
141+
142+
t.test('private key equal to N', function (t) {
143+
var privateKey = util.ec.curve.n.toArrayLike(Buffer, 'be', 32)
144+
145+
var expected = Buffer.alloc(32)
146+
var result = secp256k1.privateKeyNegate(privateKey)
147+
t.same(result, expected)
148+
149+
t.end()
150+
})
151+
132152
util.repeat(t, 'random tests', util.env.repeat, function (t) {
133153
var privateKey = util.getPrivateKey()
134154

0 commit comments

Comments
 (0)