Skip to content

Commit d7c2e4d

Browse files
author
GreenAddress.it
committed
Uses low 's' values for signatures
1 parent 3219e5e commit d7c2e4d

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/ecdsa.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,11 @@ var ecdsa = {
6969

7070
var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
7171

72+
if (s.compareTo(n.divide(BigInteger.valueOf(2))) > 0) {
73+
// Make 's' value 'low', as per https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures
74+
s = n.subtract(s);
75+
}
76+
7277
return ecdsa.serializeSig(r, s)
7378
},
7479

test/eckey.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
var assert = require('assert')
2+
var ecdsa = require('../src/ecdsa.js')
3+
var sec = require('../src/jsbn/sec.js')
4+
var BigInteger = require('../src/jsbn/jsbn.js')
5+
var ecparams = sec("secp256k1")
26
var ECKey = require('../src/eckey.js').ECKey
37
var ECPubKey = require('../src/eckey.js').ECPubKey
48
var convert = require('../src/convert.js')
@@ -148,6 +152,19 @@ describe('ECKey', function() {
148152
assert(priv.verify(message, signature))
149153
})
150154

155+
it('should sign with low S value', function() {
156+
var priv = new ECKey(hpriv)
157+
var signature = priv.sign(message)
158+
var parsed = ecdsa.parseSig(signature)
159+
160+
// Check that the 's' value is 'low', to prevent possible transaction malleability as per
161+
// https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#low-s-values-in-signatures
162+
assert(parsed.s.compareTo(ecparams.getN().divide(BigInteger.valueOf(2))) <= 0)
163+
164+
assert(priv.verify(message, signature))
165+
})
166+
167+
151168
it('should verify against the public key', function() {
152169
var priv = new ECKey(hpriv)
153170
var pub = new ECPubKey(hcpub, true)

0 commit comments

Comments
 (0)