eccrypto/browser.js

43 lines
1.1 KiB
JavaScript
Raw Normal View History

/**
* 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>).
"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");
// 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-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();
});
};