Skip to content

Commit 8ce83d7

Browse files
committed
Add more checks for privateKeyModInverse
1 parent 9ff1095 commit 8ce83d7

4 files changed

Lines changed: 23 additions & 1 deletion

File tree

lib/elliptic/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ exports.privateKeyNegate = function (privateKey) {
7979

8080
exports.privateKeyModInverse = function (privateKey) {
8181
var bn = new BN(privateKey)
82+
if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID)
83+
8284
return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32)
8385
}
8486

lib/js/index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ exports.privateKeyNegate = function (privateKey) {
2424
}
2525

2626
exports.privateKeyModInverse = function (privateKey) {
27-
return BN.fromBuffer(privateKey).uinvm().toBuffer()
27+
var bn = BN.fromBuffer(privateKey)
28+
if (bn.isOverflow() || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID)
29+
30+
return bn.uinvm().toBuffer()
2831
}
2932

3033
exports.privateKeyTweakAdd = function (privateKey, tweak) {

lib/messages.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"COMPRESSED_TYPE_INVALID": "compressed should be a boolean",
33
"EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer",
44
"EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid",
5+
"EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid",
56
"EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid",
67
"EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range",
78
"EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format",

test/privatekey.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,22 @@ module.exports = function (t, secp256k1) {
158158
t.end()
159159
})
160160

161+
t.test('private key is 0', function (t) {
162+
t.throws(function () {
163+
var privateKey = util.BN_ZERO.toArrayLike(Buffer, 'be', 32)
164+
secp256k1.privateKeyModInverse(privateKey)
165+
}, new RegExp('^Error: ' + messages.EC_PRIVATE_KEY_RANGE_INVALID + '$'))
166+
t.end()
167+
})
168+
169+
t.test('private key equal to N', function (t) {
170+
t.throws(function () {
171+
var privateKey = util.ec.curve.n.toArrayLike(Buffer, 'be', 32)
172+
secp256k1.privateKeyModInverse(privateKey)
173+
}, new RegExp('^Error: ' + messages.EC_PRIVATE_KEY_RANGE_INVALID + '$'))
174+
t.end()
175+
})
176+
161177
util.repeat(t, 'random tests', util.env.repeat, function (t) {
162178
var privateKey = util.getPrivateKey()
163179

0 commit comments

Comments
 (0)