js-crypto-ec
Version:
Universal Module for Elliptic Curve Cryptography (ECDSA and ECDH) in JavaScript
320 lines • 16.3 kB
JavaScript
"use strict";
/**
* ec.ts
*/
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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deriveSecret = exports.verify = exports.sign = exports.generateKey = void 0;
var util = __importStar(require("js-crypto-env"));
var webapi = __importStar(require("./webapi"));
var nodeapi = __importStar(require("./nodeapi"));
var purejs = __importStar(require("./purejs"));
/**
* Generate elliptic curve cryptography public/private key pair. Generated keys are in JWK.
* @param {String} [namedCurve='P-256'] - Name of curve like 'P-256'.
* @return {Promise<{publicKey: JsonWebKey, privateKey: JsonWebKey }>} - The generated keys.
* @throws {Error} - Throws if UnsupportedEnvironment, i.e., neither WebCrypto, NodeCrypto, nor PureJS codes works.
*/
var generateKey = function (namedCurve) {
if (namedCurve === void 0) { namedCurve = 'P-256'; }
return __awaiter(void 0, void 0, void 0, function () {
var env, pure, keyPair, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
env = util.getCrypto();
pure = false;
_a.label = 1;
case 1:
_a.trys.push([1, 8, , 12]);
if (!(env.name === 'webCrypto' && typeof env.crypto.generateKey === 'function' && typeof env.crypto.exportKey === 'function')) return [3 /*break*/, 3];
return [4 /*yield*/, webapi.generateKey(namedCurve, env.crypto)];
case 2:
keyPair = _a.sent();
return [3 /*break*/, 7];
case 3:
if (!(env.name === 'nodeCrypto')) return [3 /*break*/, 5];
return [4 /*yield*/, nodeapi.generateKey(namedCurve, env.crypto)];
case 4:
keyPair = _a.sent();
return [3 /*break*/, 7];
case 5:
pure = true;
return [4 /*yield*/, purejs.generateKey(namedCurve)];
case 6:
keyPair = _a.sent();
_a.label = 7;
case 7: return [2 /*return*/, keyPair];
case 8:
e_1 = _a.sent();
if (!pure) return [3 /*break*/, 9];
if (e_1 instanceof Error) {
throw new Error("UnsupportedEnvironment: ".concat(e_1.message));
}
else {
throw new Error('UnsupportedEnvironment');
}
return [3 /*break*/, 11];
case 9: return [4 /*yield*/, purejs.generateKey(namedCurve)
.catch(function (finalError) {
throw new Error("FailedBothNativeAndPureJSEnvs: ".concat(finalError.message));
})];
case 10:
keyPair = _a.sent();
return [2 /*return*/, keyPair];
case 11: return [3 /*break*/, 12];
case 12: return [2 /*return*/];
}
});
});
};
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='SHA-256'] - Name of hash algorithm used in singing, like 'SHA-256'.
* @param {String} [signatureFormat='raw'] - Signature format. 'raw' indicates the purely raw byte array of signature. It can also take 'der', and then the output is ASN.1 DER formatted.
* @return {Promise<Uint8Array>} - Output signature byte array in raw or der format.
* @throws {Error} - Throws if UnsupportedEnvironment, i.e., neither WebCrypto, NodeCrypto, nor PureJS codes works.
*/
var sign = function (msg, privateJwk, hash, signatureFormat) {
if (hash === void 0) { hash = 'SHA-256'; }
if (signatureFormat === void 0) { signatureFormat = 'raw'; }
return __awaiter(void 0, void 0, void 0, function () {
var env, pure, signature, e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
env = util.getCrypto();
pure = false;
_a.label = 1;
case 1:
_a.trys.push([1, 8, , 12]);
if (!(env.name === 'webCrypto' && typeof env.crypto.importKey === 'function' && typeof env.crypto.sign === 'function')) return [3 /*break*/, 3];
return [4 /*yield*/, webapi.sign(msg, privateJwk, hash, signatureFormat, env.crypto)];
case 2:
signature = _a.sent();
return [3 /*break*/, 7];
case 3:
if (!(env.name === 'nodeCrypto')) return [3 /*break*/, 5];
return [4 /*yield*/, nodeapi.sign(msg, privateJwk, hash, signatureFormat, env.crypto)];
case 4:
signature = _a.sent();
return [3 /*break*/, 7];
case 5:
pure = true;
return [4 /*yield*/, purejs.sign(msg, privateJwk, hash, signatureFormat)];
case 6:
signature = _a.sent();
_a.label = 7;
case 7: return [2 /*return*/, signature];
case 8:
e_2 = _a.sent();
if (!pure) return [3 /*break*/, 9];
if (e_2 instanceof Error) {
throw new Error("UnsupportedEnvironment: ".concat(e_2.message));
}
else {
throw new Error('UnsupportedEnvironment');
}
return [3 /*break*/, 11];
case 9: return [4 /*yield*/, purejs.sign(msg, privateJwk, hash, signatureFormat)
.catch(function (finalError) {
throw new Error("FailedBothNativeAndPureJSEnvs: ".concat(finalError.message));
})];
case 10:
signature = _a.sent();
return [2 /*return*/, signature];
case 11: return [3 /*break*/, 12];
case 12: return [2 /*return*/];
}
});
});
};
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='SHA-256'] - Name of hash algorithm used in singing, like 'SHA-256'.
* @param {String} [signatureFormat='raw'] - Signature format. 'raw' indicates the purely raw byte array of signature. It can also take 'der', and then the input must be in ASN.1 DER format.
* @return {Promise<boolean>} - The result of verification.
* @throws {Error} - Throws if UnsupportedEnvironment, i.e., neither WebCrypto, NodeCrypto, nor PureJS codes works.
*/
var verify = function (msg, signature, publicJwk, hash, signatureFormat) {
if (hash === void 0) { hash = 'SHA-256'; }
if (signatureFormat === void 0) { signatureFormat = 'raw'; }
return __awaiter(void 0, void 0, void 0, function () {
var env, pure, valid, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
env = util.getCrypto();
pure = false;
_a.label = 1;
case 1:
_a.trys.push([1, 8, , 12]);
if (!(env.name === 'webCrypto' && typeof env.crypto.importKey === 'function' && typeof env.crypto.sign === 'function')) return [3 /*break*/, 3];
return [4 /*yield*/, webapi.verify(msg, signature, publicJwk, hash, signatureFormat, env.crypto)];
case 2:
valid = _a.sent();
return [3 /*break*/, 7];
case 3:
if (!(env.name === 'nodeCrypto')) return [3 /*break*/, 5];
return [4 /*yield*/, nodeapi.verify(msg, signature, publicJwk, hash, signatureFormat, env.crypto)];
case 4:
valid = _a.sent();
return [3 /*break*/, 7];
case 5:
pure = true;
return [4 /*yield*/, purejs.verify(msg, signature, publicJwk, hash, signatureFormat)];
case 6:
valid = _a.sent();
_a.label = 7;
case 7: return [2 /*return*/, valid];
case 8:
e_3 = _a.sent();
if (!pure) return [3 /*break*/, 9];
if (e_3 instanceof Error) {
throw new Error("UnsupportedEnvironment: ".concat(e_3.message));
}
else {
throw new Error('UnsupportedEnvironment');
}
return [3 /*break*/, 11];
case 9: return [4 /*yield*/, purejs.verify(msg, signature, publicJwk, hash, signatureFormat)
.catch(function (finalError) {
throw new Error("FailedBothNativeAndPureJSEnvs: ".concat(finalError.message));
})];
case 10:
valid = _a.sent();
return [2 /*return*/, valid];
case 11: return [3 /*break*/, 12];
case 12: return [2 /*return*/];
}
});
});
};
exports.verify = verify;
/**
* ECDH: Elliptic Curve Diffie-Hellman Key Exchange, which derives shared secret from my private key and destination's public key.
* **NOTE** We SHOULD NOT use the derived secret as an encryption key directly.
* We should employ an appropriate key derivation procedure like HKDF to use the secret for symmetric key encryption.
* @param {JsonWebKey} publicJwk - Remote public key object in JWK format.
* @param {JsonWebKey} privateJwk - Local (my) private key object in JWK format.
* @return {Promise<Uint8Array>} - The derived master secret via ECDH.
* @throws {Error} - Throws if UnsupportedEnvironment, i.e., neither WebCrypto, NodeCrypto, nor PureJS codes works.
*/
var deriveSecret = function (publicJwk, privateJwk) { return __awaiter(void 0, void 0, void 0, function () {
var env, pure, secret, e_4;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// assertion
if (publicJwk.crv !== privateJwk.crv)
throw new Error('UnmatchedCurveName');
env = util.getCrypto();
pure = false;
_a.label = 1;
case 1:
_a.trys.push([1, 7, , 11]);
if (!(env.name === 'webCrypto' && typeof env.crypto.importKey === 'function' && typeof env.crypto.deriveBits === 'function')) return [3 /*break*/, 3];
return [4 /*yield*/, webapi.deriveSecret(publicJwk, privateJwk, env.crypto)];
case 2:
secret = _a.sent();
return [3 /*break*/, 6];
case 3:
if (!(env.name === 'nodeCrypto')) return [3 /*break*/, 4];
secret = nodeapi.deriveSecret(publicJwk, privateJwk, env.crypto);
return [3 /*break*/, 6];
case 4:
pure = true;
return [4 /*yield*/, purejs.deriveSecret(publicJwk, privateJwk)];
case 5:
secret = _a.sent();
_a.label = 6;
case 6: return [2 /*return*/, secret];
case 7:
e_4 = _a.sent();
if (!pure) return [3 /*break*/, 8];
if (e_4 instanceof Error) {
throw new Error("UnsupportedEnvironment: ".concat(e_4.message));
}
else {
throw new Error('UnsupportedEnvironment');
}
return [3 /*break*/, 10];
case 8: return [4 /*yield*/, purejs.deriveSecret(publicJwk, privateJwk)
.catch(function (finalError) {
throw new Error("FailedBothNativeAndPureJSEnvs: ".concat(finalError.message));
})];
case 9:
secret = _a.sent();
return [2 /*return*/, secret];
case 10: return [3 /*break*/, 11];
case 11: return [2 /*return*/];
}
});
}); };
exports.deriveSecret = deriveSecret;
//# sourceMappingURL=ec.js.map