UNPKG

@hpke/common

Version:

A Hybrid Public Key Encryption (HPKE) internal-use common module for @hpke family modules.

227 lines (226 loc) 8.03 kB
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; }; (function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "../../_dnt.shims.js", "../identifiers.js"], factory); } })(function (require, exports) { "use strict"; var __syncRequire = typeof module === "object" && typeof module.exports === "object"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCryptoKeyPair = exports.isDenoV1 = void 0; exports.isDeno = isDeno; exports.i2Osp = i2Osp; exports.concat = concat; exports.base64UrlToBytes = base64UrlToBytes; exports.bytesToBase64Url = bytesToBase64Url; exports.hexToBytes = hexToBytes; exports.bytesToHex = bytesToHex; exports.kemToKeyGenAlgorithm = kemToKeyGenAlgorithm; exports.loadSubtleCrypto = loadSubtleCrypto; exports.loadCrypto = loadCrypto; exports.xor = xor; const dntShim = __importStar(require("../../_dnt.shims.js")); const identifiers_js_1 = require("../identifiers.js"); const isDenoV1 = () => // deno-lint-ignore no-explicit-any dntShim.dntGlobalThis.process === undefined; exports.isDenoV1 = isDenoV1; /** * Checks whether the runtime is Deno or not (Node.js). * @returns boolean - true if the runtime is Deno, false Node.js. */ function isDeno() { // deno-lint-ignore no-explicit-any if (dntShim.dntGlobalThis.process === undefined) { return true; } // deno-lint-ignore no-explicit-any return dntShim.dntGlobalThis.process?.versions?.deno !== undefined; } /** * Checks whetehr the type of input is CryptoKeyPair or not. */ const isCryptoKeyPair = (x) => typeof x === "object" && x !== null && typeof x.privateKey === "object" && typeof x.publicKey === "object"; exports.isCryptoKeyPair = isCryptoKeyPair; /** * Converts integer to octet string. I2OSP implementation. */ function i2Osp(n, w) { if (w <= 0) { throw new Error("i2Osp: too small size"); } if (n >= 256 ** w) { throw new Error("i2Osp: too large integer"); } const ret = new Uint8Array(w); for (let i = 0; i < w && n; i++) { ret[w - (i + 1)] = n % 256; n = n >> 8; } return ret; } /** * Concatenates two Uint8Arrays. * @param a Uint8Array * @param b Uint8Array * @returns Concatenated Uint8Array */ function concat(a, b) { const ret = new Uint8Array(a.length + b.length); ret.set(a, 0); ret.set(b, a.length); return ret; } /** * Decodes Base64Url-encoded data. * @param v Base64Url-encoded string * @returns Uint8Array */ function base64UrlToBytes(v) { const base64 = v.replace(/-/g, "+").replace(/_/g, "/"); const byteString = atob(base64); const ret = new Uint8Array(byteString.length); for (let i = 0; i < byteString.length; i++) { ret[i] = byteString.charCodeAt(i); } return ret; } /** * Encodes Uint8Array to Base64Url. * @param v Uint8Array * @returns Base64Url-encoded string */ function bytesToBase64Url(v) { return btoa(String.fromCharCode(...v)) .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=*$/g, ""); } /** * Decodes hex string to Uint8Array. * @param v Hex string * @returns Uint8Array * @throws Error if the input is not a hex string. */ function hexToBytes(v) { if (v.length === 0) { return new Uint8Array([]); } const res = v.match(/[\da-f]{2}/gi); if (res == null) { throw new Error("Not hex string."); } return new Uint8Array(res.map(function (h) { return parseInt(h, 16); })); } /** * Encodes Uint8Array to hex string. * @param v Uint8Array * @returns Hex string */ function bytesToHex(v) { return [...v].map((x) => x.toString(16).padStart(2, "0")).join(""); } /** * Converts KemId to KeyAlgorithm. * @param kem KemId * @returns KeyAlgorithm */ function kemToKeyGenAlgorithm(kem) { switch (kem) { case identifiers_js_1.KemId.DhkemP256HkdfSha256: return { name: "ECDH", namedCurve: "P-256", }; case identifiers_js_1.KemId.DhkemP384HkdfSha384: return { name: "ECDH", namedCurve: "P-384", }; case identifiers_js_1.KemId.DhkemP521HkdfSha512: return { name: "ECDH", namedCurve: "P-521", }; default: // case KemId.DhkemX25519HkdfSha256 return { name: "X25519", }; } } async function loadSubtleCrypto() { if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) { // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc. return globalThis.crypto.subtle; } // Node.js <= v18 try { // @ts-ignore: to ignore "crypto" const { webcrypto } = await (__syncRequire ? Promise.resolve().then(() => __importStar(require("crypto"))) : new Promise((resolve_1, reject_1) => { require(["crypto"], resolve_1, reject_1); }).then(__importStar)); // node:crypto return webcrypto.subtle; } catch (_e) { throw new Error("Failed to load SubtleCrypto"); } } async function loadCrypto() { if (dntShim.dntGlobalThis !== undefined && globalThis.crypto !== undefined) { // Browsers, Node.js >= v19, Cloudflare Workers, Bun, etc. return globalThis.crypto; } // Node.js <= v18 try { // @ts-ignore: to ignore "crypto" const { webcrypto } = await (__syncRequire ? Promise.resolve().then(() => __importStar(require("crypto"))) : new Promise((resolve_2, reject_2) => { require(["crypto"], resolve_2, reject_2); }).then(__importStar)); // node:crypto return webcrypto; } catch (_e) { throw new Error("Web Cryptograph API not supported"); } } /** * XOR for Uint8Array. */ function xor(a, b) { if (a.byteLength !== b.byteLength) { throw new Error("xor: different length inputs"); } const buf = new Uint8Array(a.byteLength); for (let i = 0; i < a.byteLength; i++) { buf[i] = a[i] ^ b[i]; } return buf; } });