2014-12-24 00:14:28 +01:00
|
|
|
/**
|
|
|
|
* Node.js eccrypto implementation.
|
|
|
|
* @module eccrypto
|
|
|
|
*/
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
require("es6-promise").polyfill();
|
2014-12-23 21:28:40 +01:00
|
|
|
var secp256k1 = require("secp256k1");
|
|
|
|
|
2014-12-24 00:14:28 +01:00
|
|
|
/**
|
|
|
|
* Compute the public key for a given private key.
|
|
|
|
* @param {Buffer} publicKey A 32-byte private key
|
|
|
|
* @return {Buffer} A 65-byte public key
|
|
|
|
*/
|
2014-12-26 18:48:39 +01:00
|
|
|
function getPublic(privateKey) {
|
2014-12-24 00:14:28 +01:00
|
|
|
return secp256k1.createPublicKey(privateKey);
|
|
|
|
};
|
2014-12-26 18:48:39 +01:00
|
|
|
exports.getPublic = getPublic;
|
2014-12-24 00:14:28 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Create an ECDSA signature.
|
|
|
|
* @param {Buffer} privateKey A 32-byte private key
|
|
|
|
* @param {Buffer} msg The message being signed
|
2014-12-25 16:45:43 +01:00
|
|
|
* @return {Promise.<Buffer,undefined>} A promise that resolves with the
|
|
|
|
* signature or rejects on bad private key/message.
|
2014-12-24 00:14:28 +01:00
|
|
|
*/
|
|
|
|
// FIXME(Kagami): What to do in case of invalid nonce?
|
|
|
|
exports.sign = function(privateKey, msg) {
|
|
|
|
return new Promise(function(resolve, reject) {
|
|
|
|
try {
|
|
|
|
secp256k1.sign(privateKey, msg, function(code, sig) {
|
|
|
|
if (code === 1) {
|
|
|
|
resolve(sig);
|
|
|
|
} else {
|
2014-12-25 16:45:43 +01:00
|
|
|
reject();
|
2014-12-24 00:14:28 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
} catch(e) {
|
2014-12-25 16:45:43 +01:00
|
|
|
reject();
|
2014-12-24 00:14:28 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Verify an ECDSA signature.
|
2014-12-26 18:48:39 +01:00
|
|
|
* @param {Buffer} key Private or public key
|
2014-12-24 00:14:28 +01:00
|
|
|
* @param {Buffer} msg The message being verified
|
|
|
|
* @param {Buffer} sig The signature
|
2014-12-25 16:45:43 +01:00
|
|
|
* @return {Promise} A promise that resolves on correct signature and
|
|
|
|
* rejects on bad signature/public key.
|
2014-12-24 00:14:28 +01:00
|
|
|
*/
|
2014-12-26 18:48:39 +01:00
|
|
|
exports.verify = function(key, msg, sig) {
|
|
|
|
var publicKey = key.length === 32 ? getPublic(key) : key;
|
2014-12-24 00:14:28 +01:00
|
|
|
return new Promise(function(resolve, reject) {
|
|
|
|
secp256k1.verify(publicKey, msg, sig, function(code) {
|
|
|
|
if (code === 1) {
|
|
|
|
resolve();
|
|
|
|
} else {
|
2014-12-25 16:45:43 +01:00
|
|
|
reject();
|
2014-12-24 00:14:28 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|