UNPKG

js-crypto-ec

Version:

Universal Module for Elliptic Curve Cryptography (ECDSA and ECDH) in JavaScript

185 lines 9.99 kB
"use strict"; /** * nodeapi.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 params_1 = require("./params"); var asn1enc = __importStar(require("./asn1enc")); var js_crypto_key_utils_1 = require("js-crypto-key-utils"); var js_encoding_utils_1 = __importDefault(require("js-encoding-utils")); /** * Generate elliptic curve cryptography public/private key pair. Generated keys are in JWK. * @param {String} namedCurve - Name of curve like 'P-256'. * @param {Object} nodeCrypto - NodeCrypto object. * @return {Promise<{publicKey: JsonWebKey, privateKey: JsonWebKey}>} - The generated keys. * @throws {Error} - Throws if NotPublic/PrivateKeyForECCKeyGenNode */ var generateKey = function (namedCurve, nodeCrypto) { return __awaiter(void 0, void 0, void 0, function () { var ecdh, publicOct, privateOct, publicKey, publicJwk, privateKey, privateJwk; return __generator(this, function (_a) { switch (_a.label) { case 0: ecdh = nodeCrypto.ECDH(params_1.namedCurves[namedCurve].nodeName); ecdh.generateKeys(); publicOct = new Uint8Array(ecdh.getPublicKey()); privateOct = new Uint8Array(ecdh.getPrivateKey()); publicKey = new js_crypto_key_utils_1.Key('oct', publicOct, { namedCurve: namedCurve }); if (publicKey.isPrivate) throw new Error('NotPublicKeyForECCKeyGenNode'); return [4 /*yield*/, publicKey.export('jwk', { outputPublic: true })]; case 1: publicJwk = _a.sent(); privateKey = new js_crypto_key_utils_1.Key('oct', privateOct, { namedCurve: namedCurve }); if (!privateKey.isPrivate) throw new Error('NotPrivateKeyForECCKeyGenNode'); return [4 /*yield*/, privateKey.export('jwk')]; case 2: privateJwk = _a.sent(); return [2 /*return*/, { publicKey: publicJwk, privateKey: privateJwk }]; } }); }); }; 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} nodeCrypto - NodeCrypto object. * @return {Promise<Uint8Array>} - Output signature byte array in raw or der format. * @throws {Error} - Throws if NotPrivateKeyForECCSignNode. */ var sign = function (msg, privateJwk, hash, signatureFormat, nodeCrypto) { return __awaiter(void 0, void 0, void 0, function () { var privateKey, privatePem, sign, asn1sig; return __generator(this, function (_a) { switch (_a.label) { case 0: privateKey = new js_crypto_key_utils_1.Key('jwk', privateJwk); if (!privateKey.isPrivate) throw new Error('NotPrivateKeyForECCSignNode'); return [4 /*yield*/, privateKey.export('pem')]; case 1: privatePem = _a.sent(); sign = nodeCrypto.createSign(params_1.hashes[hash].nodeName); sign.update(msg); asn1sig = sign.sign(privatePem); return [2 /*return*/, (signatureFormat === 'raw') ? asn1enc.decodeAsn1Signature(asn1sig, privateJwk.crv) : asn1sig]; } }); }); }; 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} nodeCrypto - NodeCrypto object. * @return {Promise<boolean>} - The result of verification. * @throws {Error} - Throws if NotPublicKeyForEccVerifyNode. */ var verify = function (msg, signature, publicJwk, hash, signatureFormat, nodeCrypto) { return __awaiter(void 0, void 0, void 0, function () { var publicKey, publicPem, verify, asn1sig; return __generator(this, function (_a) { switch (_a.label) { case 0: publicKey = new js_crypto_key_utils_1.Key('jwk', publicJwk); if (!publicKey.isPrivate) throw new Error('NotPrivateKeyForECCVerifyNode'); return [4 /*yield*/, publicKey.export('pem', { outputPublic: true, compact: false })]; case 1: publicPem = _a.sent(); verify = nodeCrypto.createVerify(params_1.hashes[hash].nodeName); verify.update(msg); asn1sig = (signatureFormat === 'raw') ? asn1enc.encodeAsn1Signature(signature, publicJwk.crv) : signature; return [2 /*return*/, verify.verify(publicPem, asn1sig)]; } }); }); }; 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} nodeCrypto - NodeCrypto object. * @return {Uint8Array} - The derived master secret via ECDH. */ var deriveSecret = function (publicJwk, privateJwk, nodeCrypto) { var curve = params_1.namedCurves[privateJwk.crv].nodeName; var payloadSize = params_1.namedCurves[privateJwk.crv].payloadSize; var ecdh = nodeCrypto.createECDH(curve); var privKeyBuf = js_encoding_utils_1.default.encoder.decodeBase64Url(privateJwk.d); var pubKeyBuf = new Uint8Array(payloadSize * 2 + 1); pubKeyBuf[0] = 0xFF & 0x04; pubKeyBuf.set(js_encoding_utils_1.default.encoder.decodeBase64Url(publicJwk.x), 1); pubKeyBuf.set(js_encoding_utils_1.default.encoder.decodeBase64Url(publicJwk.y), payloadSize + 1); ecdh.setPrivateKey(privKeyBuf); return new Uint8Array(ecdh.computeSecret(pubKeyBuf)); }; exports.deriveSecret = deriveSecret; //# sourceMappingURL=nodeapi.js.map