From a95815cc7a64b0e42804587d4b534f25f51cd454 Mon Sep 17 00:00:00 2001 From: Kagami Hiiragi Date: Tue, 20 Jan 2015 23:17:25 +0300 Subject: [PATCH] Fix for short messages Zero-pad it for secp256k1 --- index.js | 18 ++++++++++++++++-- test.js | 14 +++++++++++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 8d9191b..fadbb73 100644 --- a/index.js +++ b/index.js @@ -62,6 +62,16 @@ function equalConstTime(b1, b2) { */ 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. * @param {Buffer} privateKey - A 32-byte private key @@ -71,7 +81,7 @@ var getPublic = exports.getPublic = secp256k1.createPublicKey; */ exports.sign = function(privateKey, msg) { 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) { 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")); + } }); }; diff --git a/test.js b/test.js index 2324c1a..9cc3558 100644 --- a/test.js +++ b/test.js @@ -1,10 +1,11 @@ var expect = require("chai").expect; -var crypto = require("crypto"); +var createHash = require("crypto").createHash; var bufferEqual = require("buffer-equal"); var eccrypto = require("./"); -var msg = crypto.createHash("sha256").update("test").digest(); -var otherMsg = crypto.createHash("sha256").update("test2").digest(); +var msg = createHash("sha256").update("test").digest(); +var otherMsg = createHash("sha256").update("test2").digest(); +var shortMsg = createHash("sha1").update("test").digest(); var privateKey = Buffer(32); 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() {