2014-12-25 16:45:43 +01:00
|
|
|
/**
|
|
|
|
* Browser eccrypto implementation.
|
|
|
|
*/
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
require("es6-promise").polyfill();
|
2014-12-27 13:47:25 +01:00
|
|
|
var assert = require("assert");
|
2014-12-25 16:45:43 +01:00
|
|
|
var EC = require("elliptic").ec;
|
|
|
|
|
|
|
|
var ec = new EC("secp256k1");
|
|
|
|
|
|
|
|
exports.getPublic = function(privateKey) {
|
2014-12-27 13:47:25 +01:00
|
|
|
// `elliptic` doesn't have such checkings so we do it ourself. We
|
|
|
|
// should always ensure that library user doesn't try to do something
|
|
|
|
// dumb.
|
|
|
|
assert(privateKey.length === 32, "Bad private key");
|
2014-12-25 16:45:43 +01:00
|
|
|
// XXX(Kagami): `elliptic.utils.encode` returns array for every
|
|
|
|
// encoding except `hex`.
|
|
|
|
return new Buffer(ec.keyPair(privateKey).getPublic("arr"));
|
|
|
|
};
|
|
|
|
|
|
|
|
exports.sign = function(privateKey, msg) {
|
|
|
|
var key = ec.keyPair(privateKey);
|
|
|
|
var sig;
|
|
|
|
try {
|
|
|
|
sig = new Buffer(key.sign(msg).toDER());
|
|
|
|
return Promise.resolve(sig);
|
|
|
|
} catch(e) {
|
|
|
|
return Promise.reject();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-12-26 18:48:39 +01:00
|
|
|
exports.verify = function(key, msg, sig) {
|
|
|
|
key = ec.keyPair(key);
|
2014-12-25 16:45:43 +01:00
|
|
|
if (key.verify(msg, sig)) {
|
|
|
|
return Promise.resolve();
|
|
|
|
} else {
|
|
|
|
return Promise.reject();
|
|
|
|
}
|
|
|
|
};
|