Fix for short messages

Zero-pad it for secp256k1
This commit is contained in:
Kagami Hiiragi 2015-01-20 23:17:25 +03:00
parent 1ac7cc1d46
commit a95815cc7a
2 changed files with 27 additions and 5 deletions

View File

@ -62,6 +62,16 @@ function equalConstTime(b1, b2) {
*/ */
var getPublic = exports.getPublic = secp256k1.createPublicKey; var getPublic = exports.getPublic = secp256k1.createPublicKey;
function padMsg(msg) {
var zeroes;
if (msg.length < 32) {
zeroes = new Buffer(32 - msg.length);
zeroes.fill(0);
msg = Buffer.concat([zeroes, msg]);
}
return msg;
}
/** /**
* Create an ECDSA signature. * Create an ECDSA signature.
* @param {Buffer} privateKey - A 32-byte private key * @param {Buffer} privateKey - A 32-byte private key
@ -71,7 +81,7 @@ var getPublic = exports.getPublic = secp256k1.createPublicKey;
*/ */
exports.sign = function(privateKey, msg) { exports.sign = function(privateKey, msg) {
return new promise(function(resolve) { return new promise(function(resolve) {
resolve(secp256k1.sign(privateKey, msg)); resolve(secp256k1.sign(privateKey, padMsg(msg)));
}); });
}; };
@ -85,7 +95,11 @@ exports.sign = function(privateKey, msg) {
*/ */
exports.verify = function(publicKey, msg, sig) { exports.verify = function(publicKey, msg, sig) {
return new promise(function(resolve, reject) { return new promise(function(resolve, reject) {
return secp256k1.verify(publicKey, msg, sig) === 1 ? resolve() : reject(); if (secp256k1.verify(publicKey, padMsg(msg), sig) === 1) {
resolve();
} else {
reject(new Error("Bad signature"));
}
}); });
}; };

14
test.js
View File

@ -1,10 +1,11 @@
var expect = require("chai").expect; var expect = require("chai").expect;
var crypto = require("crypto"); var createHash = require("crypto").createHash;
var bufferEqual = require("buffer-equal"); var bufferEqual = require("buffer-equal");
var eccrypto = require("./"); var eccrypto = require("./");
var msg = crypto.createHash("sha256").update("test").digest(); var msg = createHash("sha256").update("test").digest();
var otherMsg = crypto.createHash("sha256").update("test2").digest(); var otherMsg = createHash("sha256").update("test2").digest();
var shortMsg = createHash("sha1").update("test").digest();
var privateKey = Buffer(32); var privateKey = Buffer(32);
privateKey.fill(1); privateKey.fill(1);
@ -84,6 +85,13 @@ describe("ECDSA", function() {
}); });
}); });
}); });
it("should allow to sign and verify messages less than 32 bytes", function() {
return eccrypto.sign(privateKey, shortMsg).then(function(sig) {
expect(Buffer.isBuffer(sig)).to.be.true;
return eccrypto.verify(publicKey, shortMsg, sig);
});
});
}); });
describe("ECDH", function() { describe("ECDH", function() {