js-crypto-ec
Version:
Universal Module for Elliptic Curve Cryptography (ECDSA and ECDH) in JavaScript
182 lines • 9.62 kB
JavaScript
;
/**
* webapi.js
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deriveSecret = exports.verify = exports.sign = exports.generateKey = void 0;
var js_encoding_utils_1 = __importDefault(require("js-encoding-utils"));
var asn1enc = __importStar(require("./asn1enc"));
/**
* Generate elliptic curve cryptography public/private key pair. Generated keys are in JWK.
* @param {String} namedCurve - Name of curve like 'P-256'.
* @param {Object} webCrypto - WebCryptoSubtle object.
* @return {Promise<{publicKey: JsonWebKey, privateKey: JsonWebKey}>} - The generated keys.
*/
var generateKey = function (namedCurve, webCrypto) { return __awaiter(void 0, void 0, void 0, function () {
var keys, publicKey, privateKey;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, webCrypto.generateKey({ name: 'ECDSA', namedCurve: namedCurve, hash: { name: 'SHA-256' } }, true, ['sign', 'verify'])];
case 1:
keys = _a.sent();
return [4 /*yield*/, webCrypto.exportKey('jwk', keys.publicKey)];
case 2:
publicKey = _a.sent();
return [4 /*yield*/, webCrypto.exportKey('jwk', keys.privateKey)];
case 3:
privateKey = _a.sent();
// delete optional entries to export as general ecdsa/ecdh key
['key_ops', 'alg', 'ext'].forEach(function (elem) {
delete publicKey[elem];
delete privateKey[elem];
});
return [2 /*return*/, { publicKey: publicKey, privateKey: privateKey }];
}
});
}); };
exports.generateKey = generateKey;
/**
* Sign message with ECDSA.
* @param {Uint8Array} msg - Byte array of message to be signed.
* @param {JsonWebKey} privateJwk - Private key object in JWK format.
* @param {String} hash - Name of hash algorithm used in singing, like 'SHA-256'.
* @param {String} signatureFormat - Signature format, 'raw' or 'der'
* @param {Object} webCrypto - WebCryptoSubtle object.
* @return {Promise<Uint8Array>} - Output signature byte array in raw or der format.
*/
var sign = function (msg, privateJwk, hash, signatureFormat, webCrypto) { return __awaiter(void 0, void 0, void 0, function () {
var algo, key, signature;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
algo = { name: 'ECDSA', namedCurve: privateJwk.crv, hash: { name: hash } };
return [4 /*yield*/, webCrypto.importKey('jwk', privateJwk, algo, false, ['sign'])];
case 1:
key = _a.sent();
return [4 /*yield*/, webCrypto.sign(algo, key, msg)];
case 2:
signature = _a.sent();
return [2 /*return*/, (signatureFormat === 'raw')
? new Uint8Array(signature)
: asn1enc.encodeAsn1Signature(new Uint8Array(signature), privateJwk.crv)];
}
});
}); };
exports.sign = sign;
/**
* Verify signature with ECDSA.
* @param {Uint8Array} msg - Byte array of message that have been signed.
* @param {Uint8Array} signature - Byte array of signature for the given message.
* @param {JsonWebKey} publicJwk - Public key object in JWK format.
* @param {String} hash - Name of hash algorithm used in singing, like 'SHA-256'.
* @param {String} signatureFormat - Signature format,'raw' or 'der'.
* @param {Object} webCrypto - WebCryptoSubtle object.
* @return {Promise<boolean>} - The result of verification.
*/
var verify = function (msg, signature, publicJwk, hash, signatureFormat, webCrypto) { return __awaiter(void 0, void 0, void 0, function () {
var algo, key, rawSignature;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
algo = { name: 'ECDSA', namedCurve: publicJwk.crv, hash: { name: hash } };
return [4 /*yield*/, webCrypto.importKey('jwk', publicJwk, algo, false, ['verify'])];
case 1:
key = _a.sent();
rawSignature = (signatureFormat === 'raw')
? signature
: asn1enc.decodeAsn1Signature(signature, publicJwk.crv);
return [2 /*return*/, webCrypto.verify(algo, key, rawSignature, msg)];
}
});
}); };
exports.verify = verify;
/**
* Key Derivation for ECDH, Elliptic Curve Diffie-Hellman Key Exchange.
* @param {JsonWebKey} publicJwk - Remote public key object in JWK format.
* @param {JsonWebKey} privateJwk - Local (my) private key object in JWK format.
* @param {Object} webCrypto - WebCryptoSubtle object.
* @return {Promise<Uint8Array>} - The derived master secret via ECDH.
*/
var deriveSecret = function (publicJwk, privateJwk, webCrypto) { return __awaiter(void 0, void 0, void 0, function () {
var algo, privateKey, publicKey, bitLen, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
algo = { name: 'ECDH', namedCurve: privateJwk.crv };
return [4 /*yield*/, webCrypto.importKey('jwk', privateJwk, algo, false, ['deriveBits'])];
case 1:
privateKey = _b.sent();
return [4 /*yield*/, webCrypto.importKey('jwk', publicJwk, algo, false, [])];
case 2:
publicKey = _b.sent();
bitLen = function () { var arr = js_encoding_utils_1.default.encoder.decodeBase64Url(privateJwk.x); return 8 * arr.length; };
_a = Uint8Array.bind;
return [4 /*yield*/, webCrypto.deriveBits(Object.assign(algo, { public: publicKey }), privateKey, bitLen())];
case 3: return [2 /*return*/, new (_a.apply(Uint8Array, [void 0, _b.sent()]))()];
}
});
}); };
exports.deriveSecret = deriveSecret;
//# sourceMappingURL=webapi.js.map