Merge pull request #62 from bitcoinjs/compressed-sign

Fix sign/verify for with compressed keys
This commit is contained in:
Kyle Drake 2014-03-11 12:12:52 -07:00
commit 7219c27413
2 changed files with 19 additions and 2 deletions

View file

@ -26,7 +26,7 @@ Message.getHash = function (message) {
return convert.wordArrayToBytes(SHA256(SHA256(convert.bytesToWordArray(buffer)))); return convert.wordArrayToBytes(SHA256(SHA256(convert.bytesToWordArray(buffer))));
}; };
Message.signMessage = function (key, message, compressed) { Message.signMessage = function (key, message) {
var hash = Message.getHash(message); var hash = Message.getHash(message);
var sig = key.sign(hash); var sig = key.sign(hash);
@ -36,7 +36,7 @@ Message.signMessage = function (key, message, compressed) {
var i = ecdsa.calcPubkeyRecoveryParam(key, obj.r, obj.s, hash); var i = ecdsa.calcPubkeyRecoveryParam(key, obj.r, obj.s, hash);
i += 27; i += 27;
if (compressed) i += 4; if (key.compressed) i += 4;
var rBa = obj.r.toByteArrayUnsigned(); var rBa = obj.r.toByteArrayUnsigned();
var sBa = obj.s.toByteArrayUnsigned(); var sBa = obj.s.toByteArrayUnsigned();
@ -58,6 +58,7 @@ Message.verifyMessage = function (address, sig, message) {
var isCompressed = !!(sig.i & 4); var isCompressed = !!(sig.i & 4);
var pubKey = ecdsa.recoverPubKey(sig.r, sig.s, hash, sig.i); var pubKey = ecdsa.recoverPubKey(sig.r, sig.s, hash, sig.i);
pubKey.compressed = isCompressed;
var expectedAddress = pubKey.getBitcoinAddress().toString(); var expectedAddress = pubKey.getBitcoinAddress().toString();

View file

@ -30,5 +30,21 @@ describe('Message', function() {
var sig = Message.signMessage(key, msg); var sig = Message.signMessage(key, msg);
assert.ok(!Message.verifyMessage(addr, sig, msg)); assert.ok(!Message.verifyMessage(addr, sig, msg));
}) })
it('handles compressed keys', function() {
var key = new ECKey(hexToBytes(priv));
key.compressed = true
var addr = key.getBitcoinAddress().toString()
var sig = Message.signMessage(key, msg);
assert.ok(Message.verifyMessage(addr, sig, msg));
// wrong message
assert.ok(!Message.verifyMessage(addr, sig, 'not foobar'));
// wrong address
assert.ok(!Message.verifyMessage('1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a', sig, msg));
})
}) })
}) })