Browse Source

Use secp256k1 c bindings to verify signatures

activeAddress
Braydon Fuller 9 years ago
parent
commit
20cc273a6f
  1. 61
      lib/common/utils.js
  2. 1
      package.json

61
lib/common/utils.js

@ -1,9 +1,10 @@
var $ = require('preconditions').singleton();
var _ = require('lodash');
var Bitcore = require('bitcore-lib');
var crypto = Bitcore.crypto;
var encoding = Bitcore.encoding;
var bitcore = require('bitcore-lib');
var crypto = bitcore.crypto;
var encoding = bitcore.encoding;
var secp256k1 = require('secp256k1');
var Utils = {};
@ -28,28 +29,62 @@ Utils.strip = function(number) {
/* TODO: It would be nice to be compatible with bitcoind signmessage. How
* the hash is calculated there? */
Utils.hashMessage = function(text) {
Utils.hashMessage = function(text, noReverse) {
$.checkArgument(text);
var buf = new Buffer(text);
var ret = crypto.Hash.sha256sha256(buf);
ret = new Bitcore.encoding.BufferReader(ret).readReverse();
if (!noReverse) {
ret = new bitcore.encoding.BufferReader(ret).readReverse();
}
return ret;
};
Utils.verifyMessage = function(text, signature, pubKey) {
Utils.verifyMessage = function(text, signature, publicKey) {
$.checkArgument(text);
$.checkArgument(pubKey);
if (!signature)
var hash = Utils.hashMessage(text, true);
var sig = this._tryImportSignature(signature);
if (!sig) {
return false;
}
var publicKeyBuffer = this._tryImportPublicKey(publicKey);
if (!publicKeyBuffer) {
return false;
}
return this._tryVerifyMessage(hash, sig, publicKeyBuffer);
};
var pub = new Bitcore.PublicKey(pubKey);
var hash = Utils.hashMessage(text);
Utils._tryImportPublicKey = function(publicKey) {
var publicKeyBuffer = publicKey;
try {
if (!Buffer.isBuffer(publicKey)) {
publicKeyBuffer = new Buffer(publicKey, 'hex');
}
return publicKeyBuffer;
} catch(e) {
return false;
}
};
Utils._tryImportSignature = function(signature) {
try {
var signatureBuffer = signature;
if (!Buffer.isBuffer(signature)) {
signatureBuffer = new Buffer(signature, 'hex');
}
return secp256k1.signatureImport(signatureBuffer);
} catch(e) {
return false;
}
};
Utils._tryVerifyMessage = function(hash, sig, publicKeyBuffer) {
try {
var sig = new crypto.Signature.fromString(signature);
return crypto.ECDSA.verify(hash, sig, pub, 'little');
} catch (e) {
return secp256k1.verify(hash, sig, publicKeyBuffer);
} catch(e) {
return false;
}
};

1
package.json

@ -42,6 +42,7 @@
"preconditions": "^1.0.7",
"read": "^1.0.5",
"request": "^2.53.0",
"secp256k1": "^3.1.0",
"sjcl": "^1.0.2",
"socket.io": "^1.3.5",
"socket.io-client": "^1.3.5",

Loading…
Cancel
Save