2014-12-25 15:45:43 +00:00
|
|
|
/**
|
|
|
|
* Browser eccrypto implementation.
|
|
|
|
*/
|
|
|
|
|
2015-01-07 18:47:41 +00:00
|
|
|
// NOTE(Kagami): We don't use promise shim in Browser implementation
|
|
|
|
// because it's supported natively in new browsers (see
|
|
|
|
// <http://caniuse.com/#feat=promises>) and we can use only new browsers
|
|
|
|
// because of the WebCryptoAPI (see
|
|
|
|
// <http://caniuse.com/#feat=cryptography>).
|
|
|
|
|
2014-12-25 15:45:43 +00:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
var EC = require("elliptic").ec;
|
|
|
|
|
|
|
|
var ec = new EC("secp256k1");
|
|
|
|
|
2015-01-12 17:50:21 +00:00
|
|
|
function assert(condition, message) {
|
|
|
|
if (!condition) {
|
|
|
|
throw new Error(message || "Assertion failed");
|
2015-01-05 23:49:32 +00:00
|
|
|
}
|
2015-01-12 17:50:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
exports.getPublic = function(privateKey) {
|
|
|
|
assert(privateKey.length === 32, "Bad private key");
|
2014-12-25 15:45:43 +00: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);
|
2015-01-12 17:50:21 +00:00
|
|
|
return new Promise(function(resolve) {
|
|
|
|
resolve(new Buffer(key.sign(msg).toDER()));
|
|
|
|
});
|
2014-12-25 15:45:43 +00:00
|
|
|
};
|
|
|
|
|
2014-12-26 17:48:39 +00:00
|
|
|
exports.verify = function(key, msg, sig) {
|
|
|
|
key = ec.keyPair(key);
|
2015-01-12 17:50:21 +00:00
|
|
|
return new Promise(function(resolve, reject) {
|
|
|
|
return key.verify(msg, sig) ? resolve() : reject();
|
|
|
|
});
|
2014-12-25 15:45:43 +00:00
|
|
|
};
|