commit 3c38e096408e850731b1647597cd422031ee8bcb parent 53a156e40cdee00e5a8c808cce636aa1af6a3460 Author: Dana Keeler <dkeeler@mozilla.com> Date: Thu, 18 Dec 2025 18:56:00 +0000 Bug 1995819 - vendor PKIjs v3.3.3 r=jschanck Differential Revision: https://phabricator.services.mozilla.com/D276954 Diffstat:
38 files changed, 24149 insertions(+), 26440 deletions(-)
diff --git a/third_party/js/PKI.js/eslint.config.mjs b/third_party/js/PKI.js/eslint.config.mjs @@ -0,0 +1,89 @@ +import js from "@eslint/js"; +import tseslint from "@typescript-eslint/eslint-plugin"; +import tsparser from "@typescript-eslint/parser"; +import globals from "globals"; + +export default [ + { + ignores: ["website/**/*", "**/*.js", "build/**/*.ts"] + }, + { + plugins: { + "@typescript-eslint": tseslint + } + }, + js.configs.recommended, + { + files: ["**/*.ts"], + languageOptions: { + parser: tsparser, + parserOptions: { + ecmaVersion: 2020, + sourceType: "module", + project: "./tsconfig.json" + }, + globals: { + ...globals.browser, + ...globals.node + } + }, + rules: { + ...tseslint.configs.recommended.rules, + "@typescript-eslint/ban-ts-ignore": "off", + "@typescript-eslint/camelcase": "off", + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/interface-name-prefix": "off", + "@typescript-eslint/no-explicit-any": "off", + "no-duplicate-imports": "warn", + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/triple-slash-reference": "off", + "no-trailing-spaces": "warn", + "no-redeclare": "off", + "no-dupe-class-members": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + caughtErrorsIgnorePattern: "^_", + }, + ], + }, + ignores: [ + "build/**/*.ts", + "**/*.js", + "website" + ] + }, + { + files: ["test/**/*.ts"], + languageOptions: { + parser: tsparser, + parserOptions: { + ecmaVersion: 2020, + sourceType: "module", + project: "./tsconfig.json" + }, + globals: { + ...globals.browser, + ...globals.node, + ...globals.mocha + } + }, + rules: { + ...tseslint.configs.recommended.rules, + "@typescript-eslint/ban-ts-ignore": "off", + "@typescript-eslint/camelcase": "off", + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/interface-name-prefix": "off", + "@typescript-eslint/no-explicit-any": "off", + "no-duplicate-imports": "warn", + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/triple-slash-reference": "off", + "no-trailing-spaces": "warn", + "no-redeclare": "off", + "no-dupe-class-members": "off", + "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_", "caughtErrorsIgnorePattern": "^_" }] + } + } +]; +\ No newline at end of file diff --git a/third_party/js/PKI.js/moz.yaml b/third_party/js/PKI.js/moz.yaml @@ -20,11 +20,11 @@ origin: # Human-readable identifier for this version/release # Generally "version NNN", "tag SSS", "bookmark SSS" - release: 72d175c9edbc8e00c550dee610a8dac6204f4383 (2023-01-15T09:12:35Z). + release: c9fd2bc8f028bc4fa8528dc6cbf48eddbf382d6e (2025-11-03T08:43:07Z). # Revision to pull in # Must be a long or short commit SHA (long preferred) - revision: 72d175c9edbc8e00c550dee610a8dac6204f4383 + revision: c9fd2bc8f028bc4fa8528dc6cbf48eddbf382d6e # The package's license, where possible using the mnemonic from # https://spdx.org/licenses/ diff --git a/third_party/js/PKI.js/package.json b/third_party/js/PKI.js/package.json @@ -15,42 +15,37 @@ "url": "git://github.com/PeculiarVentures/PKI.js.git" }, "devDependencies": { - "@peculiar/webcrypto": "^1.4.0", - "@rollup/plugin-alias": "^3.1.9", - "@rollup/plugin-commonjs": "^22.0.1", - "@rollup/plugin-node-resolve": "^13.3.0", - "@types/mocha": "^9.1.1", - "@types/node": "^18.6.3", - "@typescript-eslint/eslint-plugin": "^5.32.0", - "@typescript-eslint/parser": "^5.32.0", - "assert": "^2.0.0", + "@peculiar/webcrypto": "^1.5.0", + "@rollup/plugin-alias": "^5.1.1", + "@rollup/plugin-commonjs": "^28.0.7", + "@rollup/plugin-node-resolve": "^16.0.3", + "@types/mocha": "^10.0.10", + "@types/node": "^20.19.21", + "@typescript-eslint/eslint-plugin": "^8.46.1", + "@typescript-eslint/parser": "^8.46.1", + "assert": "^2.1.0", "emailjs-mime-builder": "^2.0.5", "emailjs-mime-parser": "^2.0.7", - "eslint": "^8.21.0", - "eslint-plugin-deprecation": "^1.3.2", - "mocha": "^10.0.0", - "nyc": "^15.1.0", - "rollup": "^2.77.2", - "rollup-plugin-dts": "^4.2.2", - "rollup-plugin-typescript2": "^0.32.1", - "ts-node": "^10.9.1", - "typedoc": "^0.23.10", - "typescript": "^4.7.4" + "eslint": "^9.37.0", + "mocha": "^11.7.4", + "nyc": "^17.1.0", + "rollup": "^4.52.4", + "rollup-plugin-dts": "^6.2.3", + "rollup-plugin-typescript2": "^0.36.0", + "ts-node": "^10.9.2", + "typescript": "^5.9.3" }, "dependencies": { - "asn1js": "^3.0.5", - "bytestreamjs": "^2.0.0", - "pvtsutils": "^1.3.2", + "@noble/hashes": "1.4.0", + "asn1js": "^3.0.6", + "bytestreamjs": "^2.0.1", + "pvtsutils": "^1.3.6", "pvutils": "^1.1.3", - "tslib": "^2.4.0" - }, - "engines": { - "node": ">=12.0.0" + "tslib": "^2.8.1" }, "scripts": { "build": "rollup -c", "build:examples": "rollup -c examples/rollup.config.js", - "build:docs": "typedoc", "lint": "eslint . --ext .ts", "lint:fix": "eslint --fix . --ext .ts", "coverage": "nyc npm test", @@ -81,6 +76,16 @@ "main": "./build/index.js", "types": "./build/index.d.ts", "name": "pkijs", - "version": "3.0.11", - "license": "BSD-3-Clause" + "version": "3.3.3", + "license": "BSD-3-Clause", + "engines": { + "node": ">=16.0.0" + }, + "devEngines": { + "packageManager": { + "name": "npm", + "version": ">=10", + "onFail": "error" + } + } } diff --git a/third_party/js/PKI.js/rollup.config.js b/third_party/js/PKI.js/rollup.config.js @@ -1,60 +0,0 @@ -import path from "path"; -import fs from "fs"; -import typescript from "rollup-plugin-typescript2"; -import dts from "rollup-plugin-dts"; -import pkg from "./package.json"; -import { nodeResolve } from '@rollup/plugin-node-resolve'; - -const LICENSE = fs.readFileSync("LICENSE", { encoding: "utf-8" }); -const banner = [ - "/*!", - ...LICENSE.split("\n").map(o => ` * ${o}`), - " */", - "", -].join("\n"); -const input = "src/index.ts"; - -export default [ - { - input, - plugins: [ - typescript({ - check: true, - clean: true, - tsconfigOverride: { - compilerOptions: { - module: "ES2015", - removeComments: true, - } - }, - }), - nodeResolve(), - ], - output: [ - { - banner, - file: pkg.main, - format: "cjs", - }, - { - banner, - file: pkg.module, - format: "es", - }, - ], - }, - { - input, - plugins: [ - dts({ - tsconfig: path.resolve(__dirname, "./tsconfig.json") - }) - ], - output: [ - { - banner, - file: pkg.types, - } - ] - }, -]; diff --git a/third_party/js/PKI.js/rollup.config.mjs b/third_party/js/PKI.js/rollup.config.mjs @@ -0,0 +1,65 @@ +import path from "path"; +import fs from "fs"; +import { fileURLToPath } from "url"; +import typescript from "rollup-plugin-typescript2"; +import dts from "rollup-plugin-dts"; +import { nodeResolve } from "@rollup/plugin-node-resolve"; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const pkg = JSON.parse(fs.readFileSync("./package.json", "utf8")); + +const LICENSE = fs.readFileSync("LICENSE", { encoding: "utf-8" }); +const banner = [ + "/*!", + ...LICENSE.split("\n").map(o => ` * ${o}`), + " */", + "", +].join("\n"); +const input = "src/index.ts"; +const external = Object.keys(pkg.dependencies || {}); +external.push('@noble/hashes/sha1'); +external.push('@noble/hashes/sha2'); + +export default [ + { + input, + plugins: [ + typescript({ + check: false, + clean: true, + tsconfigOverride: { + compilerOptions: { + module: "ES2020", + removeComments: true, + } + } + }), + nodeResolve(), + ], + output: [ + { + banner, + file: pkg.main, + format: "cjs", + }, + { + banner, + file: pkg.module, + format: "es", + }, + ], + }, + { + input, + plugins: [ + dts({ + tsconfig: path.resolve(__dirname, "./tsconfig.json") + }) + ], + output: [ + { + banner, + file: pkg.types, + } + ] + }, +]; diff --git a/third_party/js/PKI.js/src/AuthenticatedSafe.ts b/third_party/js/PKI.js/src/AuthenticatedSafe.ts @@ -301,7 +301,7 @@ export class AuthenticatedSafe extends PkiObject implements IAuthenticatedSafe { //#endregion //#region Encrypt CMS EncryptedData using password - await cmsEncrypted.encrypt(currentParameters); + await cmsEncrypted.encrypt(currentParameters, crypto); //#endregion //#region Store result content in CMS_CONTENT_INFO type diff --git a/third_party/js/PKI.js/src/BasicOCSPResponse.ts b/third_party/js/PKI.js/src/BasicOCSPResponse.ts @@ -326,7 +326,7 @@ export class BasicOCSPResponse extends PkiObject implements IBasicOCSPResponse { default: } } - catch (ex) { + catch { // nothing } @@ -366,7 +366,7 @@ export class BasicOCSPResponse extends PkiObject implements IBasicOCSPResponse { //#endregion //#region Signing TBS data on provided private key - const signature = await crypto.signWithPrivateKey(this.tbsResponseData.tbsView, privateKey, { algorithm }); + const signature = await crypto.signWithPrivateKey(this.tbsResponseData.tbsView as BufferSource, privateKey, { algorithm }); this.signature = new asn1js.BitString({ valueHex: signature }); //#endregion } @@ -401,7 +401,7 @@ export class BasicOCSPResponse extends PkiObject implements IBasicOCSPResponse { break; case (this.tbsResponseData.responderID instanceof asn1js.OctetString): // [2] KeyHash for (const [index, cert] of this.certs.entries()) { - const hash = await crypto.digest({ name: "sha-1" }, cert.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); + const hash = await crypto.digest({ name: "sha-1" }, cert.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView as BufferSource); if (pvutils.isEqualBuffer(hash, this.tbsResponseData.responderID.valueBlock.valueHex)) { certIndex = index; break; @@ -436,7 +436,7 @@ export class BasicOCSPResponse extends PkiObject implements IBasicOCSPResponse { throw new Error("Validation of signer's certificate failed"); } - return crypto.verifyWithPublicKey(this.tbsResponseData.tbsView, this.signature, this.certs[certIndex].subjectPublicKeyInfo, this.signatureAlgorithm); + return crypto.verifyWithPublicKey(this.tbsResponseData.tbsView as BufferSource, this.signature, this.certs[certIndex].subjectPublicKeyInfo, this.signatureAlgorithm); } } diff --git a/third_party/js/PKI.js/src/CertBag.ts b/third_party/js/PKI.js/src/CertBag.ts @@ -153,17 +153,17 @@ export class CertBag extends PkiObject implements ICertBag { case id_CertBag_X509Certificate: // x509Certificate { try { - this.parsedValue = Certificate.fromBER(certValueHex); + this.parsedValue = Certificate.fromBER(certValueHex as BufferSource); } - catch (ex) // In some realizations the same OID used for attribute certificates + catch // In some realizations the same OID used for attribute certificates { - AttributeCertificateV2.fromBER(certValueHex); + AttributeCertificateV2.fromBER(certValueHex as BufferSource); } } break; case id_CertBag_AttributeCertificate: // attributeCertificate - (!!!) THIS OID IS SUBJECT FOR CHANGE IN FUTURE (!!!) { - this.parsedValue = AttributeCertificateV2.fromBER(certValueHex); + this.parsedValue = AttributeCertificateV2.fromBER(certValueHex as BufferSource); } break; case id_CertBag_SDSICertificate: // sdsiCertificate diff --git a/third_party/js/PKI.js/src/CertID.ts b/third_party/js/PKI.js/src/CertID.ts @@ -277,7 +277,7 @@ export class CertID extends PkiObject implements ICertID { // Create ISSUER_KEY_HASH const issuerKeyBuffer = issuerCertificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView; - const hashIssuerKey = await crypto.digest({ name: parameters.hashAlgorithm }, issuerKeyBuffer); + const hashIssuerKey = await crypto.digest({ name: parameters.hashAlgorithm }, issuerKeyBuffer as BufferSource); this.issuerKeyHash = new asn1js.OctetString({ valueHex: hashIssuerKey }); } diff --git a/third_party/js/PKI.js/src/Certificate.ts b/third_party/js/PKI.js/src/Certificate.ts @@ -740,7 +740,7 @@ export class Certificate extends PkiObject implements ICertificate { * @returns Computed hash value from `Certificate.tbsCertificate.subjectPublicKeyInfo.subjectPublicKey` */ public async getKeyHash(hashAlgorithm = "SHA-1", crypto = common.getCrypto(true)): Promise<ArrayBuffer> { - return crypto.digest({ name: hashAlgorithm }, this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); + return crypto.digest({ name: hashAlgorithm }, this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView as BufferSource); } /** @@ -766,7 +766,7 @@ export class Certificate extends PkiObject implements ICertificate { // Signing TBS data on provided private key // TODO remove any - const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters as any); + const signature = await crypto.signWithPrivateKey(this.tbsView as BufferSource, privateKey, parameters as any); this.signatureValue = new asn1js.BitString({ valueHex: signature }); } @@ -790,7 +790,7 @@ export class Certificate extends PkiObject implements ICertificate { throw new Error("Please provide issuer certificate as a parameter"); } - return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); + return crypto.verifyWithPublicKey(this.tbsView as BufferSource, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); } } diff --git a/third_party/js/PKI.js/src/CertificateChainValidationEngine.ts b/third_party/js/PKI.js/src/CertificateChainValidationEngine.ts @@ -229,7 +229,7 @@ export class CertificateChainValidationEngine { return [certificate]; } } - catch (ex) { + catch { // nothing } } @@ -314,13 +314,13 @@ export class CertificateChainValidationEngine { } // Now perform certificate verification checking - for (let i = 0; i < result.length; i++) { + for (let i = result.length - 1; i >= 0; i--) { try { const verificationResult = await certificate.verify(result[i], crypto); if (verificationResult === false) result.splice(i, 1); } - catch (ex) { + catch { result.splice(i, 1); // Something wrong, remove the certificate } } @@ -475,7 +475,7 @@ export class CertificateChainValidationEngine { break; } } - catch (ex) { + catch { // nothing } } @@ -813,7 +813,7 @@ export class CertificateChainValidationEngine { //#endregion //#region Exclude certificate paths not ended with "trusted roots" - for (let i = 0; i < result.length; i++) { + for (let i = result.length - 1; i >= 0; i--) { let found = false; for (let j = 0; j < (result[i]).length; j++) { @@ -832,7 +832,6 @@ export class CertificateChainValidationEngine { if (!found) { result.splice(i, 1); - i = 0; } } diff --git a/third_party/js/PKI.js/src/CertificateRevocationList.ts b/third_party/js/PKI.js/src/CertificateRevocationList.ts @@ -509,7 +509,7 @@ export class CertificateRevocationList extends PkiObject implements ICertificate //#endregion //#region Signing TBS data on provided private key - const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters as any); + const signature = await crypto.signWithPrivateKey(this.tbsView as BufferSource, privateKey, parameters as any); this.signatureValue = new asn1js.BitString({ valueHex: signature }); //#endregion } @@ -555,7 +555,7 @@ export class CertificateRevocationList extends PkiObject implements ICertificate } //#endregion - return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); + return crypto.verifyWithPublicKey(this.tbsView as BufferSource, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); } } diff --git a/third_party/js/PKI.js/src/CertificateSet.ts b/third_party/js/PKI.js/src/CertificateSet.ts @@ -214,7 +214,7 @@ export class CertificateSet extends PkiObject implements ICertificateSet { default: } - return element.toSchema(); + return (element as any).toSchema(); }) })); } diff --git a/third_party/js/PKI.js/src/CertificationRequest.ts b/third_party/js/PKI.js/src/CertificationRequest.ts @@ -459,7 +459,7 @@ export class CertificationRequest extends PkiObject implements ICertificationReq //#endregion //#region Signing TBS data on provided private key - const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters as any); + const signature = await crypto.signWithPrivateKey(this.tbsView as BufferSource, privateKey, parameters as any); this.signatureValue = new asn1js.BitString({ valueHex: signature }); //#endregion } @@ -470,7 +470,7 @@ export class CertificationRequest extends PkiObject implements ICertificationReq * @returns Returns `true` if signature value is valid, otherwise `false` */ public async verify(crypto = common.getCrypto(true)): Promise<boolean> { - return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, this.subjectPublicKeyInfo, this.signatureAlgorithm); + return crypto.verifyWithPublicKey(this.tbsView as BufferSource, this.signatureValue, this.subjectPublicKeyInfo, this.signatureAlgorithm); } /** diff --git a/third_party/js/PKI.js/src/CryptoEngine/AbstractCryptoEngine.ts b/third_party/js/PKI.js/src/CryptoEngine/AbstractCryptoEngine.ts @@ -62,6 +62,7 @@ export abstract class AbstractCryptoEngine implements type.ICryptoEngine { return (this.subtle.digest as any)(...args); } + public generateKey(algorithm: "Ed25519", extractable: boolean, keyUsages: ReadonlyArray<"sign" | "verify">): Promise<CryptoKeyPair>; public generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair>; public generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>; public generateKey(algorithm: globalThis.AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair | CryptoKey>; @@ -105,7 +106,11 @@ export abstract class AbstractCryptoEngine implements type.ICryptoEngine { } public getRandomValues<T extends ArrayBufferView | null>(array: T): T { - return this.crypto.getRandomValues(array); + if (array === null) { + throw new Error("Argument \"array\" must not be null"); + } + + return this.crypto.getRandomValues(array) as T; } } diff --git a/third_party/js/PKI.js/src/CryptoEngine/CryptoEngine.ts b/third_party/js/PKI.js/src/CryptoEngine/CryptoEngine.ts @@ -1,3 +1,5 @@ +import { sha1 } from "@noble/hashes/sha1"; +import { sha256, sha384, sha512 } from "@noble/hashes/sha2"; import * as asn1js from "asn1js"; import * as pvutils from "pvutils"; import * as pvtsutils from "pvtsutils"; @@ -18,185 +20,113 @@ import { ECNamedCurves } from "../ECNamedCurves"; /** * Making MAC key using algorithm described in B.2 of PKCS#12 standard. */ -async function makePKCS12B2Key(cryptoEngine: CryptoEngine, hashAlgorithm: string, keyLength: number, password: ArrayBuffer, salt: ArrayBuffer, iterationCount: number) { - //#region Initial variables - let u: number; - let v: number; +async function makePKCS12B2Key(hashAlgorithm: string, keyLength: number, password: ArrayBuffer, salt: ArrayBuffer, iterationCount: number) { + let u: number; // Output length of the hash function + let v: number; // Block size of the hash function + let md: (input: Uint8Array) => Uint8Array; // Hash function - const result: number[] = []; - //#endregion - - //#region Get "u" and "v" values + // Determine the hash algorithm parameters switch (hashAlgorithm.toUpperCase()) { case "SHA-1": - u = 20; // 160 - v = 64; // 512 + u = 20; // 160 bits + v = 64; // 512 bits + md = sha1; break; case "SHA-256": - u = 32; // 256 - v = 64; // 512 + u = 32; // 256 bits + v = 64; // 512 bits + md = sha256; break; case "SHA-384": - u = 48; // 384 - v = 128; // 1024 + u = 48; // 384 bits + v = 128; // 1024 bits + md = sha384; break; case "SHA-512": - u = 64; // 512 - v = 128; // 1024 + u = 64; // 512 bits + v = 128; // 1024 bits + md = sha512; break; default: throw new Error("Unsupported hashing algorithm"); } - //#endregion - - //#region Main algorithm making key - //#region Transform password to UTF-8 like string - const passwordViewInitial = new Uint8Array(password); - const passwordTransformed = new ArrayBuffer((password.byteLength * 2) + 2); - const passwordTransformedView = new Uint8Array(passwordTransformed); - - for (let i = 0; i < passwordViewInitial.length; i++) { - passwordTransformedView[i * 2] = 0x00; - passwordTransformedView[i * 2 + 1] = passwordViewInitial[i]; + const originalPassword = new Uint8Array(password); + let decodedPassword = new TextDecoder().decode(password); + const encodedPassword = new TextEncoder().encode(decodedPassword); + if (encodedPassword.some((byte, i) => byte !== originalPassword[i])) { + decodedPassword = String.fromCharCode(...originalPassword); } - passwordTransformedView[passwordTransformedView.length - 2] = 0x00; - passwordTransformedView[passwordTransformedView.length - 1] = 0x00; - - password = passwordTransformed.slice(0); - //#endregion - - //#region Construct a string D (the "diversifier") by concatenating v/8 copies of ID - const D = new ArrayBuffer(v); - const dView = new Uint8Array(D); - - for (let i = 0; i < D.byteLength; i++) - dView[i] = 3; // The ID value equal to "3" for MACing (see B.3 of standard) - //#endregion - - //#region Concatenate copies of the salt together to create a string S of length v * ceil(s / v) bytes (the final copy of the salt may be trunacted to create S) - const saltLength = salt.byteLength; + // Transform the password into a byte array + const passwordTransformed = new Uint8Array(decodedPassword.length * 2 + 2); + const passwordView = new DataView(passwordTransformed.buffer); + for (let i = 0; i < decodedPassword.length; i++) { + passwordView.setUint16(i * 2, decodedPassword.charCodeAt(i), false); + } + // Add null-terminator + passwordView.setUint16(decodedPassword.length * 2, 0, false); - const sLen = v * Math.ceil(saltLength / v); - const S = new ArrayBuffer(sLen); - const sView = new Uint8Array(S); + // Create a filled array D with the value 3 (ID for MACing) + const D = new Uint8Array(v).fill(3); + // Repeat the salt to fill the block size const saltView = new Uint8Array(salt); + const S = new Uint8Array(v * Math.ceil(saltView.length / v)).map((_, i) => saltView[i % saltView.length]); - for (let i = 0; i < sLen; i++) - sView[i] = saltView[i % saltLength]; - //#endregion - - //#region Concatenate copies of the password together to create a string P of length v * ceil(p / v) bytes (the final copy of the password may be truncated to create P) - const passwordLength = password.byteLength; + // Repeat the password to fill the block size + const P = new Uint8Array(v * Math.ceil(passwordTransformed.length / v)).map((_, i) => passwordTransformed[i % passwordTransformed.length]); - const pLen = v * Math.ceil(passwordLength / v); - const P = new ArrayBuffer(pLen); - const pView = new Uint8Array(P); + // Concatenate S and P to form I + let I = new Uint8Array(S.length + P.length); + I.set(S); + I.set(P, S.length); - const passwordView = new Uint8Array(password); - - for (let i = 0; i < pLen; i++) - pView[i] = passwordView[i % passwordLength]; - //#endregion - - //#region Set I=S||P to be the concatenation of S and P - const sPlusPLength = S.byteLength + P.byteLength; - - let I = new ArrayBuffer(sPlusPLength); - let iView = new Uint8Array(I); - - iView.set(sView); - iView.set(pView, sView.length); - //#endregion - - //#region Set c=ceil(n / u) + // Calculate the number of hash iterations needed const c = Math.ceil((keyLength >> 3) / u); - //#endregion - - //#region Initial variables - let internalSequence = Promise.resolve(I); - //#endregion - - //#region For i=1, 2, ..., c, do the following: - for (let i = 0; i <= c; i++) { - internalSequence = internalSequence.then(_I => { - //#region Create contecanetion of D and I - const dAndI = new ArrayBuffer(D.byteLength + _I.byteLength); - const dAndIView = new Uint8Array(dAndI); - - dAndIView.set(dView); - dAndIView.set(iView, dView.length); - //#endregion - - return dAndI; - }); - - //#region Make "iterationCount" rounds of hashing - for (let j = 0; j < iterationCount; j++) - internalSequence = internalSequence.then(roundBuffer => cryptoEngine.digest({ name: hashAlgorithm }, new Uint8Array(roundBuffer))); - //#endregion - - internalSequence = internalSequence.then(roundBuffer => { - //#region Concatenate copies of Ai to create a string B of length v bits (the final copy of Ai may be truncated to create B) - const B = new ArrayBuffer(v); - const bView = new Uint8Array(B); - - for (let j = 0; j < B.byteLength; j++) - bView[j] = (roundBuffer as any)[j % roundBuffer.byteLength]; // TODO roundBuffer is ArrayBuffer. It doesn't have indexed values - //#endregion + const result: number[] = []; - //#region Make new I value - const k = Math.ceil(saltLength / v) + Math.ceil(passwordLength / v); - const iRound = []; + // Main loop to generate the key material + for (let i = 0; i < c; i++) { + // Concatenate D and I + let A: Uint8Array = new Uint8Array(D.length + I.length); + A.set(D); + A.set(I, D.length); - let sliceStart = 0; - let sliceLength = v; + // Perform hash iterations + for (let j = 0; j < iterationCount; j++) { + A = md(A); + } - for (let j = 0; j < k; j++) { - const chunk = Array.from(new Uint8Array(I.slice(sliceStart, sliceStart + sliceLength))); - sliceStart += v; - if ((sliceStart + v) > I.byteLength) - sliceLength = I.byteLength - sliceStart; + // Create a repeated block B from the hash output A + const B = new Uint8Array(v).map((_, i) => A[i % A.length]); - let x = 0x1ff; + // Determine the number of blocks + const k = Math.ceil(saltView.length / v) + Math.ceil(passwordTransformed.length / v); + const iRound: number[] = []; - for (let l = (B.byteLength - 1); l >= 0; l--) { - x >>= 8; - x += bView[l] + chunk[l]; - chunk[l] = (x & 0xff); - } + // Adjust I based on B + for (let j = 0; j < k; j++) { + const chunk = Array.from(I.slice(j * v, (j + 1) * v)); + let x = 0x1ff; - iRound.push(...chunk); + for (let l = B.length - 1; l >= 0; l--) { + x >>= 8; + x += B[l] + (chunk[l] || 0); + chunk[l] = x & 0xff; } - I = new ArrayBuffer(iRound.length); - iView = new Uint8Array(I); - - iView.set(iRound); - //#endregion + iRound.push(...chunk); + } - result.push(...(new Uint8Array(roundBuffer))); + // Update I for the next iteration + I = new Uint8Array(iRound); - return I; - }); + // Collect the result + result.push(...A); } - //#endregion - - //#region Initialize final key - internalSequence = internalSequence.then(() => { - const resultBuffer = new ArrayBuffer(keyLength >> 3); - const resultView = new Uint8Array(resultBuffer); - - resultView.set((new Uint8Array(result)).slice(0, keyLength >> 3)); - return resultBuffer; - }); - //#endregion - //#endregion - - return internalSequence; + return new Uint8Array(result.slice(0, keyLength >> 3)).buffer; } function prepareAlgorithm(data: globalThis.AlgorithmIdentifier | EcdsaParams): Algorithm & { hash?: Algorithm; } { @@ -399,7 +329,7 @@ export class CryptoEngine extends AbstractCryptoEngine { try { privateKeyInfo.fromSchema(asn1.result); } - catch (ex) { + catch { throw new Error("Incorrect keyData"); } @@ -601,7 +531,7 @@ export class CryptoEngine extends AbstractCryptoEngine { try { publicKeyInfo.fromJSON(jwk); } - catch (ex) { + catch { throw new Error("Incorrect key data"); } @@ -613,7 +543,7 @@ export class CryptoEngine extends AbstractCryptoEngine { try { privateKeyInfo.fromJSON(jwk); } - catch (ex) { + catch { throw new Error("Incorrect key data"); } @@ -1664,7 +1594,7 @@ export class CryptoEngine extends AbstractCryptoEngine { try { pbes2Parameters = new PBES2Params({ schema: parameters.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams }); } - catch (ex) { + catch { throw new Error("Incorrectly encoded \"pbes2Parameters\""); } @@ -1673,7 +1603,7 @@ export class CryptoEngine extends AbstractCryptoEngine { try { pbkdf2Params = new PBKDF2Params({ schema: pbes2Parameters.keyDerivationFunc.algorithmParams }); } - catch (ex) { + catch { throw new Error("Incorrectly encoded \"pbkdf2Params\""); } @@ -1773,7 +1703,7 @@ export class CryptoEngine extends AbstractCryptoEngine { //#endregion //#region Create PKCS#12 key for integrity checking - const pkcsKey = await makePKCS12B2Key(this, parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); + const pkcsKey = await makePKCS12B2Key(parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); //#endregion //#region Import HMAC key @@ -1829,7 +1759,7 @@ export class CryptoEngine extends AbstractCryptoEngine { //#endregion //#region Create PKCS#12 key for integrity checking - const pkcsKey = await makePKCS12B2Key(this, parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); + const pkcsKey = await makePKCS12B2Key(parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); //#endregion //#region Import HMAC key @@ -1852,16 +1782,21 @@ export class CryptoEngine extends AbstractCryptoEngine { // Initial variables const signatureAlgorithm = new AlgorithmIdentifier(); - //#region Get a "default parameters" for current algorithm + //#region Get "default parameters" for the current algorithm const parameters = this.getAlgorithmParameters(privateKey.algorithm.name, "sign"); if (!Object.keys(parameters.algorithm).length) { throw new Error("Parameter 'algorithm' is empty"); } + // Use the hash from the privateKey.algorithm.hash.name for keys with hash algorithms (like RSA) const algorithm = parameters.algorithm as any; // TODO remove `as any` - algorithm.hash.name = hashAlgorithm; + if ("hash" in privateKey.algorithm && privateKey.algorithm.hash && (privateKey.algorithm.hash as Algorithm).name) { + algorithm.hash.name = (privateKey.algorithm.hash as Algorithm).name; + } else { + algorithm.hash.name = hashAlgorithm; + } //#endregion - //#region Fill internal structures base on "privateKey" and "hashAlgorithm" + //#region Fill internal structures based on "privateKey" and "hashAlgorithm" switch (privateKey.algorithm.name.toUpperCase()) { case "RSASSA-PKCS1-V1_5": case "ECDSA": @@ -1869,8 +1804,8 @@ export class CryptoEngine extends AbstractCryptoEngine { break; case "RSA-PSS": { - //#region Set "saltLength" as a length (in octets) of hash function result - switch (hashAlgorithm.toUpperCase()) { + //#region Set "saltLength" as the length (in octets) of the hash function result + switch (algorithm.hash.name.toUpperCase()) { case "SHA-256": algorithm.saltLength = 32; break; @@ -1887,8 +1822,8 @@ export class CryptoEngine extends AbstractCryptoEngine { //#region Fill "RSASSA_PSS_params" object const paramsObject: Partial<IRSASSAPSSParams> = {}; - if (hashAlgorithm.toUpperCase() !== "SHA-1") { - const hashAlgorithmOID = this.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); + if (algorithm.hash.name.toUpperCase() !== "SHA-1") { + const hashAlgorithmOID = this.getOIDByAlgorithm({ name: algorithm.hash.name }, true, "hashAlgorithm"); paramsObject.hashAlgorithm = new AlgorithmIdentifier({ algorithmId: hashAlgorithmOID, @@ -2066,7 +2001,7 @@ export class CryptoEngine extends AbstractCryptoEngine { //#endregion //#region Special case for ECDSA signatures - let signatureValue: BufferSource = signature.valueBlock.valueHexView; + let signatureValue: Uint8Array | ArrayBuffer = signature.valueBlock.valueHexView; if (publicKey.algorithm.name === "ECDSA") { const namedCurve = ECNamedCurves.find((publicKey.algorithm as EcKeyAlgorithm).namedCurve); @@ -2102,7 +2037,7 @@ export class CryptoEngine extends AbstractCryptoEngine { return this.verify((algorithm.algorithm as any), publicKey, - signatureValue, + signatureValue as BufferSource, data, ); //#endregion diff --git a/third_party/js/PKI.js/src/CryptoEngine/CryptoEngineInit.ts b/third_party/js/PKI.js/src/CryptoEngine/CryptoEngineInit.ts @@ -2,17 +2,15 @@ import * as common from "../common"; import { CryptoEngine } from "./CryptoEngine"; export function initCryptoEngine() { - if (typeof self !== "undefined") { - if ("crypto" in self) { - let engineName = "webcrypto"; + if (typeof globalThis !== "undefined" && "crypto" in globalThis) { + let engineName = "webcrypto"; - // Apple Safari support - if ("webkitSubtle" in self.crypto) { - engineName = "safari"; - } - - common.setEngine(engineName, new CryptoEngine({ name: engineName, crypto: crypto })); + // Apple Safari support + if ("webkitSubtle" in globalThis.crypto) { + engineName = "safari"; } + + common.setEngine(engineName, new CryptoEngine({ name: engineName, crypto: globalThis.crypto })); } else if (typeof crypto !== "undefined" && "webcrypto" in crypto) { // NodeJS ^15 const name = "NodeJS ^15"; diff --git a/third_party/js/PKI.js/src/EncryptedContentInfo.ts b/third_party/js/PKI.js/src/EncryptedContentInfo.ts @@ -27,7 +27,14 @@ export interface EncryptedContentInfoJson { encryptedContent?: asn1js.OctetStringJson; } -export type EncryptedContentParameters = PkiObjectParameters & Partial<IEncryptedContentInfo>; +export interface EncryptedContentInfoSplit { + /** + * Disables OctetString splitting for encryptedContent. + */ + disableSplit?: boolean; +} + +export type EncryptedContentParameters = PkiObjectParameters & Partial<IEncryptedContentInfo> & EncryptedContentInfoSplit; export type EncryptedContentInfoSchema = Schema.SchemaParameters<{ contentType?: string; @@ -35,6 +42,8 @@ export type EncryptedContentInfoSchema = Schema.SchemaParameters<{ encryptedContent?: string; }>; +const PIECE_SIZE = 1024; + /** * Represents the EncryptedContentInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652) */ @@ -47,7 +56,7 @@ export class EncryptedContentInfo extends PkiObject implements IEncryptedContent public encryptedContent?: asn1js.OctetString; /** - * Initializes a new instance of the {@link EncryptedContent} class + * Initializes a new instance of the {@link EncryptedContentInfo} class * @param parameters Initialization parameters */ constructor(parameters: EncryptedContentParameters = {}) { @@ -63,7 +72,8 @@ export class EncryptedContentInfo extends PkiObject implements IEncryptedContent if ((this.encryptedContent.idBlock.tagClass === 1) && (this.encryptedContent.idBlock.tagNumber === 4)) { //#region Divide OCTET STRING value down to small pieces - if (this.encryptedContent.idBlock.isConstructed === false) { + // NOTE: Acrobat cannot decrypt the content, if constructed OctetString is used + if (this.encryptedContent.idBlock.isConstructed === false && !parameters.disableSplit) { const constrString = new asn1js.OctetString({ idBlock: { isConstructed: true }, isConstructed: true @@ -73,9 +83,8 @@ export class EncryptedContentInfo extends PkiObject implements IEncryptedContent const valueHex = this.encryptedContent.valueBlock.valueHexView.slice().buffer; let length = valueHex.byteLength; - const pieceSize = 1024; while (length > 0) { - const pieceView = new Uint8Array(valueHex, offset, ((offset + pieceSize) > valueHex.byteLength) ? (valueHex.byteLength - offset) : pieceSize); + const pieceView = new Uint8Array(valueHex, offset, ((offset + PIECE_SIZE) > valueHex.byteLength) ? (valueHex.byteLength - offset) : PIECE_SIZE); const _array = new ArrayBuffer(pieceView.length); const _view = new Uint8Array(_array); diff --git a/third_party/js/PKI.js/src/EncryptedData.ts b/third_party/js/PKI.js/src/EncryptedData.ts @@ -264,7 +264,7 @@ export class EncryptedData extends PkiObject implements IEncryptedData { * Creates a new CMS Encrypted Data content * @param parameters Parameters necessary for encryption */ - public async encrypt(parameters: EncryptedDataEncryptParams): Promise<void> { + public async encrypt(parameters: EncryptedDataEncryptParams, crypto = common.getCrypto(true)): Promise<void> { //#region Check for input parameters ArgumentError.assert(parameters, "parameters", "object"); //#endregion @@ -276,7 +276,7 @@ export class EncryptedData extends PkiObject implements IEncryptedData { }; //#endregion - this.encryptedContentInfo = await common.getCrypto(true).encryptEncryptedContentInfo(encryptParams); + this.encryptedContentInfo = await crypto.encryptEncryptedContentInfo(encryptParams); } /** diff --git a/third_party/js/PKI.js/src/EnvelopedData.ts b/third_party/js/PKI.js/src/EnvelopedData.ts @@ -1,9 +1,10 @@ import * as asn1js from "asn1js"; import * as pvutils from "pvutils"; +import { BufferSourceConverter } from "pvtsutils"; import * as common from "./common"; import { OriginatorInfo, OriginatorInfoJson } from "./OriginatorInfo"; import { RecipientInfo, RecipientInfoJson } from "./RecipientInfo"; -import { EncryptedContentInfo, EncryptedContentInfoJson, EncryptedContentInfoSchema } from "./EncryptedContentInfo"; +import { EncryptedContentInfo, EncryptedContentInfoJson, EncryptedContentInfoSchema, EncryptedContentInfoSplit } from "./EncryptedContentInfo"; import { Attribute, AttributeJson } from "./Attribute"; import { AlgorithmIdentifier, AlgorithmIdentifierParameters } from "./AlgorithmIdentifier"; import { RSAESOAEPParams } from "./RSAESOAEPParams"; @@ -107,13 +108,32 @@ export interface EnvelopedDataJson { unprotectedAttrs?: AttributeJson[]; } -export type EnvelopedDataParameters = PkiObjectParameters & Partial<IEnvelopedData>; +export type EnvelopedDataParameters = PkiObjectParameters & Partial<IEnvelopedData> & EncryptedContentInfoSplit; export interface EnvelopedDataEncryptionParams { kekEncryptionLength: number; kdfAlgorithm: string; } +export interface EnvelopedDataDecryptBaseParams { + preDefinedData?: BufferSource; + recipientCertificate?: Certificate; +} + +export interface EnvelopedDataDecryptKeyParams extends EnvelopedDataDecryptBaseParams { + recipientPrivateKey: CryptoKey; + /** + * Crypto provider assigned to `recipientPrivateKey`. If the filed is empty uses default crypto provider. + */ + crypto?: Crypto; +} + +export interface EnvelopedDataDecryptBufferParams extends EnvelopedDataDecryptBaseParams { + recipientPrivateKey?: BufferSource; +} + +export type EnvelopedDataDecryptParams = EnvelopedDataDecryptBufferParams | EnvelopedDataDecryptKeyParams; + /** * Represents the EnvelopedData structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652) * @@ -172,6 +192,8 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { public encryptedContentInfo!: EncryptedContentInfo; public unprotectedAttrs?: Attribute[]; + public policy: Required<EncryptedContentInfoSplit>; + /** * Initializes a new instance of the {@link EnvelopedData} class * @param parameters Initialization parameters @@ -188,6 +210,9 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { if (UNPROTECTED_ATTRS in parameters) { this.unprotectedAttrs = pvutils.getParametersValue(parameters, UNPROTECTED_ATTRS, EnvelopedData.defaultValues(UNPROTECTED_ATTRS)); } + this.policy = { + disableSplit: !!parameters.disableSplit, + }; if (parameters.schema) { this.fromSchema(parameters.schema); @@ -413,9 +438,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { * @param variant Variant = 1 is for "key transport", variant = 2 is for "key agreement". In fact the "variant" is unnecessary now because Google has no DH algorithm implementation. Thus key encryption scheme would be choosen by certificate type only: "key transport" for RSA and "key agreement" for ECC certificates. * @param crypto Crypto engine */ - public addRecipientByCertificate(certificate: Certificate, parameters?: { - // empty - }, variant?: number, crypto = common.getCrypto(true)): boolean { + public addRecipientByCertificate(certificate: Certificate, parameters?: object, variant?: number, crypto = common.getCrypto(true)): boolean { //#region Initialize encryption parameters const encryptionParameters = Object.assign( { useOAEP: true, oaepHashAlgorithm: "SHA-512" }, @@ -803,6 +826,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { //#region Append common information to CMS_ENVELOPED_DATA this.version = 2; this.encryptedContentInfo = new EncryptedContentInfo({ + disableSplit: this.policy.disableSplit, contentType: "1.2.840.113549.1.7.1", // "data" contentEncryptionAlgorithm: new AlgorithmIdentifier({ algorithmId: contentEncryptionOID, @@ -1027,7 +1051,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { try { pbkdf2Params = new PBKDF2Params({ schema: recipientInfo.keyDerivationAlgorithm.algorithmParams }); } - catch (ex) { + catch { throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); } @@ -1120,11 +1144,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { * @param parameters Additional parameters * @param crypto Crypto engine */ - async decrypt(recipientIndex: number, parameters: { - recipientCertificate?: Certificate; - recipientPrivateKey?: BufferSource; - preDefinedData?: BufferSource; - }, crypto = common.getCrypto(true)) { + async decrypt(recipientIndex: number, parameters: EnvelopedDataDecryptParams, crypto = common.getCrypto(true)) { //#region Initial variables const decryptionParameters = parameters || {}; //#endregion @@ -1184,15 +1204,24 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { throw new Error(`Incorrect curve OID for index ${index}`); } - const ecdhPrivateKey = await crypto.importKey("pkcs8", - decryptionParameters.recipientPrivateKey, - { - name: "ECDH", - namedCurve: recipientCurve - } as EcKeyImportParams, - true, - ["deriveBits"] - ); + let ecdhPrivateKey: CryptoKey; + let keyCrypto: SubtleCrypto = crypto; + if (BufferSourceConverter.isBufferSource(decryptionParameters.recipientPrivateKey)) { + ecdhPrivateKey = await crypto.importKey("pkcs8", + decryptionParameters.recipientPrivateKey, + { + name: "ECDH", + namedCurve: recipientCurve + } as EcKeyImportParams, + true, + ["deriveBits"] + ); + } else { + ecdhPrivateKey = decryptionParameters.recipientPrivateKey; + if ("crypto" in decryptionParameters && decryptionParameters.crypto) { + keyCrypto = decryptionParameters.crypto.subtle; + } + } //#endregion //#region Import sender's ephemeral public key //#region Change "OriginatorPublicKey" if "curve" parameter absent @@ -1215,7 +1244,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { //#endregion //#region Create shared secret - const sharedSecret = await crypto.deriveBits({ + const sharedSecret = await keyCrypto.deriveBits({ name: "ECDH", public: ecdhPublicKey }, @@ -1293,7 +1322,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { //#endregion return crypto.unwrapKey("raw", - recipientInfo.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView, + recipientInfo.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView as BufferSource, aesKwKey, { name: "AES-KW" }, contentEncryptionAlgorithm, @@ -1330,18 +1359,27 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { } //#endregion - const privateKey = await crypto.importKey( - "pkcs8", - decryptionParameters.recipientPrivateKey, - algorithmParameters, - true, - ["decrypt"] - ); + let privateKey: CryptoKey; + let keyCrypto: SubtleCrypto = crypto; + if (BufferSourceConverter.isBufferSource(decryptionParameters.recipientPrivateKey)) { + privateKey = await crypto.importKey( + "pkcs8", + decryptionParameters.recipientPrivateKey, + algorithmParameters, + true, + ["decrypt"] + ); + } else { + privateKey = decryptionParameters.recipientPrivateKey; + if ("crypto" in decryptionParameters && decryptionParameters.crypto) { + keyCrypto = decryptionParameters.crypto.subtle; + } + } - const sessionKey = await crypto.decrypt( + const sessionKey = await keyCrypto.decrypt( privateKey.algorithm, privateKey, - recipientInfo.encryptedKey.valueBlock.valueHexView + recipientInfo.encryptedKey.valueBlock.valueHexView as BufferSource ); //#region Get WebCrypto form of content encryption algorithm @@ -1389,7 +1427,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { //#endregion return crypto.unwrapKey("raw", - recipientInfo.encryptedKey.valueBlock.valueHexView, + recipientInfo.encryptedKey.valueBlock.valueHexView as BufferSource, importedKey, kekAlgorithm, contentEncryptionAlgorithm, @@ -1421,7 +1459,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { try { pbkdf2Params = new PBKDF2Params({ schema: recipientInfo.keyDerivationAlgorithm.algorithmParams }); } - catch (ex) { + catch { throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); } @@ -1469,7 +1507,7 @@ export class EnvelopedData extends PkiObject implements IEnvelopedData { //#endregion return crypto.unwrapKey("raw", - recipientInfo.encryptedKey.valueBlock.valueHexView, + recipientInfo.encryptedKey.valueBlock.valueHexView as BufferSource, kekKey, kekAlgorithm, contentEncryptionAlgorithm, diff --git a/third_party/js/PKI.js/src/Extension.ts b/third_party/js/PKI.js/src/Extension.ts @@ -60,7 +60,7 @@ export class Extension extends PkiObject implements IExtension { public get parsedValue(): ExtensionParsedValue | undefined { if (this._parsedValue === undefined) { // Get PARSED_VALUE for well-known extensions - const parsedValue = ExtensionValueFactory.fromBER(this.extnID, this.extnValue.valueBlock.valueHexView); + const parsedValue = ExtensionValueFactory.fromBER(this.extnID, this.extnValue.valueBlock.valueHexView as BufferSource); this._parsedValue = parsedValue; } diff --git a/third_party/js/PKI.js/src/ExtensionValueFactory.ts b/third_party/js/PKI.js/src/ExtensionValueFactory.ts @@ -61,7 +61,7 @@ export class ExtensionValueFactory { if (item) { try { return new item.type({ schema: asn1.result }); - } catch (ex) { + } catch { const res: ExtensionParsedValue = new item.type(); res.parsingError = `Incorrectly formatted value of extension ${item.name} (${id})`; diff --git a/third_party/js/PKI.js/src/GeneralName.ts b/third_party/js/PKI.js/src/GeneralName.ts @@ -631,7 +631,7 @@ export class GeneralName extends PkiObject implements IGeneralName { try { _object.value = this.value.toJSON(); } - catch (ex) { + catch { // nothing } } diff --git a/third_party/js/PKI.js/src/OCSPResponse.ts b/third_party/js/PKI.js/src/OCSPResponse.ts @@ -276,7 +276,7 @@ export class OCSPResponse extends PkiObject implements IOCSPResponse { AsnError.assert(asn1Basic, "Basic OCSP response"); basicResponse = new BasicOCSPResponse({ schema: asn1Basic.result }); } - catch (ex) { + catch { return result; } //#endregion @@ -292,7 +292,7 @@ export class OCSPResponse extends PkiObject implements IOCSPResponse { public async sign(privateKey: CryptoKey, hashAlgorithm?: string, crypto = common.getCrypto(true)) { //#region Check that ResponseData has type BasicOCSPResponse and sign it if (this.responseBytes && this.responseBytes.responseType === id_PKIX_OCSP_Basic) { - const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView); + const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView as BufferSource); return basicResponse.sign(privateKey, hashAlgorithm, crypto); } @@ -314,7 +314,7 @@ export class OCSPResponse extends PkiObject implements IOCSPResponse { //#region Check that ResponseData has type BasicOCSPResponse and verify it if (this.responseBytes && this.responseBytes.responseType === id_PKIX_OCSP_Basic) { - const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView); + const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView as BufferSource); if (issuerCertificate !== null) { if (!basicResponse.certs) { diff --git a/third_party/js/PKI.js/src/OtherKeyAttribute.ts b/third_party/js/PKI.js/src/OtherKeyAttribute.ts @@ -76,7 +76,7 @@ export class OtherKeyAttribute extends PkiObject implements IOtherKeyAttribute { * @param memberName String name for a class member * @param memberValue Value to compare with default value */ - public static compareWithDefault<T>(memberName: string, memberValue: T): memberValue is T { + public static compareWithDefault<T extends object>(memberName: string, memberValue: T): memberValue is T { switch (memberName) { case KEY_ATTR_ID: return (typeof memberValue === "string" && memberValue === EMPTY_STRING); diff --git a/third_party/js/PKI.js/src/PFX.ts b/third_party/js/PKI.js/src/PFX.ts @@ -50,9 +50,7 @@ export interface PFXParsedValue { } export type MakeInternalValuesParams = - { - // empty - } + object | { iterations: number; diff --git a/third_party/js/PKI.js/src/PKCS8ShroudedKeyBag.ts b/third_party/js/PKI.js/src/PKCS8ShroudedKeyBag.ts @@ -215,7 +215,7 @@ export class PKCS8ShroudedKeyBag extends PkiObject implements IPKCS8ShroudedKeyB //#endregion } - public async makeInternalValues(parameters: PKCS8ShroudedKeyBagMakeInternalValuesParams): Promise<void> { + public async makeInternalValues(parameters: PKCS8ShroudedKeyBagMakeInternalValuesParams, crypto = common.getCrypto(true)): Promise<void> { //#region Check that we do have PARSED_VALUE if (!this.parsedValue) { throw new Error("Please initialize \"parsedValue\" first"); @@ -232,7 +232,7 @@ export class PKCS8ShroudedKeyBag extends PkiObject implements IPKCS8ShroudedKeyB contentToEncrypt: this.parsedValue.toSchema().toBER(false), }; - await cmsEncrypted.encrypt(encryptParams); + await cmsEncrypted.encrypt(encryptParams, crypto); if (!cmsEncrypted.encryptedContentInfo.encryptedContent) { throw new Error("The filed `encryptedContent` in EncryptedContentInfo is empty"); } diff --git a/third_party/js/PKI.js/src/PublicKeyInfo.ts b/third_party/js/PKI.js/src/PublicKeyInfo.ts @@ -25,7 +25,7 @@ export interface IPublicKeyInfo { /** * Parsed public key value */ - parsedKey?: ECPublicKey | RSAPublicKey; + parsedKey?: ECPublicKey | RSAPublicKey | undefined; } export type PublicKeyInfoParameters = PkiObjectParameters & Partial<IPublicKeyInfo> & { json?: JsonWebKey; }; @@ -62,7 +62,7 @@ export class PublicKeyInfo extends PkiObject implements IPublicKeyInfo { schema: this.subjectPublicKey.valueBlock.valueHexView }); } - catch (ex) { + catch { // nothing } // Could be a problems during recognition of internal public key data here. Let's ignore them. } @@ -75,7 +75,7 @@ export class PublicKeyInfo extends PkiObject implements IPublicKeyInfo { try { this._parsedKey = new RSAPublicKey({ schema: publicKeyASN1.result }); } - catch (ex) { + catch { // nothing } // Could be a problems during recognition of internal public key data here. Let's ignore them. } @@ -262,7 +262,7 @@ export class PublicKeyInfo extends PkiObject implements IPublicKeyInfo { try { this.fromSchema(asn1.result); } - catch (exception) { + catch { throw new Error("Error during initializing object from schema"); } } catch (e) { diff --git a/third_party/js/PKI.js/src/Request.ts b/third_party/js/PKI.js/src/Request.ts @@ -3,7 +3,8 @@ import * as pvutils from "pvutils"; import { CertID, CertIDJson, CertIDSchema } from "./CertID"; import { EMPTY_STRING } from "./constants"; import { AsnError } from "./errors"; -import { Extension, ExtensionJson, ExtensionSchema } from "./Extension"; +import { Extension, ExtensionJson } from "./Extension"; +import { Extensions, ExtensionsSchema } from "./Extensions"; import { PkiObject, PkiObjectParameters } from "./PkiObject"; import * as Schema from "./Schema"; @@ -28,7 +29,7 @@ export type RequestParameters = PkiObjectParameters & Partial<IRequest>; export type RequestSchema = Schema.SchemaParameters<{ reqCert?: CertIDSchema; - extensions?: ExtensionSchema; + extensions?: ExtensionsSchema; singleRequestExtensions?: string; }>; @@ -115,7 +116,7 @@ export class Request extends PkiObject implements IRequest { tagClass: 3, // CONTEXT-SPECIFIC tagNumber: 0 // [0] }, - value: [Extension.schema(names.extensions || { + value: [Extensions.schema(names.extensions || { names: { blockName: (names.singleRequestExtensions || EMPTY_STRING) } diff --git a/third_party/js/PKI.js/src/Schema.ts b/third_party/js/PKI.js/src/Schema.ts @@ -26,6 +26,6 @@ export interface SchemaConstructor { /** * Parameters for schema generation */ -export interface SchemaParameters<N extends Record<string, any> = { /**/ }> { +export interface SchemaParameters<N extends Record<string, any> = object> { names?: SchemaNames & N; } diff --git a/third_party/js/PKI.js/src/SignedCertificateTimestamp.ts b/third_party/js/PKI.js/src/SignedCertificateTimestamp.ts @@ -6,7 +6,6 @@ import { PublicKeyInfo } from "./PublicKeyInfo"; import * as Schema from "./Schema"; import { AlgorithmIdentifier } from "./AlgorithmIdentifier"; import { Certificate } from "./Certificate"; -import { AsnError } from "./errors"; import { PkiObject, PkiObjectParameters } from "./PkiObject"; import { EMPTY_BUFFER, EMPTY_STRING } from "./constants"; import { SignedCertificateTimestampList } from "./SignedCertificateTimestampList"; @@ -39,7 +38,7 @@ export interface ISignedCertificateTimestamp { extensions: ArrayBuffer; hashAlgorithm: string; signatureAlgorithm: string; - signature: Schema.SchemaType; + signature: ArrayBuffer; } export interface SignedCertificateTimestampJson { @@ -49,7 +48,7 @@ export interface SignedCertificateTimestampJson { extensions: string; hashAlgorithm: string; signatureAlgorithm: string; - signature: Schema.SchemaType; + signature: string; } export type SignedCertificateTimestampParameters = PkiObjectParameters & Partial<ISignedCertificateTimestamp> & { stream?: bs.SeqStream; }; @@ -75,7 +74,7 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert public extensions!: ArrayBuffer; public hashAlgorithm!: string; public signatureAlgorithm!: string; - public signature: asn1js.BaseBlock; + public signature!: ArrayBuffer; /** * Initializes a new instance of the {@link SignedCertificateTimestamp} class @@ -112,7 +111,7 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert public static override defaultValues(memberName: typeof TIMESTAMP): Date; public static override defaultValues(memberName: typeof HASH_ALGORITHM): string; public static override defaultValues(memberName: typeof SIGNATURE_ALGORITHM): string; - public static override defaultValues(memberName: typeof SIGNATURE): Schema.SchemaType; + public static override defaultValues(memberName: typeof SIGNATURE): ArrayBuffer; public static override defaultValues(memberName: string): any { switch (memberName) { case VERSION: @@ -126,7 +125,7 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert case SIGNATURE_ALGORITHM: return EMPTY_STRING; case SIGNATURE: - return new asn1js.Any(); + return EMPTY_BUFFER; default: return super.defaultValues(memberName); } @@ -212,11 +211,7 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert //#region Signature const signatureLength = stream.getUint16(); - const signatureData = new Uint8Array(stream.getBlock(signatureLength)).buffer.slice(0); - - const asn1 = asn1js.fromBER(signatureData); - AsnError.assert(asn1, "SignedCertificateTimestamp"); - this.signature = asn1.result; + this.signature = new Uint8Array(stream.getBlock(signatureLength)).buffer.slice(0); //#endregion if (blockLength !== (47 + extensionsLength + signatureLength)) { @@ -238,7 +233,7 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert public toStream(): bs.SeqStream { const stream = new bs.SeqStream(); - stream.appendUint16(47 + this.extensions.byteLength + this.signature.valueBeforeDecodeView.byteLength); + stream.appendUint16(47 + this.extensions.byteLength + this.signature.byteLength); stream.appendChar(this.version); stream.appendView(new Uint8Array(this.logID)); @@ -305,10 +300,8 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert stream.appendChar(_signatureAlgorithm); - const _signature = this.signature.toBER(false); - - stream.appendUint16(_signature.byteLength); - stream.appendView(new Uint8Array(_signature)); + stream.appendUint16(this.signature.byteLength); + stream.appendView(new Uint8Array(this.signature)); return stream; } @@ -321,7 +314,7 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert extensions: pvutils.bufferToHexCodes(this.extensions), hashAlgorithm: this.hashAlgorithm, signatureAlgorithm: this.signatureAlgorithm, - signature: this.signature.toJSON() + signature: pvutils.bufferToHexCodes(this.signature), }; } @@ -385,7 +378,7 @@ export class SignedCertificateTimestamp extends PkiObject implements ISignedCert //#region Perform verification return crypto.verifyWithPublicKey( stream.buffer.slice(0, stream.length), - new asn1js.OctetString({ valueHex: this.signature.toBER(false) }), + new asn1js.OctetString({ valueHex: this.signature }), publicKeyInfo, { algorithmId: EMPTY_STRING } as AlgorithmIdentifier, "SHA-256" @@ -421,19 +414,21 @@ export async function verifySCTsForCertificate(certificate: Certificate, issuerC const stream = new bs.SeqStream(); //#region Remove certificate extension - for (let i = 0; certificate.extensions && i < certificate.extensions.length; i++) { - switch (certificate.extensions[i].extnID) { - case id_SignedCertificateTimestampList: - { - parsedValue = certificate.extensions[i].parsedValue; - - if (!parsedValue || parsedValue.timestamps.length === 0) - throw new Error("Nothing to verify in the certificate"); - - certificate.extensions.splice(i, 1); - } - break; - default: + if (certificate.extensions) { + for (let i = certificate.extensions.length - 1; i >=0; i--) { + switch (certificate.extensions[i].extnID) { + case id_SignedCertificateTimestampList: + { + parsedValue = certificate.extensions[i].parsedValue; + + if (!parsedValue || parsedValue.timestamps.length === 0) + throw new Error("Nothing to verify in the certificate"); + + certificate.extensions.splice(i, 1); + } + break; + default: + } } } //#endregion diff --git a/third_party/js/PKI.js/src/SignedData.ts b/third_party/js/PKI.js/src/SignedData.ts @@ -598,7 +598,7 @@ export class SignedData extends PkiObject implements ISignedData { continue; } - const digest = await crypto.digest({ name: "sha-1" }, certificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); + const digest = await crypto.digest({ name: "sha-1" }, certificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView as BufferSource); if (pvutils.isEqualBuffer(digest, keyId)) { signerCert = certificate; break; @@ -635,9 +635,9 @@ export class SignedData extends PkiObject implements ISignedData { let tstInfo: TSTInfo; try { - tstInfo = TSTInfo.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView); + tstInfo = TSTInfo.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView as BufferSource); } - catch (ex) { + catch { throw new SignedDataVerifyError({ date: checkDate, code: 15, @@ -652,7 +652,7 @@ export class SignedData extends PkiObject implements ISignedData { //#region Change "checkDate" and append "timestampSerial" checkDate = tstInfo.genTime; - timestampSerial = tstInfo.serialNumber.valueBlock.valueHexView.slice(); + timestampSerial = tstInfo.serialNumber.valueBlock.valueHexView.slice().buffer; //#endregion //#region Check that we do have detached data content @@ -765,7 +765,7 @@ export class SignedData extends PkiObject implements ISignedData { data = eContent.getValue(); } else - data = eContent.valueBlock.valueBeforeDecodeView; + data = eContent.valueBlock.valueBeforeDecodeView.slice().buffer; } else // Detached data { @@ -847,7 +847,11 @@ export class SignedData extends PkiObject implements ISignedData { } //#endregion - const verifyResult = await crypto.verifyWithPublicKey(data, signerInfo.signature, signerCert.subjectPublicKeyInfo, signerCert.signatureAlgorithm, shaAlgorithm); + // This adjustment is specifically for cases where the signature algorithm is rsaEncryption. + // In such cases, we rely on the hash mechanism defined in signerInfo.digestAlgorithm for verification. + const verifyResult = signerInfo.signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.1" + ? await crypto.verifyWithPublicKey(data, signerInfo.signature, signerCert.subjectPublicKeyInfo, signerInfo.signatureAlgorithm, shaAlgorithm) + : await crypto.verifyWithPublicKey(data, signerInfo.signature, signerCert.subjectPublicKeyInfo, signerInfo.signatureAlgorithm); //#region Make a final result @@ -893,9 +897,18 @@ export class SignedData extends PkiObject implements ISignedData { //#region Initial checking if (!privateKey) throw new Error("Need to provide a private key for signing"); + + const signerInfo = this.signerInfos[signerIndex]; + if (!signerInfo) { + throw new RangeError("SignerInfo index is out of range"); + } + //#endregion - //#region Simple check for supported algorithm + //#region Adjust hashAlgorithm based on privateKey if signedAttrs are missing + if (!signerInfo.signedAttrs?.attributes.length && "hash" in privateKey.algorithm && "hash" in privateKey.algorithm && privateKey.algorithm.hash) { + hashAlgorithm = (privateKey.algorithm.hash as Algorithm).name; + } const hashAlgorithmOID = crypto.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); //#endregion @@ -907,10 +920,6 @@ export class SignedData extends PkiObject implements ISignedData { })); } - const signerInfo = this.signerInfos[signerIndex]; - if (!signerInfo) { - throw new RangeError("SignerInfo index is out of range"); - } signerInfo.digestAlgorithm = new AlgorithmIdentifier({ algorithmId: hashAlgorithmOID, algorithmParams: new asn1js.Null() @@ -945,7 +954,7 @@ export class SignedData extends PkiObject implements ISignedData { data = eContent.getValue(); } else - data = eContent.valueBlock.valueBeforeDecodeView; + data = eContent.valueBlock.valueBeforeDecodeView.slice().buffer; } else // Detached data { diff --git a/third_party/js/PKI.js/src/SingleResponse.ts b/third_party/js/PKI.js/src/SingleResponse.ts @@ -274,8 +274,12 @@ export class SingleResponse extends PkiObject implements ISingleResponse { } if (this.singleExtensions) { - outputArray.push(new asn1js.Sequence({ - value: Array.from(this.singleExtensions, o => o.toSchema()) + outputArray.push(new asn1js.Constructed({ + idBlock: { + tagClass: 3, // CONTEXT-SPECIFIC + tagNumber: 1 // [1] + }, + value: [new asn1js.Sequence({ value: Array.from(this.singleExtensions, o => o.toSchema()) })] })); } diff --git a/third_party/js/PKI.js/src/TimeStampReq.ts b/third_party/js/PKI.js/src/TimeStampReq.ts @@ -95,6 +95,7 @@ export type TimeStampReqParameters = PkiObjectParameters & Partial<ITimeStampReq * }); * * const tspReqRaw = tspReq.toSchema().toBER(); + * ``` */ export class TimeStampReq extends PkiObject implements ITimeStampReq { diff --git a/third_party/js/PKI.js/src/common.ts b/third_party/js/PKI.js/src/common.ts @@ -106,7 +106,7 @@ export function getEngine(): GlobalCryptoEngine { try { _engine = (global as any)[process.pid].pkijs.engine; } - catch (ex) { + catch { throw new Error("Please call 'setEngine' before call to 'getEngine'"); } diff --git a/third_party/js/PKI.js/tsconfig.json b/third_party/js/PKI.js/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { - "target": "ES6", - "module": "ES6", + "target": "ES2019", + "module": "CommonJS", "moduleResolution": "node", "strict": true, "importHelpers": true, @@ -10,6 +10,7 @@ "experimentalDecorators": true }, "exclude": [ + "website", "build/*.ts" ] -} +} +\ No newline at end of file diff --git a/third_party/js/PKI.js/yarn.lock b/third_party/js/PKI.js/yarn.lock @@ -1,2877 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@ampproject/remapping@^2.1.0": - "integrity" "sha512-hoyByceqwKirw7w3Z7gnIIZC3Wx3J484Y3L/cMpXFbr7d9ZQj2mODrirNzcJa+SM3UlpWXYvKV4RlRpFXlWgXg==" - "resolved" "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.1.2.tgz" - "version" "2.1.2" - dependencies: - "@jridgewell/trace-mapping" "^0.3.0" - -"@babel/code-frame@^7.16.7": - "integrity" "sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg==" - "resolved" "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/highlight" "^7.16.7" - -"@babel/compat-data@^7.17.7": - "integrity" "sha512-p8pdE6j0a29TNGebNm7NzYZWB3xVZJBZ7XGs42uAKzQo8VQ3F0By/cQCtUEABwIqw5zo6WA4NbmxsfzADzMKnQ==" - "resolved" "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.17.7.tgz" - "version" "7.17.7" - -"@babel/core@^7.0.0", "@babel/core@^7.7.5": - "integrity" "sha512-djHlEfFHnSnTAcPb7dATbiM5HxGOP98+3JLBZtjRb5I7RXrw7kFRoG2dXM8cm3H+o11A8IFH/uprmJpwFynRNQ==" - "resolved" "https://registry.npmjs.org/@babel/core/-/core-7.17.7.tgz" - "version" "7.17.7" - dependencies: - "@ampproject/remapping" "^2.1.0" - "@babel/code-frame" "^7.16.7" - "@babel/generator" "^7.17.7" - "@babel/helper-compilation-targets" "^7.17.7" - "@babel/helper-module-transforms" "^7.17.7" - "@babel/helpers" "^7.17.7" - "@babel/parser" "^7.17.7" - "@babel/template" "^7.16.7" - "@babel/traverse" "^7.17.3" - "@babel/types" "^7.17.0" - "convert-source-map" "^1.7.0" - "debug" "^4.1.0" - "gensync" "^1.0.0-beta.2" - "json5" "^2.1.2" - "semver" "^6.3.0" - -"@babel/generator@^7.17.3", "@babel/generator@^7.17.7": - "integrity" "sha512-oLcVCTeIFadUoArDTwpluncplrYBmTCCZZgXCbgNGvOBBiSDDK3eWO4b/+eOTli5tKv1lg+a5/NAXg+nTcei1w==" - "resolved" "https://registry.npmjs.org/@babel/generator/-/generator-7.17.7.tgz" - "version" "7.17.7" - dependencies: - "@babel/types" "^7.17.0" - "jsesc" "^2.5.1" - "source-map" "^0.5.0" - -"@babel/helper-compilation-targets@^7.17.7": - "integrity" "sha512-UFzlz2jjd8kroj0hmCFV5zr+tQPi1dpC2cRsDV/3IEW8bJfCPrPpmcSN6ZS8RqIq4LXcmpipCQFPddyFA5Yc7w==" - "resolved" "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.17.7.tgz" - "version" "7.17.7" - dependencies: - "@babel/compat-data" "^7.17.7" - "@babel/helper-validator-option" "^7.16.7" - "browserslist" "^4.17.5" - "semver" "^6.3.0" - -"@babel/helper-environment-visitor@^7.16.7": - "integrity" "sha512-SLLb0AAn6PkUeAfKJCCOl9e1R53pQlGAfc4y4XuMRZfqeMYLE0dM1LMhqbGAlGQY0lfw5/ohoYWAe9V1yibRag==" - "resolved" "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/types" "^7.16.7" - -"@babel/helper-function-name@^7.16.7": - "integrity" "sha512-QfDfEnIUyyBSR3HtrtGECuZ6DAyCkYFp7GHl75vFtTnn6pjKeK0T1DB5lLkFvBea8MdaiUABx3osbgLyInoejA==" - "resolved" "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/helper-get-function-arity" "^7.16.7" - "@babel/template" "^7.16.7" - "@babel/types" "^7.16.7" - -"@babel/helper-get-function-arity@^7.16.7": - "integrity" "sha512-flc+RLSOBXzNzVhcLu6ujeHUrD6tANAOU5ojrRx/as+tbzf8+stUCj7+IfRRoAbEZqj/ahXEMsjhOhgeZsrnTw==" - "resolved" "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/types" "^7.16.7" - -"@babel/helper-hoist-variables@^7.16.7": - "integrity" "sha512-m04d/0Op34H5v7pbZw6pSKP7weA6lsMvfiIAMeIvkY/R4xQtBSMFEigu9QTZ2qB/9l22vsxtM8a+Q8CzD255fg==" - "resolved" "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/types" "^7.16.7" - -"@babel/helper-module-imports@^7.16.7": - "integrity" "sha512-LVtS6TqjJHFc+nYeITRo6VLXve70xmq7wPhWTqDJusJEgGmkAACWwMiTNrvfoQo6hEhFwAIixNkvB0jPXDL8Wg==" - "resolved" "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/types" "^7.16.7" - -"@babel/helper-module-transforms@^7.17.7": - "integrity" "sha512-VmZD99F3gNTYB7fJRDTi+u6l/zxY0BE6OIxPSU7a50s6ZUQkHwSDmV92FfM+oCG0pZRVojGYhkR8I0OGeCVREw==" - "resolved" "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.17.7.tgz" - "version" "7.17.7" - dependencies: - "@babel/helper-environment-visitor" "^7.16.7" - "@babel/helper-module-imports" "^7.16.7" - "@babel/helper-simple-access" "^7.17.7" - "@babel/helper-split-export-declaration" "^7.16.7" - "@babel/helper-validator-identifier" "^7.16.7" - "@babel/template" "^7.16.7" - "@babel/traverse" "^7.17.3" - "@babel/types" "^7.17.0" - -"@babel/helper-simple-access@^7.17.7": - "integrity" "sha512-txyMCGroZ96i+Pxr3Je3lzEJjqwaRC9buMUgtomcrLe5Nd0+fk1h0LLA+ixUF5OW7AhHuQ7Es1WcQJZmZsz2XA==" - "resolved" "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.17.7.tgz" - "version" "7.17.7" - dependencies: - "@babel/types" "^7.17.0" - -"@babel/helper-split-export-declaration@^7.16.7": - "integrity" "sha512-xbWoy/PFoxSWazIToT9Sif+jJTlrMcndIsaOKvTA6u7QEo7ilkRZpjew18/W3c7nm8fXdUDXh02VXTbZ0pGDNw==" - "resolved" "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/types" "^7.16.7" - -"@babel/helper-validator-identifier@^7.16.7": - "integrity" "sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw==" - "resolved" "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz" - "version" "7.16.7" - -"@babel/helper-validator-option@^7.16.7": - "integrity" "sha512-TRtenOuRUVo9oIQGPC5G9DgK4743cdxvtOw0weQNpZXaS16SCBi5MNjZF8vba3ETURjZpTbVn7Vvcf2eAwFozQ==" - "resolved" "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.16.7.tgz" - "version" "7.16.7" - -"@babel/helpers@^7.17.7": - "integrity" "sha512-TKsj9NkjJfTBxM7Phfy7kv6yYc4ZcOo+AaWGqQOKTPDOmcGkIFb5xNA746eKisQkm4yavUYh4InYM9S+VnO01w==" - "resolved" "https://registry.npmjs.org/@babel/helpers/-/helpers-7.17.7.tgz" - "version" "7.17.7" - dependencies: - "@babel/template" "^7.16.7" - "@babel/traverse" "^7.17.3" - "@babel/types" "^7.17.0" - -"@babel/highlight@^7.16.7": - "integrity" "sha512-5FnTQLSLswEj6IkgVw5KusNUUFY9ZGqe/TRFnP/BKYHYgfh7tc+C7mwiy95/yNP7Dh9x580Vv8r7u7ZfTBFxdw==" - "resolved" "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.10.tgz" - "version" "7.16.10" - dependencies: - "@babel/helper-validator-identifier" "^7.16.7" - "chalk" "^2.0.0" - "js-tokens" "^4.0.0" - -"@babel/parser@^7.16.7", "@babel/parser@^7.17.3", "@babel/parser@^7.17.7": - "integrity" "sha512-bm3AQf45vR4gKggRfvJdYJ0gFLoCbsPxiFLSH6hTVYABptNHY6l9NrhnucVjQ/X+SPtLANT9lc0fFhikj+VBRA==" - "resolved" "https://registry.npmjs.org/@babel/parser/-/parser-7.17.7.tgz" - "version" "7.17.7" - -"@babel/template@^7.16.7": - "integrity" "sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w==" - "resolved" "https://registry.npmjs.org/@babel/template/-/template-7.16.7.tgz" - "version" "7.16.7" - dependencies: - "@babel/code-frame" "^7.16.7" - "@babel/parser" "^7.16.7" - "@babel/types" "^7.16.7" - -"@babel/traverse@^7.17.3": - "integrity" "sha512-5irClVky7TxRWIRtxlh2WPUUOLhcPN06AGgaQSB8AEwuyEBgJVuJ5imdHm5zxk8w0QS5T+tDfnDxAlhWjpb7cw==" - "resolved" "https://registry.npmjs.org/@babel/traverse/-/traverse-7.17.3.tgz" - "version" "7.17.3" - dependencies: - "@babel/code-frame" "^7.16.7" - "@babel/generator" "^7.17.3" - "@babel/helper-environment-visitor" "^7.16.7" - "@babel/helper-function-name" "^7.16.7" - "@babel/helper-hoist-variables" "^7.16.7" - "@babel/helper-split-export-declaration" "^7.16.7" - "@babel/parser" "^7.17.3" - "@babel/types" "^7.17.0" - "debug" "^4.1.0" - "globals" "^11.1.0" - -"@babel/types@^7.16.7", "@babel/types@^7.17.0": - "integrity" "sha512-TmKSNO4D5rzhL5bjWFcVHHLETzfQ/AmbKpKPOSjlP0WoHZ6L911fgoOKY4Alp/emzG4cHJdyN49zpgkbXFEHHw==" - "resolved" "https://registry.npmjs.org/@babel/types/-/types-7.17.0.tgz" - "version" "7.17.0" - dependencies: - "@babel/helper-validator-identifier" "^7.16.7" - "to-fast-properties" "^2.0.0" - -"@cspotcode/source-map-support@^0.8.0": - "integrity" "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==" - "resolved" "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz" - "version" "0.8.1" - dependencies: - "@jridgewell/trace-mapping" "0.3.9" - -"@eslint/eslintrc@^1.3.0": - "integrity" "sha512-UWW0TMTmk2d7hLcWD1/e2g5HDM/HQ3csaLSqXCfqwh4uNDuNqlaKWXmEsL4Cs41Z0KnILNvwbHAah3C2yt06kw==" - "resolved" "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-1.3.0.tgz" - "version" "1.3.0" - dependencies: - "ajv" "^6.12.4" - "debug" "^4.3.2" - "espree" "^9.3.2" - "globals" "^13.15.0" - "ignore" "^5.2.0" - "import-fresh" "^3.2.1" - "js-yaml" "^4.1.0" - "minimatch" "^3.1.2" - "strip-json-comments" "^3.1.1" - -"@humanwhocodes/config-array@^0.10.4": - "integrity" "sha512-mXAIHxZT3Vcpg83opl1wGlVZ9xydbfZO3r5YfRSH6Gpp2J/PfdBP0wbDa2sO6/qRbcalpoevVyW6A/fI6LfeMw==" - "resolved" "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.10.4.tgz" - "version" "0.10.4" - dependencies: - "@humanwhocodes/object-schema" "^1.2.1" - "debug" "^4.1.1" - "minimatch" "^3.0.4" - -"@humanwhocodes/gitignore-to-minimatch@^1.0.2": - "integrity" "sha512-rSqmMJDdLFUsyxR6FMtD00nfQKKLFb1kv+qBbOVKqErvloEIJLo5bDTJTQNTYgeyp78JsA7u/NPi5jT1GR/MuA==" - "resolved" "https://registry.npmjs.org/@humanwhocodes/gitignore-to-minimatch/-/gitignore-to-minimatch-1.0.2.tgz" - "version" "1.0.2" - -"@humanwhocodes/object-schema@^1.2.1": - "integrity" "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==" - "resolved" "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz" - "version" "1.2.1" - -"@istanbuljs/load-nyc-config@^1.0.0": - "integrity" "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==" - "resolved" "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz" - "version" "1.1.0" - dependencies: - "camelcase" "^5.3.1" - "find-up" "^4.1.0" - "get-package-type" "^0.1.0" - "js-yaml" "^3.13.1" - "resolve-from" "^5.0.0" - -"@istanbuljs/schema@^0.1.2": - "integrity" "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==" - "resolved" "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz" - "version" "0.1.3" - -"@jridgewell/resolve-uri@^3.0.3": - "integrity" "sha512-VPeQ7+wH0itvQxnG+lIzWgkysKIr3L9sslimFW55rHMdGu/qCQ5z5h9zq4gI8uBtqkpHhsF4Z/OwExufUCThew==" - "resolved" "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.0.5.tgz" - "version" "3.0.5" - -"@jridgewell/sourcemap-codec@^1.4.10": - "integrity" "sha512-Fg32GrJo61m+VqYSdRSjRXMjQ06j8YIYfcTqndLYVAaHmroZHLJZCydsWBOTDqXS2v+mjxohBWEMfg97GXmYQg==" - "resolved" "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.11.tgz" - "version" "1.4.11" - -"@jridgewell/trace-mapping@^0.3.0", "@jridgewell/trace-mapping@0.3.9": - "integrity" "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==" - "resolved" "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz" - "version" "0.3.9" - dependencies: - "@jridgewell/resolve-uri" "^3.0.3" - "@jridgewell/sourcemap-codec" "^1.4.10" - -"@nodelib/fs.scandir@2.1.5": - "integrity" "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==" - "resolved" "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz" - "version" "2.1.5" - dependencies: - "@nodelib/fs.stat" "2.0.5" - "run-parallel" "^1.1.9" - -"@nodelib/fs.stat@^2.0.2", "@nodelib/fs.stat@2.0.5": - "integrity" "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==" - "resolved" "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz" - "version" "2.0.5" - -"@nodelib/fs.walk@^1.2.3": - "integrity" "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==" - "resolved" "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz" - "version" "1.2.8" - dependencies: - "@nodelib/fs.scandir" "2.1.5" - "fastq" "^1.6.0" - -"@peculiar/asn1-schema@^2.1.6": - "integrity" "sha512-6ewdxD32vsjxbI/MvTef7PQxZIfLyV4w/5XzjOkosIGNt726zj8evLitCbjTeMHSZ/VeU4ZFSnrPXdCBHI6NWQ==" - "resolved" "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.1.6.tgz" - "version" "2.1.6" - dependencies: - "asn1js" "^3.0.0" - "pvtsutils" "^1.3.2" - "tslib" "^2.4.0" - -"@peculiar/json-schema@^1.1.12": - "integrity" "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==" - "resolved" "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz" - "version" "1.1.12" - dependencies: - "tslib" "^2.0.0" - -"@peculiar/webcrypto@^1.4.0": - "integrity" "sha512-U58N44b2m3OuTgpmKgf0LPDOmP3bhwNz01vAnj1mBwxBASRhptWYK+M3zG+HBkDqGQM+bFsoIihTW8MdmPXEqg==" - "resolved" "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.4.0.tgz" - "version" "1.4.0" - dependencies: - "@peculiar/asn1-schema" "^2.1.6" - "@peculiar/json-schema" "^1.1.12" - "pvtsutils" "^1.3.2" - "tslib" "^2.4.0" - "webcrypto-core" "^1.7.4" - -"@rollup/plugin-alias@^3.1.9": - "integrity" "sha512-QI5fsEvm9bDzt32k39wpOwZhVzRcL5ydcffUHMyLVaVaLeC70I8TJZ17F1z1eMoLu4E/UOcH9BWVkKpIKdrfiw==" - "resolved" "https://registry.npmjs.org/@rollup/plugin-alias/-/plugin-alias-3.1.9.tgz" - "version" "3.1.9" - dependencies: - "slash" "^3.0.0" - -"@rollup/plugin-commonjs@^22.0.1": - "integrity" "sha512-dGfEZvdjDHObBiP5IvwTKMVeq/tBZGMBHZFMdIV1ClMM/YoWS34xrHFGfag9SN2ZtMgNZRFruqvxZQEa70O6nQ==" - "resolved" "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-22.0.1.tgz" - "version" "22.0.1" - dependencies: - "@rollup/pluginutils" "^3.1.0" - "commondir" "^1.0.1" - "estree-walker" "^2.0.1" - "glob" "^7.1.6" - "is-reference" "^1.2.1" - "magic-string" "^0.25.7" - "resolve" "^1.17.0" - -"@rollup/plugin-node-resolve@^13.3.0": - "integrity" "sha512-Lus8rbUo1eEcnS4yTFKLZrVumLPY+YayBdWXgFSHYhTT2iJbMhoaaBL3xl5NCdeRytErGr8tZ0L71BMRmnlwSw==" - "resolved" "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-13.3.0.tgz" - "version" "13.3.0" - dependencies: - "@rollup/pluginutils" "^3.1.0" - "@types/resolve" "1.17.1" - "deepmerge" "^4.2.2" - "is-builtin-module" "^3.1.0" - "is-module" "^1.0.0" - "resolve" "^1.19.0" - -"@rollup/pluginutils@^3.1.0": - "integrity" "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==" - "resolved" "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz" - "version" "3.1.0" - dependencies: - "@types/estree" "0.0.39" - "estree-walker" "^1.0.1" - "picomatch" "^2.2.2" - -"@rollup/pluginutils@^4.1.2": - "integrity" "sha512-2WUyJNRkyH5p487pGnn4tWAsxhEFKN/pT8CMgHshd5H+IXkOnKvKZwsz5ZWz+YCXkleZRAU5kwbfgF8CPfDRqA==" - "resolved" "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.0.tgz" - "version" "4.2.0" - dependencies: - "estree-walker" "^2.0.1" - "picomatch" "^2.2.2" - -"@tsconfig/node10@^1.0.7": - "integrity" "sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg==" - "resolved" "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.8.tgz" - "version" "1.0.8" - -"@tsconfig/node12@^1.0.7": - "integrity" "sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw==" - "resolved" "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.9.tgz" - "version" "1.0.9" - -"@tsconfig/node14@^1.0.0": - "integrity" "sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg==" - "resolved" "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.1.tgz" - "version" "1.0.1" - -"@tsconfig/node16@^1.0.2": - "integrity" "sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==" - "resolved" "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.2.tgz" - "version" "1.0.2" - -"@types/estree@*", "@types/estree@0.0.39": - "integrity" "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==" - "resolved" "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz" - "version" "0.0.39" - -"@types/json-schema@^7.0.9": - "integrity" "sha512-BLO9bBq59vW3fxCpD4o0N4U+DXsvwvIcl+jofw0frQo/GrBFC+/jRZj1E7kgp6dvTyNmA4y6JCV5Id/r3mNP5A==" - "resolved" "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.10.tgz" - "version" "7.0.10" - -"@types/mocha@^9.1.1": - "integrity" "sha512-Z61JK7DKDtdKTWwLeElSEBcWGRLY8g95ic5FoQqI9CMx0ns/Ghep3B4DfcEimiKMvtamNVULVNKEsiwV3aQmXw==" - "resolved" "https://registry.npmjs.org/@types/mocha/-/mocha-9.1.1.tgz" - "version" "9.1.1" - -"@types/node@*", "@types/node@^18.6.3": - "integrity" "sha512-6qKpDtoaYLM+5+AFChLhHermMQxc3TOEFIDzrZLPRGHPrLEwqFkkT5Kx3ju05g6X7uDPazz3jHbKPX0KzCjntg==" - "resolved" "https://registry.npmjs.org/@types/node/-/node-18.6.3.tgz" - "version" "18.6.3" - -"@types/resolve@1.17.1": - "integrity" "sha512-yy7HuzQhj0dhGpD8RLXSZWEkLsV9ibvxvi6EiJ3bkqLAO1RGo0WbkWQiwpRlSFymTJRz0d3k5LM3kkx8ArDbLw==" - "resolved" "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz" - "version" "1.17.1" - dependencies: - "@types/node" "*" - -"@typescript-eslint/eslint-plugin@^5.32.0": - "integrity" "sha512-CHLuz5Uz7bHP2WgVlvoZGhf0BvFakBJKAD/43Ty0emn4wXWv5k01ND0C0fHcl/Im8Td2y/7h44E9pca9qAu2ew==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.32.0.tgz" - "version" "5.32.0" - dependencies: - "@typescript-eslint/scope-manager" "5.32.0" - "@typescript-eslint/type-utils" "5.32.0" - "@typescript-eslint/utils" "5.32.0" - "debug" "^4.3.4" - "functional-red-black-tree" "^1.0.1" - "ignore" "^5.2.0" - "regexpp" "^3.2.0" - "semver" "^7.3.7" - "tsutils" "^3.21.0" - -"@typescript-eslint/experimental-utils@^5.0.0": - "integrity" "sha512-rKxoCUtAHwEH6IcAoVpqipY6Th+YKW7WFspAKu0IFdbdKZpveFBeqxxE9Xn+GWikhq1o03V3VXbxIe+GdhggiQ==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-5.22.0.tgz" - "version" "5.22.0" - dependencies: - "@typescript-eslint/utils" "5.22.0" - -"@typescript-eslint/parser@^5.0.0", "@typescript-eslint/parser@^5.32.0": - "integrity" "sha512-IxRtsehdGV9GFQ35IGm5oKKR2OGcazUoiNBxhRV160iF9FoyuXxjY+rIqs1gfnd+4eL98OjeGnMpE7RF/NBb3A==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.32.0.tgz" - "version" "5.32.0" - dependencies: - "@typescript-eslint/scope-manager" "5.32.0" - "@typescript-eslint/types" "5.32.0" - "@typescript-eslint/typescript-estree" "5.32.0" - "debug" "^4.3.4" - -"@typescript-eslint/scope-manager@5.22.0": - "integrity" "sha512-yA9G5NJgV5esANJCO0oF15MkBO20mIskbZ8ijfmlKIvQKg0ynVKfHZ15/nhAJN5m8Jn3X5qkwriQCiUntC9AbA==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.22.0.tgz" - "version" "5.22.0" - dependencies: - "@typescript-eslint/types" "5.22.0" - "@typescript-eslint/visitor-keys" "5.22.0" - -"@typescript-eslint/scope-manager@5.32.0": - "integrity" "sha512-KyAE+tUON0D7tNz92p1uetRqVJiiAkeluvwvZOqBmW9z2XApmk5WSMV9FrzOroAcVxJZB3GfUwVKr98Dr/OjOg==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.32.0.tgz" - "version" "5.32.0" - dependencies: - "@typescript-eslint/types" "5.32.0" - "@typescript-eslint/visitor-keys" "5.32.0" - -"@typescript-eslint/type-utils@5.32.0": - "integrity" "sha512-0gSsIhFDduBz3QcHJIp3qRCvVYbqzHg8D6bHFsDMrm0rURYDj+skBK2zmYebdCp+4nrd9VWd13egvhYFJj/wZg==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.32.0.tgz" - "version" "5.32.0" - dependencies: - "@typescript-eslint/utils" "5.32.0" - "debug" "^4.3.4" - "tsutils" "^3.21.0" - -"@typescript-eslint/types@5.22.0": - "integrity" "sha512-T7owcXW4l0v7NTijmjGWwWf/1JqdlWiBzPqzAWhobxft0SiEvMJB56QXmeCQjrPuM8zEfGUKyPQr/L8+cFUBLw==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.22.0.tgz" - "version" "5.22.0" - -"@typescript-eslint/types@5.32.0": - "integrity" "sha512-EBUKs68DOcT/EjGfzywp+f8wG9Zw6gj6BjWu7KV/IYllqKJFPlZlLSYw/PTvVyiRw50t6wVbgv4p9uE2h6sZrQ==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.32.0.tgz" - "version" "5.32.0" - -"@typescript-eslint/typescript-estree@5.22.0": - "integrity" "sha512-EyBEQxvNjg80yinGE2xdhpDYm41so/1kOItl0qrjIiJ1kX/L/L8WWGmJg8ni6eG3DwqmOzDqOhe6763bF92nOw==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.22.0.tgz" - "version" "5.22.0" - dependencies: - "@typescript-eslint/types" "5.22.0" - "@typescript-eslint/visitor-keys" "5.22.0" - "debug" "^4.3.2" - "globby" "^11.0.4" - "is-glob" "^4.0.3" - "semver" "^7.3.5" - "tsutils" "^3.21.0" - -"@typescript-eslint/typescript-estree@5.32.0": - "integrity" "sha512-ZVAUkvPk3ITGtCLU5J4atCw9RTxK+SRc6hXqLtllC2sGSeMFWN+YwbiJR9CFrSFJ3w4SJfcWtDwNb/DmUIHdhg==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.32.0.tgz" - "version" "5.32.0" - dependencies: - "@typescript-eslint/types" "5.32.0" - "@typescript-eslint/visitor-keys" "5.32.0" - "debug" "^4.3.4" - "globby" "^11.1.0" - "is-glob" "^4.0.3" - "semver" "^7.3.7" - "tsutils" "^3.21.0" - -"@typescript-eslint/utils@5.22.0": - "integrity" "sha512-HodsGb037iobrWSUMS7QH6Hl1kppikjA1ELiJlNSTYf/UdMEwzgj0WIp+lBNb6WZ3zTwb0tEz51j0Wee3iJ3wQ==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.22.0.tgz" - "version" "5.22.0" - dependencies: - "@types/json-schema" "^7.0.9" - "@typescript-eslint/scope-manager" "5.22.0" - "@typescript-eslint/types" "5.22.0" - "@typescript-eslint/typescript-estree" "5.22.0" - "eslint-scope" "^5.1.1" - "eslint-utils" "^3.0.0" - -"@typescript-eslint/utils@5.32.0": - "integrity" "sha512-W7lYIAI5Zlc5K082dGR27Fczjb3Q57ECcXefKU/f0ajM5ToM0P+N9NmJWip8GmGu/g6QISNT+K6KYB+iSHjXCQ==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.32.0.tgz" - "version" "5.32.0" - dependencies: - "@types/json-schema" "^7.0.9" - "@typescript-eslint/scope-manager" "5.32.0" - "@typescript-eslint/types" "5.32.0" - "@typescript-eslint/typescript-estree" "5.32.0" - "eslint-scope" "^5.1.1" - "eslint-utils" "^3.0.0" - -"@typescript-eslint/visitor-keys@5.22.0": - "integrity" "sha512-DbgTqn2Dv5RFWluG88tn0pP6Ex0ROF+dpDO1TNNZdRtLjUr6bdznjA6f/qNqJLjd2PgguAES2Zgxh/JzwzETDg==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.22.0.tgz" - "version" "5.22.0" - dependencies: - "@typescript-eslint/types" "5.22.0" - "eslint-visitor-keys" "^3.0.0" - -"@typescript-eslint/visitor-keys@5.32.0": - "integrity" "sha512-S54xOHZgfThiZ38/ZGTgB2rqx51CMJ5MCfVT2IplK4Q7hgzGfe0nLzLCcenDnc/cSjP568hdeKfeDcBgqNHD/g==" - "resolved" "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.32.0.tgz" - "version" "5.32.0" - dependencies: - "@typescript-eslint/types" "5.32.0" - "eslint-visitor-keys" "^3.3.0" - -"@ungap/promise-all-settled@1.1.2": - "integrity" "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==" - "resolved" "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz" - "version" "1.1.2" - -"acorn-jsx@^5.3.2": - "integrity" "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==" - "resolved" "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz" - "version" "5.3.2" - -"acorn-walk@^8.1.1": - "integrity" "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==" - "resolved" "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz" - "version" "8.2.0" - -"acorn@^6.0.0 || ^7.0.0 || ^8.0.0", "acorn@^8.4.1", "acorn@^8.8.0": - "integrity" "sha512-QOxyigPVrpZ2GXT+PFyZTl6TtOFc5egxHIP9IlQ+RbupQuX4RkT/Bee4/kQuC02Xkzg84JcT7oLYtDIQxp+v7w==" - "resolved" "https://registry.npmjs.org/acorn/-/acorn-8.8.0.tgz" - "version" "8.8.0" - -"aggregate-error@^3.0.0": - "integrity" "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==" - "resolved" "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz" - "version" "3.1.0" - dependencies: - "clean-stack" "^2.0.0" - "indent-string" "^4.0.0" - -"ajv@^6.10.0", "ajv@^6.12.4": - "integrity" "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==" - "resolved" "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz" - "version" "6.12.6" - dependencies: - "fast-deep-equal" "^3.1.1" - "fast-json-stable-stringify" "^2.0.0" - "json-schema-traverse" "^0.4.1" - "uri-js" "^4.2.2" - -"ansi-colors@4.1.1": - "integrity" "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==" - "resolved" "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz" - "version" "4.1.1" - -"ansi-regex@^5.0.1": - "integrity" "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" - "resolved" "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz" - "version" "5.0.1" - -"ansi-styles@^3.2.1": - "integrity" "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==" - "resolved" "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz" - "version" "3.2.1" - dependencies: - "color-convert" "^1.9.0" - -"ansi-styles@^4.0.0", "ansi-styles@^4.1.0": - "integrity" "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==" - "resolved" "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz" - "version" "4.3.0" - dependencies: - "color-convert" "^2.0.1" - -"anymatch@~3.1.2": - "integrity" "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==" - "resolved" "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz" - "version" "3.1.2" - dependencies: - "normalize-path" "^3.0.0" - "picomatch" "^2.0.4" - -"append-transform@^2.0.0": - "integrity" "sha512-7yeyCEurROLQJFv5Xj4lEGTy0borxepjFv1g22oAdqFu//SrAlDl1O1Nxx15SH1RoliUml6p8dwJW9jvZughhg==" - "resolved" "https://registry.npmjs.org/append-transform/-/append-transform-2.0.0.tgz" - "version" "2.0.0" - dependencies: - "default-require-extensions" "^3.0.0" - -"archy@^1.0.0": - "integrity" "sha1-+cjBN1fMHde8N5rHeyxipcKGjEA= sha512-Xg+9RwCg/0p32teKdGMPTPnVXKD0w3DfHnFTficozsAgsvq2XenPJq/MYpzzQ/v8zrOyJn6Ds39VA4JIDwFfqw==" - "resolved" "https://registry.npmjs.org/archy/-/archy-1.0.0.tgz" - "version" "1.0.0" - -"arg@^4.1.0": - "integrity" "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==" - "resolved" "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz" - "version" "4.1.3" - -"argparse@^1.0.7": - "integrity" "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==" - "resolved" "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz" - "version" "1.0.10" - dependencies: - "sprintf-js" "~1.0.2" - -"argparse@^2.0.1": - "integrity" "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" - "resolved" "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz" - "version" "2.0.1" - -"array-union@^2.1.0": - "integrity" "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==" - "resolved" "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz" - "version" "2.1.0" - -"asn1js@^3.0.0", "asn1js@^3.0.1", "asn1js@^3.0.5": - "integrity" "sha512-FVnvrKJwpt9LP2lAMl8qZswRNm3T4q9CON+bxldk2iwk3FFpuwhx2FfinyitizWHsVYyaY+y5JzDR0rCMV5yTQ==" - "resolved" "https://registry.npmjs.org/asn1js/-/asn1js-3.0.5.tgz" - "version" "3.0.5" - dependencies: - "pvtsutils" "^1.3.2" - "pvutils" "^1.1.3" - "tslib" "^2.4.0" - -"assert@^2.0.0": - "integrity" "sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==" - "resolved" "https://registry.npmjs.org/assert/-/assert-2.0.0.tgz" - "version" "2.0.0" - dependencies: - "es6-object-assign" "^1.1.0" - "is-nan" "^1.2.1" - "object-is" "^1.0.1" - "util" "^0.12.0" - -"available-typed-arrays@^1.0.5": - "integrity" "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==" - "resolved" "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz" - "version" "1.0.5" - -"balanced-match@^1.0.0": - "integrity" "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" - "resolved" "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz" - "version" "1.0.2" - -"binary-extensions@^2.0.0": - "integrity" "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==" - "resolved" "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz" - "version" "2.2.0" - -"brace-expansion@^1.1.7": - "integrity" "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==" - "resolved" "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz" - "version" "1.1.11" - dependencies: - "balanced-match" "^1.0.0" - "concat-map" "0.0.1" - -"brace-expansion@^2.0.1": - "integrity" "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==" - "resolved" "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz" - "version" "2.0.1" - dependencies: - "balanced-match" "^1.0.0" - -"braces@^3.0.1", "braces@~3.0.2": - "integrity" "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==" - "resolved" "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz" - "version" "3.0.2" - dependencies: - "fill-range" "^7.0.1" - -"browser-stdout@1.3.1": - "integrity" "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==" - "resolved" "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz" - "version" "1.3.1" - -"browserslist@^4.17.5": - "integrity" "sha512-CQOBCqp/9pDvDbx3xfMi+86pr4KXIf2FDkTTdeuYw8OxS9t898LA1Khq57gtufFILXpfgsSx5woNgsBgvGjpsA==" - "resolved" "https://registry.npmjs.org/browserslist/-/browserslist-4.20.2.tgz" - "version" "4.20.2" - dependencies: - "caniuse-lite" "^1.0.30001317" - "electron-to-chromium" "^1.4.84" - "escalade" "^3.1.1" - "node-releases" "^2.0.2" - "picocolors" "^1.0.0" - -"builtin-modules@^3.0.0": - "integrity" "sha512-lGzLKcioL90C7wMczpkY0n/oART3MbBa8R9OFGE1rJxoVI86u4WAGfEk8Wjv10eKSyTHVGkSo3bvBylCEtk7LA==" - "resolved" "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.2.0.tgz" - "version" "3.2.0" - -"bytestreamjs@^2.0.0": - "integrity" "sha512-TyOlxeS92FcMOaJwAVq5gwqW0vfkWUv5W+ErwdbBzolcUN/9XYpCKWvCV21jjzXU550D9Wt4GgE8Pr1vVbR+wQ==" - "resolved" "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.0.tgz" - "version" "2.0.0" - -"caching-transform@^4.0.0": - "integrity" "sha512-kpqOvwXnjjN44D89K5ccQC+RUrsy7jB/XLlRrx0D7/2HNcTPqzsb6XgYoErwko6QsV184CA2YgS1fxDiiDZMWA==" - "resolved" "https://registry.npmjs.org/caching-transform/-/caching-transform-4.0.0.tgz" - "version" "4.0.0" - dependencies: - "hasha" "^5.0.0" - "make-dir" "^3.0.0" - "package-hash" "^4.0.0" - "write-file-atomic" "^3.0.0" - -"call-bind@^1.0.0", "call-bind@^1.0.2": - "integrity" "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==" - "resolved" "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz" - "version" "1.0.2" - dependencies: - "function-bind" "^1.1.1" - "get-intrinsic" "^1.0.2" - -"callsites@^3.0.0": - "integrity" "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==" - "resolved" "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz" - "version" "3.1.0" - -"camelcase@^5.0.0", "camelcase@^5.3.1": - "integrity" "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" - "resolved" "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz" - "version" "5.3.1" - -"camelcase@^6.0.0": - "integrity" "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==" - "resolved" "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz" - "version" "6.3.0" - -"caniuse-lite@^1.0.30001317": - "integrity" "sha512-xIZLh8gBm4dqNX0gkzrBeyI86J2eCjWzYAs40q88smG844YIrN4tVQl/RhquHvKEKImWWFIVh1Lxe5n1G/N+GQ==" - "resolved" "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001317.tgz" - "version" "1.0.30001317" - -"chalk@^2.0.0": - "integrity" "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==" - "resolved" "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz" - "version" "2.4.2" - dependencies: - "ansi-styles" "^3.2.1" - "escape-string-regexp" "^1.0.5" - "supports-color" "^5.3.0" - -"chalk@^4.0.0", "chalk@^4.1.0": - "integrity" "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==" - "resolved" "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz" - "version" "4.1.2" - dependencies: - "ansi-styles" "^4.1.0" - "supports-color" "^7.1.0" - -"chokidar@3.5.3": - "integrity" "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==" - "resolved" "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz" - "version" "3.5.3" - dependencies: - "anymatch" "~3.1.2" - "braces" "~3.0.2" - "glob-parent" "~5.1.2" - "is-binary-path" "~2.1.0" - "is-glob" "~4.0.1" - "normalize-path" "~3.0.0" - "readdirp" "~3.6.0" - optionalDependencies: - "fsevents" "~2.3.2" - -"clean-stack@^2.0.0": - "integrity" "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==" - "resolved" "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz" - "version" "2.2.0" - -"cliui@^6.0.0": - "integrity" "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==" - "resolved" "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz" - "version" "6.0.0" - dependencies: - "string-width" "^4.2.0" - "strip-ansi" "^6.0.0" - "wrap-ansi" "^6.2.0" - -"cliui@^7.0.2": - "integrity" "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==" - "resolved" "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz" - "version" "7.0.4" - dependencies: - "string-width" "^4.2.0" - "strip-ansi" "^6.0.0" - "wrap-ansi" "^7.0.0" - -"color-convert@^1.9.0": - "integrity" "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==" - "resolved" "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz" - "version" "1.9.3" - dependencies: - "color-name" "1.1.3" - -"color-convert@^2.0.1": - "integrity" "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==" - "resolved" "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz" - "version" "2.0.1" - dependencies: - "color-name" "~1.1.4" - -"color-name@~1.1.4": - "integrity" "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" - "resolved" "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz" - "version" "1.1.4" - -"color-name@1.1.3": - "integrity" "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" - "resolved" "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz" - "version" "1.1.3" - -"commondir@^1.0.1": - "integrity" "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs= sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==" - "resolved" "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz" - "version" "1.0.1" - -"concat-map@0.0.1": - "integrity" "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" - "resolved" "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" - "version" "0.0.1" - -"convert-source-map@^1.7.0": - "integrity" "sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==" - "resolved" "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.8.0.tgz" - "version" "1.8.0" - dependencies: - "safe-buffer" "~5.1.1" - -"create-require@^1.1.0": - "integrity" "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==" - "resolved" "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz" - "version" "1.1.1" - -"cross-spawn@^7.0.0", "cross-spawn@^7.0.2": - "integrity" "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==" - "resolved" "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz" - "version" "7.0.3" - dependencies: - "path-key" "^3.1.0" - "shebang-command" "^2.0.0" - "which" "^2.0.1" - -"debug@^4.1.0", "debug@^4.1.1", "debug@^4.3.2", "debug@^4.3.4", "debug@4.3.4": - "integrity" "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==" - "resolved" "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz" - "version" "4.3.4" - dependencies: - "ms" "2.1.2" - -"decamelize@^1.2.0": - "integrity" "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==" - "resolved" "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz" - "version" "1.2.0" - -"decamelize@^4.0.0": - "integrity" "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==" - "resolved" "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz" - "version" "4.0.0" - -"deep-is@^0.1.3": - "integrity" "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==" - "resolved" "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz" - "version" "0.1.4" - -"deepmerge@^4.2.2": - "integrity" "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==" - "resolved" "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz" - "version" "4.2.2" - -"default-require-extensions@^3.0.0": - "integrity" "sha512-ek6DpXq/SCpvjhpFsLFRVtIxJCRw6fUR42lYMVZuUMK7n8eMz4Uh5clckdBjEpLhn/gEBZo7hDJnJcwdKLKQjg==" - "resolved" "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-3.0.0.tgz" - "version" "3.0.0" - dependencies: - "strip-bom" "^4.0.0" - -"define-properties@^1.1.3": - "integrity" "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==" - "resolved" "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz" - "version" "1.1.3" - dependencies: - "object-keys" "^1.0.12" - -"diff@^4.0.1": - "integrity" "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==" - "resolved" "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz" - "version" "4.0.2" - -"diff@5.0.0": - "integrity" "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==" - "resolved" "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz" - "version" "5.0.0" - -"dir-glob@^3.0.1": - "integrity" "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==" - "resolved" "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz" - "version" "3.0.1" - dependencies: - "path-type" "^4.0.0" - -"doctrine@^3.0.0": - "integrity" "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==" - "resolved" "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz" - "version" "3.0.0" - dependencies: - "esutils" "^2.0.2" - -"electron-to-chromium@^1.4.84": - "integrity" "sha512-EXXTtDHFUKdFVkCnhauU7Xp8wmFC1ZG6GK9a1BeI2vvNhy61IwfNPo/CRexhf7mh4ajxAHJPind62BzpzVUeuQ==" - "resolved" "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.87.tgz" - "version" "1.4.87" - -"emailjs-addressparser@^2.0.1", "emailjs-addressparser@^2.0.2": - "integrity" "sha512-E6ztFf1ePtZEwqfN3aWsvZNcpBeDqgJbVL4D32dckHkcwdhJ1bhlE4MLvHBf/IoXQmJBgkKlwGP5/5l11EE5OQ==" - "resolved" "https://registry.npmjs.org/emailjs-addressparser/-/emailjs-addressparser-2.0.2.tgz" - "version" "2.0.2" - -"emailjs-base64@^1.1.4": - "integrity" "sha512-4h0xp1jgVTnIQBHxSJWXWanNnmuc5o+k4aHEpcLXSToN8asjB5qbXAexs7+PEsUKcEyBteNYsSvXUndYT2CGGA==" - "resolved" "https://registry.npmjs.org/emailjs-base64/-/emailjs-base64-1.1.4.tgz" - "version" "1.1.4" - -"emailjs-mime-builder@^2.0.5": - "integrity" "sha512-fkaUn6IA4onX3SmVpqvVTlkdrusM9lq+xnrA24euyMUga2B44Ue0ftE48aSNveEWPgGLtHfSd04lGWhT2/AOpw==" - "resolved" "https://registry.npmjs.org/emailjs-mime-builder/-/emailjs-mime-builder-2.0.5.tgz" - "version" "2.0.5" - dependencies: - "emailjs-addressparser" "^2.0.2" - "emailjs-mime-codec" "^2.0.5" - "emailjs-mime-types" "^2.0.0" - "punycode" "1.4.1" - "ramda" "^0.25.0" - -"emailjs-mime-codec@^2.0.5", "emailjs-mime-codec@^2.0.8": - "integrity" "sha512-7qJo4pFGcKlWh/kCeNjmcgj34YoJWY0ekZXEHYtluWg4MVBnXqGM4CRMtZQkfYwitOhUgaKN5EQktJddi/YIDQ==" - "resolved" "https://registry.npmjs.org/emailjs-mime-codec/-/emailjs-mime-codec-2.0.9.tgz" - "version" "2.0.9" - dependencies: - "emailjs-base64" "^1.1.4" - "ramda" "^0.26.1" - "text-encoding" "^0.7.0" - -"emailjs-mime-parser@^2.0.7": - "integrity" "sha512-rOrRtAzq0OVLrxbTkRLyrtoY/YQldPgIzAk6lcD3LfXR0Gw3+PzsN2rO1QENY+cIQD94vYr2t2Ri0Zxlc9aeew==" - "resolved" "https://registry.npmjs.org/emailjs-mime-parser/-/emailjs-mime-parser-2.0.7.tgz" - "version" "2.0.7" - dependencies: - "emailjs-addressparser" "^2.0.1" - "emailjs-mime-codec" "^2.0.8" - "ramda" "^0.26.1" - -"emailjs-mime-types@^2.0.0": - "integrity" "sha512-vlmgTAE3cya0GHoqHYgvmzG342sKGsHhddJhOSqXIZM0V7kjUAKxXmol3NTyeuHltggCp6HJT3NRqJuDkchCrw==" - "resolved" "https://registry.npmjs.org/emailjs-mime-types/-/emailjs-mime-types-2.1.0.tgz" - "version" "2.1.0" - -"emoji-regex@^8.0.0": - "integrity" "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" - "resolved" "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz" - "version" "8.0.0" - -"es-abstract@^1.18.5": - "integrity" "sha512-gfSBJoZdlL2xRiOCy0g8gLMryhoe1TlimjzU99L/31Z8QEGIhVQI+EWwt5lT+AuU9SnorVupXFqqOGqGfsyO6w==" - "resolved" "https://registry.npmjs.org/es-abstract/-/es-abstract-1.19.2.tgz" - "version" "1.19.2" - dependencies: - "call-bind" "^1.0.2" - "es-to-primitive" "^1.2.1" - "function-bind" "^1.1.1" - "get-intrinsic" "^1.1.1" - "get-symbol-description" "^1.0.0" - "has" "^1.0.3" - "has-symbols" "^1.0.3" - "internal-slot" "^1.0.3" - "is-callable" "^1.2.4" - "is-negative-zero" "^2.0.2" - "is-regex" "^1.1.4" - "is-shared-array-buffer" "^1.0.1" - "is-string" "^1.0.7" - "is-weakref" "^1.0.2" - "object-inspect" "^1.12.0" - "object-keys" "^1.1.1" - "object.assign" "^4.1.2" - "string.prototype.trimend" "^1.0.4" - "string.prototype.trimstart" "^1.0.4" - "unbox-primitive" "^1.0.1" - -"es-to-primitive@^1.2.1": - "integrity" "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==" - "resolved" "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz" - "version" "1.2.1" - dependencies: - "is-callable" "^1.1.4" - "is-date-object" "^1.0.1" - "is-symbol" "^1.0.2" - -"es6-error@^4.0.1": - "integrity" "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==" - "resolved" "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz" - "version" "4.1.1" - -"es6-object-assign@^1.1.0": - "integrity" "sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw= sha512-MEl9uirslVwqQU369iHNWZXsI8yaZYGg/D65aOgZkeyFJwHYSxilf7rQzXKI7DdDuBPrBXbfk3sl9hJhmd5AUw==" - "resolved" "https://registry.npmjs.org/es6-object-assign/-/es6-object-assign-1.1.0.tgz" - "version" "1.1.0" - -"escalade@^3.1.1": - "integrity" "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" - "resolved" "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz" - "version" "3.1.1" - -"escape-string-regexp@^1.0.5": - "integrity" "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==" - "resolved" "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz" - "version" "1.0.5" - -"escape-string-regexp@^4.0.0", "escape-string-regexp@4.0.0": - "integrity" "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==" - "resolved" "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz" - "version" "4.0.0" - -"eslint-plugin-deprecation@^1.3.2": - "integrity" "sha512-z93wbx9w7H/E3ogPw6AZMkkNJ6m51fTZRNZPNQqxQLmx+KKt7aLkMU9wN67s71i+VVHN4tLOZ3zT3QLbnlC0Mg==" - "resolved" "https://registry.npmjs.org/eslint-plugin-deprecation/-/eslint-plugin-deprecation-1.3.2.tgz" - "version" "1.3.2" - dependencies: - "@typescript-eslint/experimental-utils" "^5.0.0" - "tslib" "^2.3.1" - "tsutils" "^3.21.0" - -"eslint-scope@^5.1.1": - "integrity" "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==" - "resolved" "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz" - "version" "5.1.1" - dependencies: - "esrecurse" "^4.3.0" - "estraverse" "^4.1.1" - -"eslint-scope@^7.1.1": - "integrity" "sha512-QKQM/UXpIiHcLqJ5AOyIW7XZmzjkzQXYE54n1++wb0u9V/abW3l9uQnxX8Z5Xd18xyKIMTUAyQ0k1e8pz6LUrw==" - "resolved" "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.1.1.tgz" - "version" "7.1.1" - dependencies: - "esrecurse" "^4.3.0" - "estraverse" "^5.2.0" - -"eslint-utils@^3.0.0": - "integrity" "sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==" - "resolved" "https://registry.npmjs.org/eslint-utils/-/eslint-utils-3.0.0.tgz" - "version" "3.0.0" - dependencies: - "eslint-visitor-keys" "^2.0.0" - -"eslint-visitor-keys@^2.0.0": - "integrity" "sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==" - "resolved" "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz" - "version" "2.1.0" - -"eslint-visitor-keys@^3.0.0", "eslint-visitor-keys@^3.3.0": - "integrity" "sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA==" - "resolved" "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz" - "version" "3.3.0" - -"eslint@*", "eslint@^6.0.0 || ^7.0.0 || ^8.0.0", "eslint@^8.21.0", "eslint@>=5": - "integrity" "sha512-/XJ1+Qurf1T9G2M5IHrsjp+xrGT73RZf23xA1z5wB1ZzzEAWSZKvRwhWxTFp1rvkvCfwcvAUNAP31bhKTTGfDA==" - "resolved" "https://registry.npmjs.org/eslint/-/eslint-8.21.0.tgz" - "version" "8.21.0" - dependencies: - "@eslint/eslintrc" "^1.3.0" - "@humanwhocodes/config-array" "^0.10.4" - "@humanwhocodes/gitignore-to-minimatch" "^1.0.2" - "ajv" "^6.10.0" - "chalk" "^4.0.0" - "cross-spawn" "^7.0.2" - "debug" "^4.3.2" - "doctrine" "^3.0.0" - "escape-string-regexp" "^4.0.0" - "eslint-scope" "^7.1.1" - "eslint-utils" "^3.0.0" - "eslint-visitor-keys" "^3.3.0" - "espree" "^9.3.3" - "esquery" "^1.4.0" - "esutils" "^2.0.2" - "fast-deep-equal" "^3.1.3" - "file-entry-cache" "^6.0.1" - "find-up" "^5.0.0" - "functional-red-black-tree" "^1.0.1" - "glob-parent" "^6.0.1" - "globals" "^13.15.0" - "globby" "^11.1.0" - "grapheme-splitter" "^1.0.4" - "ignore" "^5.2.0" - "import-fresh" "^3.0.0" - "imurmurhash" "^0.1.4" - "is-glob" "^4.0.0" - "js-yaml" "^4.1.0" - "json-stable-stringify-without-jsonify" "^1.0.1" - "levn" "^0.4.1" - "lodash.merge" "^4.6.2" - "minimatch" "^3.1.2" - "natural-compare" "^1.4.0" - "optionator" "^0.9.1" - "regexpp" "^3.2.0" - "strip-ansi" "^6.0.1" - "strip-json-comments" "^3.1.0" - "text-table" "^0.2.0" - "v8-compile-cache" "^2.0.3" - -"espree@^9.3.2", "espree@^9.3.3": - "integrity" "sha512-ORs1Rt/uQTqUKjDdGCyrtYxbazf5umATSf/K4qxjmZHORR6HJk+2s/2Pqe+Kk49HHINC/xNIrGfgh8sZcll0ng==" - "resolved" "https://registry.npmjs.org/espree/-/espree-9.3.3.tgz" - "version" "9.3.3" - dependencies: - "acorn" "^8.8.0" - "acorn-jsx" "^5.3.2" - "eslint-visitor-keys" "^3.3.0" - -"esprima@^4.0.0": - "integrity" "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" - "resolved" "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz" - "version" "4.0.1" - -"esquery@^1.4.0": - "integrity" "sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w==" - "resolved" "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz" - "version" "1.4.0" - dependencies: - "estraverse" "^5.1.0" - -"esrecurse@^4.3.0": - "integrity" "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==" - "resolved" "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz" - "version" "4.3.0" - dependencies: - "estraverse" "^5.2.0" - -"estraverse@^4.1.1": - "integrity" "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==" - "resolved" "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz" - "version" "4.3.0" - -"estraverse@^5.1.0": - "integrity" "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==" - "resolved" "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz" - "version" "5.3.0" - -"estraverse@^5.2.0": - "integrity" "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==" - "resolved" "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz" - "version" "5.3.0" - -"estree-walker@^1.0.1": - "integrity" "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==" - "resolved" "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz" - "version" "1.0.1" - -"estree-walker@^2.0.1": - "integrity" "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==" - "resolved" "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz" - "version" "2.0.2" - -"esutils@^2.0.2": - "integrity" "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" - "resolved" "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz" - "version" "2.0.3" - -"fast-deep-equal@^3.1.1", "fast-deep-equal@^3.1.3": - "integrity" "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" - "resolved" "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" - "version" "3.1.3" - -"fast-glob@^3.2.9": - "integrity" "sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew==" - "resolved" "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.11.tgz" - "version" "3.2.11" - dependencies: - "@nodelib/fs.stat" "^2.0.2" - "@nodelib/fs.walk" "^1.2.3" - "glob-parent" "^5.1.2" - "merge2" "^1.3.0" - "micromatch" "^4.0.4" - -"fast-json-stable-stringify@^2.0.0": - "integrity" "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" - "resolved" "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz" - "version" "2.1.0" - -"fast-levenshtein@^2.0.6": - "integrity" "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==" - "resolved" "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz" - "version" "2.0.6" - -"fastq@^1.6.0": - "integrity" "sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==" - "resolved" "https://registry.npmjs.org/fastq/-/fastq-1.13.0.tgz" - "version" "1.13.0" - dependencies: - "reusify" "^1.0.4" - -"file-entry-cache@^6.0.1": - "integrity" "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==" - "resolved" "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz" - "version" "6.0.1" - dependencies: - "flat-cache" "^3.0.4" - -"fill-range@^7.0.1": - "integrity" "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==" - "resolved" "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz" - "version" "7.0.1" - dependencies: - "to-regex-range" "^5.0.1" - -"find-cache-dir@^3.2.0", "find-cache-dir@^3.3.2": - "integrity" "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==" - "resolved" "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz" - "version" "3.3.2" - dependencies: - "commondir" "^1.0.1" - "make-dir" "^3.0.2" - "pkg-dir" "^4.1.0" - -"find-up@^4.0.0": - "integrity" "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==" - "resolved" "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz" - "version" "4.1.0" - dependencies: - "locate-path" "^5.0.0" - "path-exists" "^4.0.0" - -"find-up@^4.1.0": - "integrity" "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==" - "resolved" "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz" - "version" "4.1.0" - dependencies: - "locate-path" "^5.0.0" - "path-exists" "^4.0.0" - -"find-up@^5.0.0", "find-up@5.0.0": - "integrity" "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==" - "resolved" "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz" - "version" "5.0.0" - dependencies: - "locate-path" "^6.0.0" - "path-exists" "^4.0.0" - -"flat-cache@^3.0.4": - "integrity" "sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==" - "resolved" "https://registry.npmjs.org/flat-cache/-/flat-cache-3.0.4.tgz" - "version" "3.0.4" - dependencies: - "flatted" "^3.1.0" - "rimraf" "^3.0.2" - -"flat@^5.0.2": - "integrity" "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==" - "resolved" "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz" - "version" "5.0.2" - -"flatted@^3.1.0": - "integrity" "sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==" - "resolved" "https://registry.npmjs.org/flatted/-/flatted-3.2.5.tgz" - "version" "3.2.5" - -"foreach@^2.0.5": - "integrity" "sha1-C+4AUBiusmDQo6865ljdATbsG5k= sha512-ZBbtRiapkZYLsqoPyZOR+uPfto0GRMNQN1GwzZtZt7iZvPPbDDQV0JF5Hx4o/QFQ5c0vyuoZ98T8RSBbopzWtA==" - "resolved" "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz" - "version" "2.0.5" - -"foreground-child@^2.0.0": - "integrity" "sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==" - "resolved" "https://registry.npmjs.org/foreground-child/-/foreground-child-2.0.0.tgz" - "version" "2.0.0" - dependencies: - "cross-spawn" "^7.0.0" - "signal-exit" "^3.0.2" - -"fromentries@^1.2.0": - "integrity" "sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg==" - "resolved" "https://registry.npmjs.org/fromentries/-/fromentries-1.3.2.tgz" - "version" "1.3.2" - -"fs-extra@^10.0.0": - "integrity" "sha512-NbdoVMZso2Lsrn/QwLXOy6rm0ufY2zEOKCDzJR/0kBsb0E6qed0P3iYK+Ath3BfvXEeu4JhEtXLgILx5psUfag==" - "resolved" "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.1.tgz" - "version" "10.0.1" - dependencies: - "graceful-fs" "^4.2.0" - "jsonfile" "^6.0.1" - "universalify" "^2.0.0" - -"fs.realpath@^1.0.0": - "integrity" "sha1-FQStJSMVjKpA20onh8sBQRmU6k8= sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" - "resolved" "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz" - "version" "1.0.0" - -"fsevents@~2.3.2": - "integrity" "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==" - "resolved" "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz" - "version" "2.3.2" - -"function-bind@^1.1.1": - "integrity" "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" - "resolved" "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz" - "version" "1.1.1" - -"functional-red-black-tree@^1.0.1": - "integrity" "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==" - "resolved" "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz" - "version" "1.0.1" - -"gensync@^1.0.0-beta.2": - "integrity" "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==" - "resolved" "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz" - "version" "1.0.0-beta.2" - -"get-caller-file@^2.0.1", "get-caller-file@^2.0.5": - "integrity" "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" - "resolved" "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz" - "version" "2.0.5" - -"get-intrinsic@^1.0.2", "get-intrinsic@^1.1.0", "get-intrinsic@^1.1.1": - "integrity" "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==" - "resolved" "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz" - "version" "1.1.1" - dependencies: - "function-bind" "^1.1.1" - "has" "^1.0.3" - "has-symbols" "^1.0.1" - -"get-package-type@^0.1.0": - "integrity" "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==" - "resolved" "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz" - "version" "0.1.0" - -"get-symbol-description@^1.0.0": - "integrity" "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==" - "resolved" "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz" - "version" "1.0.0" - dependencies: - "call-bind" "^1.0.2" - "get-intrinsic" "^1.1.1" - -"glob-parent@^5.1.2": - "integrity" "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==" - "resolved" "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz" - "version" "5.1.2" - dependencies: - "is-glob" "^4.0.1" - -"glob-parent@^6.0.1": - "integrity" "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==" - "resolved" "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz" - "version" "6.0.2" - dependencies: - "is-glob" "^4.0.3" - -"glob-parent@~5.1.2": - "integrity" "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==" - "resolved" "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz" - "version" "5.1.2" - dependencies: - "is-glob" "^4.0.1" - -"glob@^7.1.3", "glob@^7.1.4", "glob@^7.1.6", "glob@7.2.0": - "integrity" "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==" - "resolved" "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz" - "version" "7.2.0" - dependencies: - "fs.realpath" "^1.0.0" - "inflight" "^1.0.4" - "inherits" "2" - "minimatch" "^3.0.4" - "once" "^1.3.0" - "path-is-absolute" "^1.0.0" - -"globals@^11.1.0": - "integrity" "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==" - "resolved" "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz" - "version" "11.12.0" - -"globals@^13.15.0": - "integrity" "sha512-bpzcOlgDhMG070Av0Vy5Owklpv1I6+j96GhUI7Rh7IzDCKLzboflLrrfqMu8NquDbiR4EOQk7XzJwqVJxicxog==" - "resolved" "https://registry.npmjs.org/globals/-/globals-13.15.0.tgz" - "version" "13.15.0" - dependencies: - "type-fest" "^0.20.2" - -"globby@^11.0.4", "globby@^11.1.0": - "integrity" "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==" - "resolved" "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz" - "version" "11.1.0" - dependencies: - "array-union" "^2.1.0" - "dir-glob" "^3.0.1" - "fast-glob" "^3.2.9" - "ignore" "^5.2.0" - "merge2" "^1.4.1" - "slash" "^3.0.0" - -"graceful-fs@^4.1.15", "graceful-fs@^4.1.6", "graceful-fs@^4.2.0": - "integrity" "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==" - "resolved" "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz" - "version" "4.2.9" - -"grapheme-splitter@^1.0.4": - "integrity" "sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==" - "resolved" "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz" - "version" "1.0.4" - -"has-bigints@^1.0.1": - "integrity" "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==" - "resolved" "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz" - "version" "1.0.1" - -"has-flag@^3.0.0": - "integrity" "sha1-tdRU3CGZriJWmfNGfloH87lVuv0= sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==" - "resolved" "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz" - "version" "3.0.0" - -"has-flag@^4.0.0": - "integrity" "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==" - "resolved" "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz" - "version" "4.0.0" - -"has-symbols@^1.0.1", "has-symbols@^1.0.2", "has-symbols@^1.0.3": - "integrity" "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" - "resolved" "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz" - "version" "1.0.3" - -"has-tostringtag@^1.0.0": - "integrity" "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==" - "resolved" "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz" - "version" "1.0.0" - dependencies: - "has-symbols" "^1.0.2" - -"has@^1.0.3": - "integrity" "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==" - "resolved" "https://registry.npmjs.org/has/-/has-1.0.3.tgz" - "version" "1.0.3" - dependencies: - "function-bind" "^1.1.1" - -"hasha@^5.0.0": - "integrity" "sha512-Hrp5vIK/xr5SkeN2onO32H0MgNZ0f17HRNH39WfL0SYUNOTZ5Lz1TJ8Pajo/87dYGEFlLMm7mIc/k/s6Bvz9HQ==" - "resolved" "https://registry.npmjs.org/hasha/-/hasha-5.2.2.tgz" - "version" "5.2.2" - dependencies: - "is-stream" "^2.0.0" - "type-fest" "^0.8.0" - -"he@1.2.0": - "integrity" "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==" - "resolved" "https://registry.npmjs.org/he/-/he-1.2.0.tgz" - "version" "1.2.0" - -"html-escaper@^2.0.0": - "integrity" "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==" - "resolved" "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz" - "version" "2.0.2" - -"ignore@^5.2.0": - "integrity" "sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ==" - "resolved" "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz" - "version" "5.2.0" - -"import-fresh@^3.0.0", "import-fresh@^3.2.1": - "integrity" "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==" - "resolved" "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz" - "version" "3.3.0" - dependencies: - "parent-module" "^1.0.0" - "resolve-from" "^4.0.0" - -"imurmurhash@^0.1.4": - "integrity" "sha1-khi5srkoojixPcT7a21XbyMUU+o= sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==" - "resolved" "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz" - "version" "0.1.4" - -"indent-string@^4.0.0": - "integrity" "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==" - "resolved" "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz" - "version" "4.0.0" - -"inflight@^1.0.4": - "integrity" "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==" - "resolved" "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz" - "version" "1.0.6" - dependencies: - "once" "^1.3.0" - "wrappy" "1" - -"inherits@^2.0.3", "inherits@2": - "integrity" "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - "resolved" "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz" - "version" "2.0.4" - -"internal-slot@^1.0.3": - "integrity" "sha512-O0DB1JC/sPyZl7cIo78n5dR7eUSwwpYPiXRhTzNxZVAMUuB8vlnRFyLxdrVToks6XPLVnFfbzaVd5WLjhgg+vA==" - "resolved" "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.3.tgz" - "version" "1.0.3" - dependencies: - "get-intrinsic" "^1.1.0" - "has" "^1.0.3" - "side-channel" "^1.0.4" - -"is-arguments@^1.0.4": - "integrity" "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==" - "resolved" "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz" - "version" "1.1.1" - dependencies: - "call-bind" "^1.0.2" - "has-tostringtag" "^1.0.0" - -"is-bigint@^1.0.1": - "integrity" "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==" - "resolved" "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz" - "version" "1.0.4" - dependencies: - "has-bigints" "^1.0.1" - -"is-binary-path@~2.1.0": - "integrity" "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==" - "resolved" "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz" - "version" "2.1.0" - dependencies: - "binary-extensions" "^2.0.0" - -"is-boolean-object@^1.1.0": - "integrity" "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==" - "resolved" "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz" - "version" "1.1.2" - dependencies: - "call-bind" "^1.0.2" - "has-tostringtag" "^1.0.0" - -"is-builtin-module@^3.1.0": - "integrity" "sha512-OV7JjAgOTfAFJmHZLvpSTb4qi0nIILDV1gWPYDnDJUTNFM5aGlRAhk4QcT8i7TuAleeEV5Fdkqn3t4mS+Q11fg==" - "resolved" "https://registry.npmjs.org/is-builtin-module/-/is-builtin-module-3.1.0.tgz" - "version" "3.1.0" - dependencies: - "builtin-modules" "^3.0.0" - -"is-callable@^1.1.4", "is-callable@^1.2.4": - "integrity" "sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w==" - "resolved" "https://registry.npmjs.org/is-callable/-/is-callable-1.2.4.tgz" - "version" "1.2.4" - -"is-core-module@^2.8.1": - "integrity" "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==" - "resolved" "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz" - "version" "2.8.1" - dependencies: - "has" "^1.0.3" - -"is-date-object@^1.0.1": - "integrity" "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==" - "resolved" "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz" - "version" "1.0.5" - dependencies: - "has-tostringtag" "^1.0.0" - -"is-extglob@^2.1.1": - "integrity" "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==" - "resolved" "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz" - "version" "2.1.1" - -"is-fullwidth-code-point@^3.0.0": - "integrity" "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" - "resolved" "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz" - "version" "3.0.0" - -"is-generator-function@^1.0.7": - "integrity" "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==" - "resolved" "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.10.tgz" - "version" "1.0.10" - dependencies: - "has-tostringtag" "^1.0.0" - -"is-glob@^4.0.0", "is-glob@^4.0.1", "is-glob@^4.0.3", "is-glob@~4.0.1": - "integrity" "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==" - "resolved" "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz" - "version" "4.0.3" - dependencies: - "is-extglob" "^2.1.1" - -"is-module@^1.0.0": - "integrity" "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE= sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==" - "resolved" "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz" - "version" "1.0.0" - -"is-nan@^1.2.1": - "integrity" "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==" - "resolved" "https://registry.npmjs.org/is-nan/-/is-nan-1.3.2.tgz" - "version" "1.3.2" - dependencies: - "call-bind" "^1.0.0" - "define-properties" "^1.1.3" - -"is-negative-zero@^2.0.2": - "integrity" "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==" - "resolved" "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz" - "version" "2.0.2" - -"is-number-object@^1.0.4": - "integrity" "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==" - "resolved" "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz" - "version" "1.0.7" - dependencies: - "has-tostringtag" "^1.0.0" - -"is-number@^7.0.0": - "integrity" "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" - "resolved" "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz" - "version" "7.0.0" - -"is-plain-obj@^2.1.0": - "integrity" "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==" - "resolved" "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz" - "version" "2.1.0" - -"is-reference@^1.2.1": - "integrity" "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==" - "resolved" "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz" - "version" "1.2.1" - dependencies: - "@types/estree" "*" - -"is-regex@^1.1.4": - "integrity" "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==" - "resolved" "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz" - "version" "1.1.4" - dependencies: - "call-bind" "^1.0.2" - "has-tostringtag" "^1.0.0" - -"is-shared-array-buffer@^1.0.1": - "integrity" "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==" - "resolved" "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz" - "version" "1.0.2" - dependencies: - "call-bind" "^1.0.2" - -"is-stream@^2.0.0": - "integrity" "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==" - "resolved" "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz" - "version" "2.0.1" - -"is-string@^1.0.5", "is-string@^1.0.7": - "integrity" "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==" - "resolved" "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz" - "version" "1.0.7" - dependencies: - "has-tostringtag" "^1.0.0" - -"is-symbol@^1.0.2", "is-symbol@^1.0.3": - "integrity" "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==" - "resolved" "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz" - "version" "1.0.4" - dependencies: - "has-symbols" "^1.0.2" - -"is-typed-array@^1.1.3", "is-typed-array@^1.1.7": - "integrity" "sha512-HqH41TNZq2fgtGT8WHVFVJhBVGuY3AnP3Q36K8JKXUxSxRgk/d+7NjmwG2vo2mYmXK8UYZKu0qH8bVP5gEisjA==" - "resolved" "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.8.tgz" - "version" "1.1.8" - dependencies: - "available-typed-arrays" "^1.0.5" - "call-bind" "^1.0.2" - "es-abstract" "^1.18.5" - "foreach" "^2.0.5" - "has-tostringtag" "^1.0.0" - -"is-typedarray@^1.0.0": - "integrity" "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo= sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" - "resolved" "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz" - "version" "1.0.0" - -"is-unicode-supported@^0.1.0": - "integrity" "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==" - "resolved" "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz" - "version" "0.1.0" - -"is-weakref@^1.0.2": - "integrity" "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==" - "resolved" "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz" - "version" "1.0.2" - dependencies: - "call-bind" "^1.0.2" - -"is-windows@^1.0.2": - "integrity" "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==" - "resolved" "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz" - "version" "1.0.2" - -"isexe@^2.0.0": - "integrity" "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" - "resolved" "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz" - "version" "2.0.0" - -"istanbul-lib-coverage@^3.0.0", "istanbul-lib-coverage@^3.0.0-alpha.1": - "integrity" "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==" - "resolved" "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz" - "version" "3.2.0" - -"istanbul-lib-hook@^3.0.0": - "integrity" "sha512-Pt/uge1Q9s+5VAZ+pCo16TYMWPBIl+oaNIjgLQxcX0itS6ueeaA+pEfThZpH8WxhFgCiEb8sAJY6MdUKgiIWaQ==" - "resolved" "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-3.0.0.tgz" - "version" "3.0.0" - dependencies: - "append-transform" "^2.0.0" - -"istanbul-lib-instrument@^4.0.0": - "integrity" "sha512-BXgQl9kf4WTCPCCpmFGoJkz/+uhvm7h7PFKUYxh7qarQd3ER33vHG//qaE8eN25l07YqZPpHXU9I09l/RD5aGQ==" - "resolved" "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-4.0.3.tgz" - "version" "4.0.3" - dependencies: - "@babel/core" "^7.7.5" - "@istanbuljs/schema" "^0.1.2" - "istanbul-lib-coverage" "^3.0.0" - "semver" "^6.3.0" - -"istanbul-lib-processinfo@^2.0.2": - "integrity" "sha512-kOwpa7z9hme+IBPZMzQ5vdQj8srYgAtaRqeI48NGmAQ+/5yKiHLV0QbYqQpxsdEF0+w14SoB8YbnHKcXE2KnYw==" - "resolved" "https://registry.npmjs.org/istanbul-lib-processinfo/-/istanbul-lib-processinfo-2.0.2.tgz" - "version" "2.0.2" - dependencies: - "archy" "^1.0.0" - "cross-spawn" "^7.0.0" - "istanbul-lib-coverage" "^3.0.0-alpha.1" - "make-dir" "^3.0.0" - "p-map" "^3.0.0" - "rimraf" "^3.0.0" - "uuid" "^3.3.3" - -"istanbul-lib-report@^3.0.0": - "integrity" "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==" - "resolved" "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz" - "version" "3.0.0" - dependencies: - "istanbul-lib-coverage" "^3.0.0" - "make-dir" "^3.0.0" - "supports-color" "^7.1.0" - -"istanbul-lib-source-maps@^4.0.0": - "integrity" "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==" - "resolved" "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz" - "version" "4.0.1" - dependencies: - "debug" "^4.1.1" - "istanbul-lib-coverage" "^3.0.0" - "source-map" "^0.6.1" - -"istanbul-reports@^3.0.2": - "integrity" "sha512-r1/DshN4KSE7xWEknZLLLLDn5CJybV3nw01VTkp6D5jzLuELlcbudfj/eSQFvrKsJuTVCGnePO7ho82Nw9zzfw==" - "resolved" "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.4.tgz" - "version" "3.1.4" - dependencies: - "html-escaper" "^2.0.0" - "istanbul-lib-report" "^3.0.0" - -"js-tokens@^4.0.0": - "integrity" "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" - "resolved" "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz" - "version" "4.0.0" - -"js-yaml@^3.13.1": - "integrity" "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==" - "resolved" "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz" - "version" "3.14.1" - dependencies: - "argparse" "^1.0.7" - "esprima" "^4.0.0" - -"js-yaml@^4.1.0", "js-yaml@4.1.0": - "integrity" "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==" - "resolved" "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz" - "version" "4.1.0" - dependencies: - "argparse" "^2.0.1" - -"jsesc@^2.5.1": - "integrity" "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==" - "resolved" "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz" - "version" "2.5.2" - -"json-schema-traverse@^0.4.1": - "integrity" "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" - "resolved" "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz" - "version" "0.4.1" - -"json-stable-stringify-without-jsonify@^1.0.1": - "integrity" "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==" - "resolved" "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz" - "version" "1.0.1" - -"json5@^2.1.2": - "integrity" "sha512-f+8cldu7X/y7RAJurMEJmdoKXGB/X550w2Nr3tTbezL6RwEE/iMcm+tZnXeoZtKuOq6ft8+CqzEkrIgx1fPoQA==" - "resolved" "https://registry.npmjs.org/json5/-/json5-2.2.0.tgz" - "version" "2.2.0" - dependencies: - "minimist" "^1.2.5" - -"jsonc-parser@^3.0.0": - "integrity" "sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA==" - "resolved" "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.0.0.tgz" - "version" "3.0.0" - -"jsonfile@^6.0.1": - "integrity" "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==" - "resolved" "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz" - "version" "6.1.0" - dependencies: - "universalify" "^2.0.0" - optionalDependencies: - "graceful-fs" "^4.1.6" - -"levn@^0.4.1": - "integrity" "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==" - "resolved" "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz" - "version" "0.4.1" - dependencies: - "prelude-ls" "^1.2.1" - "type-check" "~0.4.0" - -"locate-path@^5.0.0": - "integrity" "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==" - "resolved" "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz" - "version" "5.0.0" - dependencies: - "p-locate" "^4.1.0" - -"locate-path@^6.0.0": - "integrity" "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==" - "resolved" "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz" - "version" "6.0.0" - dependencies: - "p-locate" "^5.0.0" - -"lodash.flattendeep@^4.4.0": - "integrity" "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI= sha512-uHaJFihxmJcEX3kT4I23ABqKKalJ/zDrDg0lsFtc1h+3uw49SIJ5beyhx5ExVRti3AvKoOJngIj7xz3oylPdWQ==" - "resolved" "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz" - "version" "4.4.0" - -"lodash.merge@^4.6.2": - "integrity" "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==" - "resolved" "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz" - "version" "4.6.2" - -"log-symbols@4.1.0": - "integrity" "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==" - "resolved" "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz" - "version" "4.1.0" - dependencies: - "chalk" "^4.1.0" - "is-unicode-supported" "^0.1.0" - -"lru-cache@^6.0.0": - "integrity" "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==" - "resolved" "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz" - "version" "6.0.0" - dependencies: - "yallist" "^4.0.0" - -"lunr@^2.3.9": - "integrity" "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==" - "resolved" "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz" - "version" "2.3.9" - -"magic-string@^0.25.7": - "integrity" "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==" - "resolved" "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz" - "version" "0.25.9" - dependencies: - "sourcemap-codec" "^1.4.8" - -"magic-string@^0.26.1": - "integrity" "sha512-ndThHmvgtieXe8J/VGPjG+Apu7v7ItcD5mhEIvOscWjPF/ccOiLxHaSuCAS2G+3x4GKsAbT8u7zdyamupui8Tg==" - "resolved" "https://registry.npmjs.org/magic-string/-/magic-string-0.26.1.tgz" - "version" "0.26.1" - dependencies: - "sourcemap-codec" "^1.4.8" - -"make-dir@^3.0.0", "make-dir@^3.0.2": - "integrity" "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==" - "resolved" "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz" - "version" "3.1.0" - dependencies: - "semver" "^6.0.0" - -"make-error@^1.1.1": - "integrity" "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" - "resolved" "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz" - "version" "1.3.6" - -"marked@^4.0.18": - "integrity" "sha512-wbLDJ7Zh0sqA0Vdg6aqlbT+yPxqLblpAZh1mK2+AO2twQkPywvvqQNfEPVwSSRjZ7dZcdeVBIAgiO7MMp3Dszw==" - "resolved" "https://registry.npmjs.org/marked/-/marked-4.0.18.tgz" - "version" "4.0.18" - -"merge2@^1.3.0", "merge2@^1.4.1": - "integrity" "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==" - "resolved" "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz" - "version" "1.4.1" - -"micromatch@^4.0.4": - "integrity" "sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==" - "resolved" "https://registry.npmjs.org/micromatch/-/micromatch-4.0.4.tgz" - "version" "4.0.4" - dependencies: - "braces" "^3.0.1" - "picomatch" "^2.2.3" - -"minimatch@^3.0.4", "minimatch@^3.1.2": - "integrity" "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==" - "resolved" "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz" - "version" "3.1.2" - dependencies: - "brace-expansion" "^1.1.7" - -"minimatch@^5.1.0": - "integrity" "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==" - "resolved" "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz" - "version" "5.1.0" - dependencies: - "brace-expansion" "^2.0.1" - -"minimatch@5.0.1": - "integrity" "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==" - "resolved" "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz" - "version" "5.0.1" - dependencies: - "brace-expansion" "^2.0.1" - -"minimist@^1.2.5": - "integrity" "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" - "resolved" "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz" - "version" "1.2.6" - -"mocha@^10.0.0": - "integrity" "sha512-0Wl+elVUD43Y0BqPZBzZt8Tnkw9CMUdNYnUsTfOM1vuhJVZL+kiesFYsqwBkEEuEixaiPe5ZQdqDgX2jddhmoA==" - "resolved" "https://registry.npmjs.org/mocha/-/mocha-10.0.0.tgz" - "version" "10.0.0" - dependencies: - "@ungap/promise-all-settled" "1.1.2" - "ansi-colors" "4.1.1" - "browser-stdout" "1.3.1" - "chokidar" "3.5.3" - "debug" "4.3.4" - "diff" "5.0.0" - "escape-string-regexp" "4.0.0" - "find-up" "5.0.0" - "glob" "7.2.0" - "he" "1.2.0" - "js-yaml" "4.1.0" - "log-symbols" "4.1.0" - "minimatch" "5.0.1" - "ms" "2.1.3" - "nanoid" "3.3.3" - "serialize-javascript" "6.0.0" - "strip-json-comments" "3.1.1" - "supports-color" "8.1.1" - "workerpool" "6.2.1" - "yargs" "16.2.0" - "yargs-parser" "20.2.4" - "yargs-unparser" "2.0.0" - -"ms@2.1.2": - "integrity" "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - "resolved" "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz" - "version" "2.1.2" - -"ms@2.1.3": - "integrity" "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" - "resolved" "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz" - "version" "2.1.3" - -"nanoid@3.3.3": - "integrity" "sha512-p1sjXuopFs0xg+fPASzQ28agW1oHD7xDsd9Xkf3T15H3c/cifrFHVwrh74PdoklAPi+i7MdRsE47vm2r6JoB+w==" - "resolved" "https://registry.npmjs.org/nanoid/-/nanoid-3.3.3.tgz" - "version" "3.3.3" - -"natural-compare@^1.4.0": - "integrity" "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==" - "resolved" "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz" - "version" "1.4.0" - -"node-preload@^0.2.1": - "integrity" "sha512-RM5oyBy45cLEoHqCeh+MNuFAxO0vTFBLskvQbOKnEE7YTTSN4tbN8QWDIPQ6L+WvKsB/qLEGpYe2ZZ9d4W9OIQ==" - "resolved" "https://registry.npmjs.org/node-preload/-/node-preload-0.2.1.tgz" - "version" "0.2.1" - dependencies: - "process-on-spawn" "^1.0.0" - -"node-releases@^2.0.2": - "integrity" "sha512-XxYDdcQ6eKqp/YjI+tb2C5WM2LgjnZrfYg4vgQt49EK268b6gYCHsBLrK2qvJo4FmCtqmKezb0WZFK4fkrZNsg==" - "resolved" "https://registry.npmjs.org/node-releases/-/node-releases-2.0.2.tgz" - "version" "2.0.2" - -"normalize-path@^3.0.0", "normalize-path@~3.0.0": - "integrity" "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" - "resolved" "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz" - "version" "3.0.0" - -"nyc@^15.1.0": - "integrity" "sha512-jMW04n9SxKdKi1ZMGhvUTHBN0EICCRkHemEoE5jm6mTYcqcdas0ATzgUgejlQUHMvpnOZqGB5Xxsv9KxJW1j8A==" - "resolved" "https://registry.npmjs.org/nyc/-/nyc-15.1.0.tgz" - "version" "15.1.0" - dependencies: - "@istanbuljs/load-nyc-config" "^1.0.0" - "@istanbuljs/schema" "^0.1.2" - "caching-transform" "^4.0.0" - "convert-source-map" "^1.7.0" - "decamelize" "^1.2.0" - "find-cache-dir" "^3.2.0" - "find-up" "^4.1.0" - "foreground-child" "^2.0.0" - "get-package-type" "^0.1.0" - "glob" "^7.1.6" - "istanbul-lib-coverage" "^3.0.0" - "istanbul-lib-hook" "^3.0.0" - "istanbul-lib-instrument" "^4.0.0" - "istanbul-lib-processinfo" "^2.0.2" - "istanbul-lib-report" "^3.0.0" - "istanbul-lib-source-maps" "^4.0.0" - "istanbul-reports" "^3.0.2" - "make-dir" "^3.0.0" - "node-preload" "^0.2.1" - "p-map" "^3.0.0" - "process-on-spawn" "^1.0.0" - "resolve-from" "^5.0.0" - "rimraf" "^3.0.0" - "signal-exit" "^3.0.2" - "spawn-wrap" "^2.0.0" - "test-exclude" "^6.0.0" - "yargs" "^15.0.2" - -"object-inspect@^1.12.0", "object-inspect@^1.9.0": - "integrity" "sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==" - "resolved" "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.0.tgz" - "version" "1.12.0" - -"object-is@^1.0.1": - "integrity" "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==" - "resolved" "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz" - "version" "1.1.5" - dependencies: - "call-bind" "^1.0.2" - "define-properties" "^1.1.3" - -"object-keys@^1.0.12", "object-keys@^1.1.1": - "integrity" "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" - "resolved" "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz" - "version" "1.1.1" - -"object.assign@^4.1.2": - "integrity" "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==" - "resolved" "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz" - "version" "4.1.2" - dependencies: - "call-bind" "^1.0.0" - "define-properties" "^1.1.3" - "has-symbols" "^1.0.1" - "object-keys" "^1.1.1" - -"once@^1.3.0": - "integrity" "sha1-WDsap3WWHUsROsF9nFC6753Xa9E= sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==" - "resolved" "https://registry.npmjs.org/once/-/once-1.4.0.tgz" - "version" "1.4.0" - dependencies: - "wrappy" "1" - -"optionator@^0.9.1": - "integrity" "sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw==" - "resolved" "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz" - "version" "0.9.1" - dependencies: - "deep-is" "^0.1.3" - "fast-levenshtein" "^2.0.6" - "levn" "^0.4.1" - "prelude-ls" "^1.2.1" - "type-check" "^0.4.0" - "word-wrap" "^1.2.3" - -"p-limit@^2.2.0": - "integrity" "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==" - "resolved" "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz" - "version" "2.3.0" - dependencies: - "p-try" "^2.0.0" - -"p-limit@^3.0.2": - "integrity" "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==" - "resolved" "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz" - "version" "3.1.0" - dependencies: - "yocto-queue" "^0.1.0" - -"p-locate@^4.1.0": - "integrity" "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==" - "resolved" "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz" - "version" "4.1.0" - dependencies: - "p-limit" "^2.2.0" - -"p-locate@^5.0.0": - "integrity" "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==" - "resolved" "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz" - "version" "5.0.0" - dependencies: - "p-limit" "^3.0.2" - -"p-map@^3.0.0": - "integrity" "sha512-d3qXVTF/s+W+CdJ5A29wywV2n8CQQYahlgz2bFiA+4eVNJbHJodPZ+/gXwPGh0bOqA+j8S+6+ckmvLGPk1QpxQ==" - "resolved" "https://registry.npmjs.org/p-map/-/p-map-3.0.0.tgz" - "version" "3.0.0" - dependencies: - "aggregate-error" "^3.0.0" - -"p-try@^2.0.0": - "integrity" "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" - "resolved" "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz" - "version" "2.2.0" - -"package-hash@^4.0.0": - "integrity" "sha512-whdkPIooSu/bASggZ96BWVvZTRMOFxnyUG5PnTSGKoJE2gd5mbVNmR2Nj20QFzxYYgAXpoqC+AiXzl+UMRh7zQ==" - "resolved" "https://registry.npmjs.org/package-hash/-/package-hash-4.0.0.tgz" - "version" "4.0.0" - dependencies: - "graceful-fs" "^4.1.15" - "hasha" "^5.0.0" - "lodash.flattendeep" "^4.4.0" - "release-zalgo" "^1.0.0" - -"parent-module@^1.0.0": - "integrity" "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==" - "resolved" "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz" - "version" "1.0.1" - dependencies: - "callsites" "^3.0.0" - -"path-exists@^4.0.0": - "integrity" "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==" - "resolved" "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz" - "version" "4.0.0" - -"path-is-absolute@^1.0.0": - "integrity" "sha1-F0uSaHNVNP+8es5r9TpanhtcX18= sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==" - "resolved" "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz" - "version" "1.0.1" - -"path-key@^3.1.0": - "integrity" "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" - "resolved" "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz" - "version" "3.1.1" - -"path-parse@^1.0.7": - "integrity" "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" - "resolved" "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz" - "version" "1.0.7" - -"path-type@^4.0.0": - "integrity" "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" - "resolved" "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz" - "version" "4.0.0" - -"picocolors@^1.0.0": - "integrity" "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" - "resolved" "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz" - "version" "1.0.0" - -"picomatch@^2.0.4", "picomatch@^2.2.1", "picomatch@^2.2.2", "picomatch@^2.2.3": - "integrity" "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==" - "resolved" "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz" - "version" "2.3.1" - -"pkg-dir@^4.1.0": - "integrity" "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==" - "resolved" "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz" - "version" "4.2.0" - dependencies: - "find-up" "^4.0.0" - -"prelude-ls@^1.2.1": - "integrity" "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==" - "resolved" "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz" - "version" "1.2.1" - -"process-on-spawn@^1.0.0": - "integrity" "sha512-1WsPDsUSMmZH5LeMLegqkPDrsGgsWwk1Exipy2hvB0o/F0ASzbpIctSCcZIK1ykJvtTJULEH+20WOFjMvGnCTg==" - "resolved" "https://registry.npmjs.org/process-on-spawn/-/process-on-spawn-1.0.0.tgz" - "version" "1.0.0" - dependencies: - "fromentries" "^1.2.0" - -"punycode@^2.1.0": - "integrity" "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==" - "resolved" "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz" - "version" "2.1.1" - -"punycode@1.4.1": - "integrity" "sha1-wNWmOycYgArY4esPpSachN1BhF4= sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==" - "resolved" "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz" - "version" "1.4.1" - -"pvtsutils@^1.3.2": - "integrity" "sha512-+Ipe2iNUyrZz+8K/2IOo+kKikdtfhRKzNpQbruF2URmqPtoqAs8g3xS7TJvFF2GcPXjh7DkqMnpVveRFq4PgEQ==" - "resolved" "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.2.tgz" - "version" "1.3.2" - dependencies: - "tslib" "^2.4.0" - -"pvutils@^1.1.3": - "integrity" "sha512-pMpnA0qRdFp32b1sJl1wOJNxZLQ2cbQx+k6tjNtZ8CpvVhNqEPRgivZ2WOUev2YMajecdH7ctUPDvEe87nariQ==" - "resolved" "https://registry.npmjs.org/pvutils/-/pvutils-1.1.3.tgz" - "version" "1.1.3" - -"queue-microtask@^1.2.2": - "integrity" "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==" - "resolved" "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz" - "version" "1.2.3" - -"ramda@^0.25.0": - "integrity" "sha512-GXpfrYVPwx3K7RQ6aYT8KPS8XViSXUVJT1ONhoKPE9VAleW42YE+U+8VEyGWt41EnEQW7gwecYJriTI0pKoecQ==" - "resolved" "https://registry.npmjs.org/ramda/-/ramda-0.25.0.tgz" - "version" "0.25.0" - -"ramda@^0.26.1": - "integrity" "sha512-hLWjpy7EnsDBb0p+Z3B7rPi3GDeRG5ZtiI33kJhTt+ORCd38AbAIjB/9zRIUoeTbE/AVX5ZkU7m6bznsvrf8eQ==" - "resolved" "https://registry.npmjs.org/ramda/-/ramda-0.26.1.tgz" - "version" "0.26.1" - -"randombytes@^2.1.0": - "integrity" "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==" - "resolved" "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz" - "version" "2.1.0" - dependencies: - "safe-buffer" "^5.1.0" - -"readdirp@~3.6.0": - "integrity" "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==" - "resolved" "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz" - "version" "3.6.0" - dependencies: - "picomatch" "^2.2.1" - -"regexpp@^3.2.0": - "integrity" "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==" - "resolved" "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz" - "version" "3.2.0" - -"release-zalgo@^1.0.0": - "integrity" "sha1-CXALflB0Mpc5Mw5TXFqQ+2eFFzA= sha512-gUAyHVHPPC5wdqX/LG4LWtRYtgjxyX78oanFNTMMyFEfOqdC54s3eE82imuWKbOeqYht2CrNf64Qb8vgmmtZGA==" - "resolved" "https://registry.npmjs.org/release-zalgo/-/release-zalgo-1.0.0.tgz" - "version" "1.0.0" - dependencies: - "es6-error" "^4.0.1" - -"require-directory@^2.1.1": - "integrity" "sha1-jGStX9MNqxyXbiNE/+f3kqam30I= sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" - "resolved" "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz" - "version" "2.1.1" - -"require-main-filename@^2.0.0": - "integrity" "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" - "resolved" "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz" - "version" "2.0.0" - -"resolve-from@^4.0.0": - "integrity" "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==" - "resolved" "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz" - "version" "4.0.0" - -"resolve-from@^5.0.0": - "integrity" "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==" - "resolved" "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz" - "version" "5.0.0" - -"resolve@^1.17.0", "resolve@^1.19.0", "resolve@^1.20.0": - "integrity" "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==" - "resolved" "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz" - "version" "1.22.0" - dependencies: - "is-core-module" "^2.8.1" - "path-parse" "^1.0.7" - "supports-preserve-symlinks-flag" "^1.0.0" - -"reusify@^1.0.4": - "integrity" "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==" - "resolved" "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz" - "version" "1.0.4" - -"rimraf@^3.0.0", "rimraf@^3.0.2": - "integrity" "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==" - "resolved" "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz" - "version" "3.0.2" - dependencies: - "glob" "^7.1.3" - -"rollup-plugin-dts@^4.2.2": - "integrity" "sha512-A3g6Rogyko/PXeKoUlkjxkP++8UDVpgA7C+Tdl77Xj4fgEaIjPSnxRmR53EzvoYy97VMVwLAOcWJudaVAuxneQ==" - "resolved" "https://registry.npmjs.org/rollup-plugin-dts/-/rollup-plugin-dts-4.2.2.tgz" - "version" "4.2.2" - dependencies: - "magic-string" "^0.26.1" - optionalDependencies: - "@babel/code-frame" "^7.16.7" - -"rollup-plugin-typescript2@^0.32.1": - "integrity" "sha512-RanO8bp1WbeMv0bVlgcbsFNCn+Y3rX7wF97SQLDxf0fMLsg0B/QFF005t4AsGUcDgF3aKJHoqt4JF2xVaABeKw==" - "resolved" "https://registry.npmjs.org/rollup-plugin-typescript2/-/rollup-plugin-typescript2-0.32.1.tgz" - "version" "0.32.1" - dependencies: - "@rollup/pluginutils" "^4.1.2" - "find-cache-dir" "^3.3.2" - "fs-extra" "^10.0.0" - "resolve" "^1.20.0" - "tslib" "^2.4.0" - -"rollup@^1.20.0||^2.0.0", "rollup@^2.42.0", "rollup@^2.55", "rollup@^2.68.0", "rollup@^2.77.2", "rollup@>=1.26.3": - "integrity" "sha512-m/4YzYgLcpMQbxX3NmAqDvwLATZzxt8bIegO78FZLl+lAgKJBd1DRAOeEiZcKOIOPjxE6ewHWHNgGEalFXuz1g==" - "resolved" "https://registry.npmjs.org/rollup/-/rollup-2.77.2.tgz" - "version" "2.77.2" - optionalDependencies: - "fsevents" "~2.3.2" - -"run-parallel@^1.1.9": - "integrity" "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==" - "resolved" "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz" - "version" "1.2.0" - dependencies: - "queue-microtask" "^1.2.2" - -"safe-buffer@^5.1.0", "safe-buffer@^5.1.2", "safe-buffer@~5.1.1": - "integrity" "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" - "resolved" "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz" - "version" "5.1.2" - -"semver@^6.0.0": - "integrity" "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==" - "resolved" "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz" - "version" "6.3.0" - -"semver@^6.3.0": - "integrity" "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==" - "resolved" "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz" - "version" "6.3.0" - -"semver@^7.3.5", "semver@^7.3.7": - "integrity" "sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==" - "resolved" "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz" - "version" "7.3.7" - dependencies: - "lru-cache" "^6.0.0" - -"serialize-javascript@6.0.0": - "integrity" "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==" - "resolved" "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz" - "version" "6.0.0" - dependencies: - "randombytes" "^2.1.0" - -"set-blocking@^2.0.0": - "integrity" "sha1-BF+XgtARrppoA93TgrJDkrPYkPc= sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" - "resolved" "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz" - "version" "2.0.0" - -"shebang-command@^2.0.0": - "integrity" "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==" - "resolved" "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz" - "version" "2.0.0" - dependencies: - "shebang-regex" "^3.0.0" - -"shebang-regex@^3.0.0": - "integrity" "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" - "resolved" "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz" - "version" "3.0.0" - -"shiki@^0.10.1": - "integrity" "sha512-VsY7QJVzU51j5o1+DguUd+6vmCmZ5v/6gYu4vyYAhzjuNQU6P/vmSy4uQaOhvje031qQMiW0d2BwgMH52vqMng==" - "resolved" "https://registry.npmjs.org/shiki/-/shiki-0.10.1.tgz" - "version" "0.10.1" - dependencies: - "jsonc-parser" "^3.0.0" - "vscode-oniguruma" "^1.6.1" - "vscode-textmate" "5.2.0" - -"side-channel@^1.0.4": - "integrity" "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==" - "resolved" "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz" - "version" "1.0.4" - dependencies: - "call-bind" "^1.0.0" - "get-intrinsic" "^1.0.2" - "object-inspect" "^1.9.0" - -"signal-exit@^3.0.2": - "integrity" "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" - "resolved" "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz" - "version" "3.0.7" - -"slash@^3.0.0": - "integrity" "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==" - "resolved" "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz" - "version" "3.0.0" - -"source-map@^0.5.0": - "integrity" "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==" - "resolved" "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz" - "version" "0.5.7" - -"source-map@^0.6.1": - "integrity" "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" - "resolved" "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz" - "version" "0.6.1" - -"sourcemap-codec@^1.4.8": - "integrity" "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==" - "resolved" "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz" - "version" "1.4.8" - -"spawn-wrap@^2.0.0": - "integrity" "sha512-EeajNjfN9zMnULLwhZZQU3GWBoFNkbngTUPfaawT4RkMiviTxcX0qfhVbGey39mfctfDHkWtuecgQ8NJcyQWHg==" - "resolved" "https://registry.npmjs.org/spawn-wrap/-/spawn-wrap-2.0.0.tgz" - "version" "2.0.0" - dependencies: - "foreground-child" "^2.0.0" - "is-windows" "^1.0.2" - "make-dir" "^3.0.0" - "rimraf" "^3.0.0" - "signal-exit" "^3.0.2" - "which" "^2.0.1" - -"sprintf-js@~1.0.2": - "integrity" "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==" - "resolved" "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz" - "version" "1.0.3" - -"string-width@^4.1.0", "string-width@^4.2.0": - "integrity" "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==" - "resolved" "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz" - "version" "4.2.3" - dependencies: - "emoji-regex" "^8.0.0" - "is-fullwidth-code-point" "^3.0.0" - "strip-ansi" "^6.0.1" - -"string.prototype.trimend@^1.0.4": - "integrity" "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==" - "resolved" "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz" - "version" "1.0.4" - dependencies: - "call-bind" "^1.0.2" - "define-properties" "^1.1.3" - -"string.prototype.trimstart@^1.0.4": - "integrity" "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==" - "resolved" "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz" - "version" "1.0.4" - dependencies: - "call-bind" "^1.0.2" - "define-properties" "^1.1.3" - -"strip-ansi@^6.0.0", "strip-ansi@^6.0.1": - "integrity" "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==" - "resolved" "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz" - "version" "6.0.1" - dependencies: - "ansi-regex" "^5.0.1" - -"strip-bom@^4.0.0": - "integrity" "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==" - "resolved" "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz" - "version" "4.0.0" - -"strip-json-comments@^3.1.0", "strip-json-comments@^3.1.1", "strip-json-comments@3.1.1": - "integrity" "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==" - "resolved" "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz" - "version" "3.1.1" - -"supports-color@^5.3.0": - "integrity" "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==" - "resolved" "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz" - "version" "5.5.0" - dependencies: - "has-flag" "^3.0.0" - -"supports-color@^7.1.0": - "integrity" "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==" - "resolved" "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz" - "version" "7.2.0" - dependencies: - "has-flag" "^4.0.0" - -"supports-color@8.1.1": - "integrity" "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==" - "resolved" "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz" - "version" "8.1.1" - dependencies: - "has-flag" "^4.0.0" - -"supports-preserve-symlinks-flag@^1.0.0": - "integrity" "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" - "resolved" "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz" - "version" "1.0.0" - -"test-exclude@^6.0.0": - "integrity" "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==" - "resolved" "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz" - "version" "6.0.0" - dependencies: - "@istanbuljs/schema" "^0.1.2" - "glob" "^7.1.4" - "minimatch" "^3.0.4" - -"text-encoding@^0.7.0": - "integrity" "sha512-oJQ3f1hrOnbRLOcwKz0Liq2IcrvDeZRHXhd9RgLrsT+DjWY/nty1Hi7v3dtkaEYbPYe0mUoOfzRrMwfXXwgPUA==" - "resolved" "https://registry.npmjs.org/text-encoding/-/text-encoding-0.7.0.tgz" - "version" "0.7.0" - -"text-table@^0.2.0": - "integrity" "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==" - "resolved" "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz" - "version" "0.2.0" - -"to-fast-properties@^2.0.0": - "integrity" "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4= sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==" - "resolved" "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz" - "version" "2.0.0" - -"to-regex-range@^5.0.1": - "integrity" "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==" - "resolved" "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz" - "version" "5.0.1" - dependencies: - "is-number" "^7.0.0" - -"ts-node@^10.9.1": - "integrity" "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==" - "resolved" "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz" - "version" "10.9.1" - dependencies: - "@cspotcode/source-map-support" "^0.8.0" - "@tsconfig/node10" "^1.0.7" - "@tsconfig/node12" "^1.0.7" - "@tsconfig/node14" "^1.0.0" - "@tsconfig/node16" "^1.0.2" - "acorn" "^8.4.1" - "acorn-walk" "^8.1.1" - "arg" "^4.1.0" - "create-require" "^1.1.0" - "diff" "^4.0.1" - "make-error" "^1.1.1" - "v8-compile-cache-lib" "^3.0.1" - "yn" "3.1.1" - -"tslib@^1.8.1": - "integrity" "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==" - "resolved" "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz" - "version" "1.14.1" - -"tslib@^2.0.0", "tslib@^2.3.1", "tslib@^2.4.0": - "integrity" "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" - "resolved" "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz" - "version" "2.4.0" - -"tsutils@^3.21.0": - "integrity" "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==" - "resolved" "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz" - "version" "3.21.0" - dependencies: - "tslib" "^1.8.1" - -"type-check@^0.4.0", "type-check@~0.4.0": - "integrity" "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==" - "resolved" "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz" - "version" "0.4.0" - dependencies: - "prelude-ls" "^1.2.1" - -"type-fest@^0.20.2": - "integrity" "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==" - "resolved" "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz" - "version" "0.20.2" - -"type-fest@^0.8.0": - "integrity" "sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==" - "resolved" "https://registry.npmjs.org/type-fest/-/type-fest-0.8.1.tgz" - "version" "0.8.1" - -"typedarray-to-buffer@^3.1.5": - "integrity" "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==" - "resolved" "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz" - "version" "3.1.5" - dependencies: - "is-typedarray" "^1.0.0" - -"typedoc@^0.23.10": - "integrity" "sha512-03EUiu/ZuScUBMnY6p0lY+HTH8SwhzvRE3gImoemdPDWXPXlks83UGTx++lyquWeB1MTwm9D9Ca8RIjkK3AFfQ==" - "resolved" "https://registry.npmjs.org/typedoc/-/typedoc-0.23.10.tgz" - "version" "0.23.10" - dependencies: - "lunr" "^2.3.9" - "marked" "^4.0.18" - "minimatch" "^5.1.0" - "shiki" "^0.10.1" - -"typescript@^3.7.5 || ^4.0.0", "typescript@^4.1", "typescript@^4.7.4", "typescript@>=2.4.0", "typescript@>=2.7", "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta", "typescript@4.6.x || 4.7.x": - "integrity" "sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==" - "resolved" "https://registry.npmjs.org/typescript/-/typescript-4.7.4.tgz" - "version" "4.7.4" - -"unbox-primitive@^1.0.1": - "integrity" "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==" - "resolved" "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz" - "version" "1.0.1" - dependencies: - "function-bind" "^1.1.1" - "has-bigints" "^1.0.1" - "has-symbols" "^1.0.2" - "which-boxed-primitive" "^1.0.2" - -"universalify@^2.0.0": - "integrity" "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" - "resolved" "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz" - "version" "2.0.0" - -"uri-js@^4.2.2": - "integrity" "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==" - "resolved" "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz" - "version" "4.4.1" - dependencies: - "punycode" "^2.1.0" - -"util@^0.12.0": - "integrity" "sha512-bxZ9qtSlGUWSOy9Qa9Xgk11kSslpuZwaxCg4sNIDj6FLucDab2JxnHwyNTCpHMtK1MjoQiWQ6DiUMZYbSrO+Sw==" - "resolved" "https://registry.npmjs.org/util/-/util-0.12.4.tgz" - "version" "0.12.4" - dependencies: - "inherits" "^2.0.3" - "is-arguments" "^1.0.4" - "is-generator-function" "^1.0.7" - "is-typed-array" "^1.1.3" - "safe-buffer" "^5.1.2" - "which-typed-array" "^1.1.2" - -"uuid@^3.3.3": - "integrity" "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" - "resolved" "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz" - "version" "3.4.0" - -"v8-compile-cache-lib@^3.0.1": - "integrity" "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==" - "resolved" "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz" - "version" "3.0.1" - -"v8-compile-cache@^2.0.3": - "integrity" "sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==" - "resolved" "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz" - "version" "2.3.0" - -"vscode-oniguruma@^1.6.1": - "integrity" "sha512-KH8+KKov5eS/9WhofZR8M8dMHWN2gTxjMsG4jd04YhpbPR91fUj7rYQ2/XjeHCJWbg7X++ApRIU9NUwM2vTvLA==" - "resolved" "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-1.6.2.tgz" - "version" "1.6.2" - -"vscode-textmate@5.2.0": - "integrity" "sha512-Uw5ooOQxRASHgu6C7GVvUxisKXfSgW4oFlO+aa+PAkgmH89O3CXxEEzNRNtHSqtXFTl0nAC1uYj0GMSH27uwtQ==" - "resolved" "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-5.2.0.tgz" - "version" "5.2.0" - -"webcrypto-core@^1.7.4": - "integrity" "sha512-gaExY2/3EHQlRNNNVSrbG2Cg94Rutl7fAaKILS1w8ZDhGxdFOaw6EbCfHIxPy9vt/xwp5o0VQAx9aySPF6hU1A==" - "resolved" "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.7.5.tgz" - "version" "1.7.5" - dependencies: - "@peculiar/asn1-schema" "^2.1.6" - "@peculiar/json-schema" "^1.1.12" - "asn1js" "^3.0.1" - "pvtsutils" "^1.3.2" - "tslib" "^2.4.0" - -"which-boxed-primitive@^1.0.2": - "integrity" "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==" - "resolved" "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz" - "version" "1.0.2" - dependencies: - "is-bigint" "^1.0.1" - "is-boolean-object" "^1.1.0" - "is-number-object" "^1.0.4" - "is-string" "^1.0.5" - "is-symbol" "^1.0.3" - -"which-module@^2.0.0": - "integrity" "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= sha512-B+enWhmw6cjfVC7kS8Pj9pCrKSc5txArRyaYGe088shv/FGWH+0Rjx/xPgtsWfsUtS27FkP697E4DDhgrgoc0Q==" - "resolved" "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz" - "version" "2.0.0" - -"which-typed-array@^1.1.2": - "integrity" "sha512-vjxaB4nfDqwKI0ws7wZpxIlde1XrLX5uB0ZjpfshgmapJMD7jJWhZI+yToJTqaFByF0eNBcYxbjmCzoRP7CfEw==" - "resolved" "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.7.tgz" - "version" "1.1.7" - dependencies: - "available-typed-arrays" "^1.0.5" - "call-bind" "^1.0.2" - "es-abstract" "^1.18.5" - "foreach" "^2.0.5" - "has-tostringtag" "^1.0.0" - "is-typed-array" "^1.1.7" - -"which@^2.0.1": - "integrity" "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==" - "resolved" "https://registry.npmjs.org/which/-/which-2.0.2.tgz" - "version" "2.0.2" - dependencies: - "isexe" "^2.0.0" - -"word-wrap@^1.2.3": - "integrity" "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==" - "resolved" "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz" - "version" "1.2.3" - -"workerpool@6.2.1": - "integrity" "sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw==" - "resolved" "https://registry.npmjs.org/workerpool/-/workerpool-6.2.1.tgz" - "version" "6.2.1" - -"wrap-ansi@^6.2.0": - "integrity" "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==" - "resolved" "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz" - "version" "6.2.0" - dependencies: - "ansi-styles" "^4.0.0" - "string-width" "^4.1.0" - "strip-ansi" "^6.0.0" - -"wrap-ansi@^7.0.0": - "integrity" "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==" - "resolved" "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz" - "version" "7.0.0" - dependencies: - "ansi-styles" "^4.0.0" - "string-width" "^4.1.0" - "strip-ansi" "^6.0.0" - -"wrappy@1": - "integrity" "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" - "resolved" "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz" - "version" "1.0.2" - -"write-file-atomic@^3.0.0": - "integrity" "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==" - "resolved" "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz" - "version" "3.0.3" - dependencies: - "imurmurhash" "^0.1.4" - "is-typedarray" "^1.0.0" - "signal-exit" "^3.0.2" - "typedarray-to-buffer" "^3.1.5" - -"y18n@^4.0.0": - "integrity" "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==" - "resolved" "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz" - "version" "4.0.3" - -"y18n@^5.0.5": - "integrity" "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" - "resolved" "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz" - "version" "5.0.8" - -"yallist@^4.0.0": - "integrity" "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - "resolved" "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz" - "version" "4.0.0" - -"yargs-parser@^18.1.2": - "integrity" "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==" - "resolved" "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz" - "version" "18.1.3" - dependencies: - "camelcase" "^5.0.0" - "decamelize" "^1.2.0" - -"yargs-parser@^20.2.2", "yargs-parser@20.2.4": - "integrity" "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==" - "resolved" "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz" - "version" "20.2.4" - -"yargs-unparser@2.0.0": - "integrity" "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==" - "resolved" "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz" - "version" "2.0.0" - dependencies: - "camelcase" "^6.0.0" - "decamelize" "^4.0.0" - "flat" "^5.0.2" - "is-plain-obj" "^2.1.0" - -"yargs@^15.0.2": - "integrity" "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==" - "resolved" "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz" - "version" "15.4.1" - dependencies: - "cliui" "^6.0.0" - "decamelize" "^1.2.0" - "find-up" "^4.1.0" - "get-caller-file" "^2.0.1" - "require-directory" "^2.1.1" - "require-main-filename" "^2.0.0" - "set-blocking" "^2.0.0" - "string-width" "^4.2.0" - "which-module" "^2.0.0" - "y18n" "^4.0.0" - "yargs-parser" "^18.1.2" - -"yargs@16.2.0": - "integrity" "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==" - "resolved" "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz" - "version" "16.2.0" - dependencies: - "cliui" "^7.0.2" - "escalade" "^3.1.1" - "get-caller-file" "^2.0.5" - "require-directory" "^2.1.1" - "string-width" "^4.2.0" - "y18n" "^5.0.5" - "yargs-parser" "^20.2.2" - -"yn@3.1.1": - "integrity" "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==" - "resolved" "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz" - "version" "3.1.1" - -"yocto-queue@^0.1.0": - "integrity" "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==" - "resolved" "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz" - "version" "0.1.0" diff --git a/toolkit/components/certviewer/content/vendor/pkijs.js b/toolkit/components/certviewer/content/vendor/pkijs.js @@ -35,7 +35,7 @@ /*! * MIT License * - * Copyright (c) 2017-2022 Peculiar Ventures, LLC + * Copyright (c) 2017-2024 Peculiar Ventures, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -57,318 +57,339 @@ * */ -const ARRAY_BUFFER_NAME = "[object ArrayBuffer]"; -class BufferSourceConverter { - static isArrayBuffer(data) { - return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME; - } - static toArrayBuffer(data) { - if (this.isArrayBuffer(data)) { - return data; - } - if (data.byteLength === data.buffer.byteLength) { - return data.buffer; - } - return this.toUint8Array(data).slice().buffer; - } - static toUint8Array(data) { - return this.toView(data, Uint8Array); - } - static toView(data, type) { - if (data.constructor === type) { - return data; - } - if (this.isArrayBuffer(data)) { - return new type(data); - } - if (this.isArrayBufferView(data)) { - return new type(data.buffer, data.byteOffset, data.byteLength); - } - throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'"); - } - static isBufferSource(data) { - return this.isArrayBufferView(data) - || this.isArrayBuffer(data); - } - static isArrayBufferView(data) { - return ArrayBuffer.isView(data) - || (data && this.isArrayBuffer(data.buffer)); - } - static isEqual(a, b) { - const aView = BufferSourceConverter.toUint8Array(a); - const bView = BufferSourceConverter.toUint8Array(b); - if (aView.length !== bView.byteLength) { - return false; - } - for (let i = 0; i < aView.length; i++) { - if (aView[i] !== bView[i]) { - return false; - } - } - return true; - } - static concat(...args) { - if (Array.isArray(args[0])) { - const buffers = args[0]; - let size = 0; - for (const buffer of buffers) { - size += buffer.byteLength; - } - const res = new Uint8Array(size); - let offset = 0; - for (const buffer of buffers) { - const view = this.toUint8Array(buffer); - res.set(view, offset); - offset += view.length; - } - if (args[1]) { - return this.toView(res, args[1]); - } - return res.buffer; - } - else { - return this.concat(args); - } - } +const ARRAY_BUFFER_NAME = "[object ArrayBuffer]"; +class BufferSourceConverter { + static isArrayBuffer(data) { + return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME; + } + static toArrayBuffer(data) { + if (this.isArrayBuffer(data)) { + return data; + } + if (data.byteLength === data.buffer.byteLength) { + return data.buffer; + } + if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) { + return data.buffer; + } + return this.toUint8Array(data.buffer) + .slice(data.byteOffset, data.byteOffset + data.byteLength) + .buffer; + } + static toUint8Array(data) { + return this.toView(data, Uint8Array); + } + static toView(data, type) { + if (data.constructor === type) { + return data; + } + if (this.isArrayBuffer(data)) { + return new type(data); + } + if (this.isArrayBufferView(data)) { + return new type(data.buffer, data.byteOffset, data.byteLength); + } + throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'"); + } + static isBufferSource(data) { + return this.isArrayBufferView(data) + || this.isArrayBuffer(data); + } + static isArrayBufferView(data) { + return ArrayBuffer.isView(data) + || (data && this.isArrayBuffer(data.buffer)); + } + static isEqual(a, b) { + const aView = BufferSourceConverter.toUint8Array(a); + const bView = BufferSourceConverter.toUint8Array(b); + if (aView.length !== bView.byteLength) { + return false; + } + for (let i = 0; i < aView.length; i++) { + if (aView[i] !== bView[i]) { + return false; + } + } + return true; + } + static concat(...args) { + let buffers; + if (Array.isArray(args[0]) && !(args[1] instanceof Function)) { + buffers = args[0]; + } + else if (Array.isArray(args[0]) && args[1] instanceof Function) { + buffers = args[0]; + } + else { + if (args[args.length - 1] instanceof Function) { + buffers = args.slice(0, args.length - 1); + } + else { + buffers = args; + } + } + let size = 0; + for (const buffer of buffers) { + size += buffer.byteLength; + } + const res = new Uint8Array(size); + let offset = 0; + for (const buffer of buffers) { + const view = this.toUint8Array(buffer); + res.set(view, offset); + offset += view.length; + } + if (args[args.length - 1] instanceof Function) { + return this.toView(res, args[args.length - 1]); + } + return res.buffer; + } } -class Utf8Converter { - static fromString(text) { - const s = unescape(encodeURIComponent(text)); - const uintArray = new Uint8Array(s.length); - for (let i = 0; i < s.length; i++) { - uintArray[i] = s.charCodeAt(i); - } - return uintArray.buffer; - } - static toString(buffer) { - const buf = BufferSourceConverter.toUint8Array(buffer); - let encodedString = ""; - for (let i = 0; i < buf.length; i++) { - encodedString += String.fromCharCode(buf[i]); - } - const decodedString = decodeURIComponent(escape(encodedString)); - return decodedString; - } -} -class Utf16Converter { - static toString(buffer, littleEndian = false) { - const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer); - const dataView = new DataView(arrayBuffer); - let res = ""; - for (let i = 0; i < arrayBuffer.byteLength; i += 2) { - const code = dataView.getUint16(i, littleEndian); - res += String.fromCharCode(code); - } - return res; - } - static fromString(text, littleEndian = false) { - const res = new ArrayBuffer(text.length * 2); - const dataView = new DataView(res); - for (let i = 0; i < text.length; i++) { - dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian); - } - return res; - } -} -class Convert { - static isHex(data) { - return typeof data === "string" - && /^[a-z0-9]+$/i.test(data); - } - static isBase64(data) { - return typeof data === "string" - && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data); - } - static isBase64Url(data) { - return typeof data === "string" - && /^[a-zA-Z0-9-_]+$/i.test(data); - } - static ToString(buffer, enc = "utf8") { - const buf = BufferSourceConverter.toUint8Array(buffer); - switch (enc.toLowerCase()) { - case "utf8": - return this.ToUtf8String(buf); - case "binary": - return this.ToBinary(buf); - case "hex": - return this.ToHex(buf); - case "base64": - return this.ToBase64(buf); - case "base64url": - return this.ToBase64Url(buf); - case "utf16le": - return Utf16Converter.toString(buf, true); - case "utf16": - case "utf16be": - return Utf16Converter.toString(buf); - default: - throw new Error(`Unknown type of encoding '${enc}'`); - } - } - static FromString(str, enc = "utf8") { - if (!str) { - return new ArrayBuffer(0); - } - switch (enc.toLowerCase()) { - case "utf8": - return this.FromUtf8String(str); - case "binary": - return this.FromBinary(str); - case "hex": - return this.FromHex(str); - case "base64": - return this.FromBase64(str); - case "base64url": - return this.FromBase64Url(str); - case "utf16le": - return Utf16Converter.fromString(str, true); - case "utf16": - case "utf16be": - return Utf16Converter.fromString(str); - default: - throw new Error(`Unknown type of encoding '${enc}'`); - } - } - static ToBase64(buffer) { - const buf = BufferSourceConverter.toUint8Array(buffer); - if (typeof btoa !== "undefined") { - const binary = this.ToString(buf, "binary"); - return btoa(binary); - } - else { - return Buffer.from(buf).toString("base64"); - } - } - static FromBase64(base64) { - const formatted = this.formatString(base64); - if (!formatted) { - return new ArrayBuffer(0); - } - if (!Convert.isBase64(formatted)) { - throw new TypeError("Argument 'base64Text' is not Base64 encoded"); - } - if (typeof atob !== "undefined") { - return this.FromBinary(atob(formatted)); - } - else { - return new Uint8Array(Buffer.from(formatted, "base64")).buffer; - } - } - static FromBase64Url(base64url) { - const formatted = this.formatString(base64url); - if (!formatted) { - return new ArrayBuffer(0); - } - if (!Convert.isBase64Url(formatted)) { - throw new TypeError("Argument 'base64url' is not Base64Url encoded"); - } - return this.FromBase64(this.Base64Padding(formatted.replace(/\-/g, "+").replace(/\_/g, "/"))); - } - static ToBase64Url(data) { - return this.ToBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, ""); - } - static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) { - switch (encoding) { - case "ascii": - return this.FromBinary(text); - case "utf8": - return Utf8Converter.fromString(text); - case "utf16": - case "utf16be": - return Utf16Converter.fromString(text); - case "utf16le": - case "usc2": - return Utf16Converter.fromString(text, true); - default: - throw new Error(`Unknown type of encoding '${encoding}'`); - } - } - static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) { - switch (encoding) { - case "ascii": - return this.ToBinary(buffer); - case "utf8": - return Utf8Converter.toString(buffer); - case "utf16": - case "utf16be": - return Utf16Converter.toString(buffer); - case "utf16le": - case "usc2": - return Utf16Converter.toString(buffer, true); - default: - throw new Error(`Unknown type of encoding '${encoding}'`); - } - } - static FromBinary(text) { - const stringLength = text.length; - const resultView = new Uint8Array(stringLength); - for (let i = 0; i < stringLength; i++) { - resultView[i] = text.charCodeAt(i); - } - return resultView.buffer; - } - static ToBinary(buffer) { - const buf = BufferSourceConverter.toUint8Array(buffer); - let res = ""; - for (let i = 0; i < buf.length; i++) { - res += String.fromCharCode(buf[i]); - } - return res; - } - static ToHex(buffer) { - const buf = BufferSourceConverter.toUint8Array(buffer); - const splitter = ""; - const res = []; - const len = buf.length; - for (let i = 0; i < len; i++) { - const char = buf[i].toString(16).padStart(2, "0"); - res.push(char); - } - return res.join(splitter); - } - static FromHex(hexString) { - let formatted = this.formatString(hexString); - if (!formatted) { - return new ArrayBuffer(0); - } - if (!Convert.isHex(formatted)) { - throw new TypeError("Argument 'hexString' is not HEX encoded"); - } - if (formatted.length % 2) { - formatted = `0${formatted}`; - } - const res = new Uint8Array(formatted.length / 2); - for (let i = 0; i < formatted.length; i = i + 2) { - const c = formatted.slice(i, i + 2); - res[i / 2] = parseInt(c, 16); - } - return res.buffer; - } - static ToUtf16String(buffer, littleEndian = false) { - return Utf16Converter.toString(buffer, littleEndian); - } - static FromUtf16String(text, littleEndian = false) { - return Utf16Converter.fromString(text, littleEndian); - } - static Base64Padding(base64) { - const padCount = 4 - (base64.length % 4); - if (padCount < 4) { - for (let i = 0; i < padCount; i++) { - base64 += "="; - } - } - return base64; - } - static formatString(data) { - return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || ""; - } -} +const STRING_TYPE = "string"; +const HEX_REGEX = /^[0-9a-f\s]+$/i; +const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/; +class Utf8Converter { + static fromString(text) { + const s = unescape(encodeURIComponent(text)); + const uintArray = new Uint8Array(s.length); + for (let i = 0; i < s.length; i++) { + uintArray[i] = s.charCodeAt(i); + } + return uintArray.buffer; + } + static toString(buffer) { + const buf = BufferSourceConverter.toUint8Array(buffer); + let encodedString = ""; + for (let i = 0; i < buf.length; i++) { + encodedString += String.fromCharCode(buf[i]); + } + const decodedString = decodeURIComponent(escape(encodedString)); + return decodedString; + } +} +class Utf16Converter { + static toString(buffer, littleEndian = false) { + const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer); + const dataView = new DataView(arrayBuffer); + let res = ""; + for (let i = 0; i < arrayBuffer.byteLength; i += 2) { + const code = dataView.getUint16(i, littleEndian); + res += String.fromCharCode(code); + } + return res; + } + static fromString(text, littleEndian = false) { + const res = new ArrayBuffer(text.length * 2); + const dataView = new DataView(res); + for (let i = 0; i < text.length; i++) { + dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian); + } + return res; + } +} +class Convert { + static isHex(data) { + return typeof data === STRING_TYPE + && HEX_REGEX.test(data); + } + static isBase64(data) { + return typeof data === STRING_TYPE + && BASE64_REGEX.test(data); + } + static isBase64Url(data) { + return typeof data === STRING_TYPE + && BASE64URL_REGEX.test(data); + } + static ToString(buffer, enc = "utf8") { + const buf = BufferSourceConverter.toUint8Array(buffer); + switch (enc.toLowerCase()) { + case "utf8": + return this.ToUtf8String(buf); + case "binary": + return this.ToBinary(buf); + case "hex": + return this.ToHex(buf); + case "base64": + return this.ToBase64(buf); + case "base64url": + return this.ToBase64Url(buf); + case "utf16le": + return Utf16Converter.toString(buf, true); + case "utf16": + case "utf16be": + return Utf16Converter.toString(buf); + default: + throw new Error(`Unknown type of encoding '${enc}'`); + } + } + static FromString(str, enc = "utf8") { + if (!str) { + return new ArrayBuffer(0); + } + switch (enc.toLowerCase()) { + case "utf8": + return this.FromUtf8String(str); + case "binary": + return this.FromBinary(str); + case "hex": + return this.FromHex(str); + case "base64": + return this.FromBase64(str); + case "base64url": + return this.FromBase64Url(str); + case "utf16le": + return Utf16Converter.fromString(str, true); + case "utf16": + case "utf16be": + return Utf16Converter.fromString(str); + default: + throw new Error(`Unknown type of encoding '${enc}'`); + } + } + static ToBase64(buffer) { + const buf = BufferSourceConverter.toUint8Array(buffer); + if (typeof btoa !== "undefined") { + const binary = this.ToString(buf, "binary"); + return btoa(binary); + } + else { + return Buffer.from(buf).toString("base64"); + } + } + static FromBase64(base64) { + const formatted = this.formatString(base64); + if (!formatted) { + return new ArrayBuffer(0); + } + if (!Convert.isBase64(formatted)) { + throw new TypeError("Argument 'base64Text' is not Base64 encoded"); + } + if (typeof atob !== "undefined") { + return this.FromBinary(atob(formatted)); + } + else { + return new Uint8Array(Buffer.from(formatted, "base64")).buffer; + } + } + static FromBase64Url(base64url) { + const formatted = this.formatString(base64url); + if (!formatted) { + return new ArrayBuffer(0); + } + if (!Convert.isBase64Url(formatted)) { + throw new TypeError("Argument 'base64url' is not Base64Url encoded"); + } + return this.FromBase64(this.Base64Padding(formatted.replace(/\-/g, "+").replace(/\_/g, "/"))); + } + static ToBase64Url(data) { + return this.ToBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, ""); + } + static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) { + switch (encoding) { + case "ascii": + return this.FromBinary(text); + case "utf8": + return Utf8Converter.fromString(text); + case "utf16": + case "utf16be": + return Utf16Converter.fromString(text); + case "utf16le": + case "usc2": + return Utf16Converter.fromString(text, true); + default: + throw new Error(`Unknown type of encoding '${encoding}'`); + } + } + static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) { + switch (encoding) { + case "ascii": + return this.ToBinary(buffer); + case "utf8": + return Utf8Converter.toString(buffer); + case "utf16": + case "utf16be": + return Utf16Converter.toString(buffer); + case "utf16le": + case "usc2": + return Utf16Converter.toString(buffer, true); + default: + throw new Error(`Unknown type of encoding '${encoding}'`); + } + } + static FromBinary(text) { + const stringLength = text.length; + const resultView = new Uint8Array(stringLength); + for (let i = 0; i < stringLength; i++) { + resultView[i] = text.charCodeAt(i); + } + return resultView.buffer; + } + static ToBinary(buffer) { + const buf = BufferSourceConverter.toUint8Array(buffer); + let res = ""; + for (let i = 0; i < buf.length; i++) { + res += String.fromCharCode(buf[i]); + } + return res; + } + static ToHex(buffer) { + const buf = BufferSourceConverter.toUint8Array(buffer); + let result = ""; + const len = buf.length; + for (let i = 0; i < len; i++) { + const byte = buf[i]; + if (byte < 16) { + result += "0"; + } + result += byte.toString(16); + } + return result; + } + static FromHex(hexString) { + let formatted = this.formatString(hexString); + if (!formatted) { + return new ArrayBuffer(0); + } + if (!Convert.isHex(formatted)) { + throw new TypeError("Argument 'hexString' is not HEX encoded"); + } + if (formatted.length % 2) { + formatted = `0${formatted}`; + } + const res = new Uint8Array(formatted.length / 2); + for (let i = 0; i < formatted.length; i = i + 2) { + const c = formatted.slice(i, i + 2); + res[i / 2] = parseInt(c, 16); + } + return res.buffer; + } + static ToUtf16String(buffer, littleEndian = false) { + return Utf16Converter.toString(buffer, littleEndian); + } + static FromUtf16String(text, littleEndian = false) { + return Utf16Converter.fromString(text, littleEndian); + } + static Base64Padding(base64) { + const padCount = 4 - (base64.length % 4); + if (padCount < 4) { + for (let i = 0; i < padCount; i++) { + base64 += "="; + } + } + return base64; + } + static formatString(data) { + return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || ""; + } +} Convert.DEFAULT_UTF8_ENCODING = "utf8"; /*! Copyright (c) Peculiar Ventures, LLC */ + function getParametersValue(parameters, name, defaultValue) { var _a; if ((parameters instanceof Object) === false) { @@ -711,23371 +732,23842 @@ function clearProps(object, propsArray) { * */ -function assertBigInt() { - if (typeof BigInt === "undefined") { - throw new Error("BigInt is not defined. Your environment doesn't implement BigInt."); - } -} -function concat(buffers) { - let outputLength = 0; - let prevLength = 0; - for (let i = 0; i < buffers.length; i++) { - const buffer = buffers[i]; - outputLength += buffer.byteLength; - } - const retView = new Uint8Array(outputLength); - for (let i = 0; i < buffers.length; i++) { - const buffer = buffers[i]; - retView.set(new Uint8Array(buffer), prevLength); - prevLength += buffer.byteLength; - } - return retView.buffer; -} -function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) { - if (!(inputBuffer instanceof Uint8Array)) { - baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'"; - return false; - } - if (!inputBuffer.byteLength) { - baseBlock.error = "Wrong parameter: inputBuffer has zero length"; - return false; - } - if (inputOffset < 0) { - baseBlock.error = "Wrong parameter: inputOffset less than zero"; - return false; - } - if (inputLength < 0) { - baseBlock.error = "Wrong parameter: inputLength less than zero"; - return false; - } - if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) { - baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; - return false; - } - return true; + +function assertBigInt() { + if (typeof BigInt === "undefined") { + throw new Error("BigInt is not defined. Your environment doesn't implement BigInt."); + } +} +function concat(buffers) { + let outputLength = 0; + let prevLength = 0; + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + outputLength += buffer.byteLength; + } + const retView = new Uint8Array(outputLength); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + retView.set(new Uint8Array(buffer), prevLength); + prevLength += buffer.byteLength; + } + return retView.buffer; +} +function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) { + if (!(inputBuffer instanceof Uint8Array)) { + baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'"; + return false; + } + if (!inputBuffer.byteLength) { + baseBlock.error = "Wrong parameter: inputBuffer has zero length"; + return false; + } + if (inputOffset < 0) { + baseBlock.error = "Wrong parameter: inputOffset less than zero"; + return false; + } + if (inputLength < 0) { + baseBlock.error = "Wrong parameter: inputLength less than zero"; + return false; + } + if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) { + baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return false; + } + return true; } -class ViewWriter { - constructor() { - this.items = []; - } - write(buf) { - this.items.push(buf); - } - final() { - return concat(this.items); - } +class ViewWriter { + constructor() { + this.items = []; + } + write(buf) { + this.items.push(buf); + } + final() { + return concat(this.items); + } } -const powers2 = [new Uint8Array([1])]; -const digitsString = "0123456789"; -const NAME = "name"; -const VALUE_HEX_VIEW = "valueHexView"; -const IS_HEX_ONLY = "isHexOnly"; -const ID_BLOCK = "idBlock"; -const TAG_CLASS = "tagClass"; -const TAG_NUMBER = "tagNumber"; -const IS_CONSTRUCTED = "isConstructed"; -const FROM_BER = "fromBER"; -const TO_BER = "toBER"; -const LOCAL = "local"; -const EMPTY_STRING$1 = ""; -const EMPTY_BUFFER$1 = new ArrayBuffer(0); -const EMPTY_VIEW = new Uint8Array(0); -const END_OF_CONTENT_NAME = "EndOfContent"; -const OCTET_STRING_NAME = "OCTET STRING"; +const powers2 = [new Uint8Array([1])]; +const digitsString = "0123456789"; +const NAME = "name"; +const VALUE_HEX_VIEW = "valueHexView"; +const IS_HEX_ONLY = "isHexOnly"; +const ID_BLOCK = "idBlock"; +const TAG_CLASS = "tagClass"; +const TAG_NUMBER = "tagNumber"; +const IS_CONSTRUCTED = "isConstructed"; +const FROM_BER = "fromBER"; +const TO_BER = "toBER"; +const LOCAL = "local"; +const EMPTY_STRING$1 = ""; +const EMPTY_BUFFER$1 = new ArrayBuffer(0); +const EMPTY_VIEW = new Uint8Array(0); +const END_OF_CONTENT_NAME = "EndOfContent"; +const OCTET_STRING_NAME = "OCTET STRING"; const BIT_STRING_NAME = "BIT STRING"; -function HexBlock(BaseClass) { - var _a; - return _a = class Some extends BaseClass { - constructor(...args) { - var _a; - super(...args); - const params = args[0] || {}; - this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false; - this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW; - } - get valueHex() { - return this.valueHexView.slice().buffer; - } - set valueHex(value) { - this.valueHexView = new Uint8Array(value); - } - fromBER(inputBuffer, inputOffset, inputLength) { - const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; - if (!checkBufferParams(this, view, inputOffset, inputLength)) { - return -1; - } - const endLength = inputOffset + inputLength; - this.valueHexView = view.subarray(inputOffset, endLength); - if (!this.valueHexView.length) { - this.warnings.push("Zero buffer length"); - return inputOffset; - } - this.blockLength = inputLength; - return endLength; - } - toBER(sizeOnly = false) { - if (!this.isHexOnly) { - this.error = "Flag 'isHexOnly' is not set, abort"; - return EMPTY_BUFFER$1; - } - if (sizeOnly) { - return new ArrayBuffer(this.valueHexView.byteLength); - } - return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength) - ? this.valueHexView.buffer - : this.valueHexView.slice().buffer; - } - toJSON() { - return { - ...super.toJSON(), - isHexOnly: this.isHexOnly, - valueHex: Convert.ToHex(this.valueHexView), - }; - } - }, - _a.NAME = "hexBlock", - _a; +function HexBlock(BaseClass) { + var _a; + return _a = class Some extends BaseClass { + get valueHex() { + return this.valueHexView.slice().buffer; + } + set valueHex(value) { + this.valueHexView = new Uint8Array(value); + } + constructor(...args) { + var _b; + super(...args); + const params = args[0] || {}; + this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false; + this.valueHexView = params.valueHex ? BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const endLength = inputOffset + inputLength; + this.valueHexView = view.subarray(inputOffset, endLength); + if (!this.valueHexView.length) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + this.blockLength = inputLength; + return endLength; + } + toBER(sizeOnly = false) { + if (!this.isHexOnly) { + this.error = "Flag 'isHexOnly' is not set, abort"; + return EMPTY_BUFFER$1; + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength); + } + return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength) + ? this.valueHexView.buffer + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isHexOnly: this.isHexOnly, + valueHex: Convert.ToHex(this.valueHexView), + }; + } + }, + _a.NAME = "hexBlock", + _a; } -class LocalBaseBlock { - constructor({ blockLength = 0, error = EMPTY_STRING$1, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) { - this.blockLength = blockLength; - this.error = error; - this.warnings = warnings; - this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode); - } - static blockName() { - return this.NAME; - } - get valueBeforeDecode() { - return this.valueBeforeDecodeView.slice().buffer; - } - set valueBeforeDecode(value) { - this.valueBeforeDecodeView = new Uint8Array(value); - } - toJSON() { - return { - blockName: this.constructor.NAME, - blockLength: this.blockLength, - error: this.error, - warnings: this.warnings, - valueBeforeDecode: Convert.ToHex(this.valueBeforeDecodeView), - }; - } -} +class LocalBaseBlock { + static blockName() { + return this.NAME; + } + get valueBeforeDecode() { + return this.valueBeforeDecodeView.slice().buffer; + } + set valueBeforeDecode(value) { + this.valueBeforeDecodeView = new Uint8Array(value); + } + constructor({ blockLength = 0, error = EMPTY_STRING$1, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) { + this.blockLength = blockLength; + this.error = error; + this.warnings = warnings; + this.valueBeforeDecodeView = BufferSourceConverter.toUint8Array(valueBeforeDecode); + } + toJSON() { + return { + blockName: this.constructor.NAME, + blockLength: this.blockLength, + error: this.error, + warnings: this.warnings, + valueBeforeDecode: Convert.ToHex(this.valueBeforeDecodeView), + }; + } +} LocalBaseBlock.NAME = "baseBlock"; -class ValueBlock extends LocalBaseBlock { - fromBER(inputBuffer, inputOffset, inputLength) { - throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); - } - toBER(sizeOnly, writer) { - throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); - } -} +class ValueBlock extends LocalBaseBlock { + fromBER(_inputBuffer, _inputOffset, _inputLength) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } + toBER(_sizeOnly, _writer) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } +} ValueBlock.NAME = "valueBlock"; -class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) { - constructor({ idBlock = {}, } = {}) { - var _a, _b, _c, _d; - super(); - if (idBlock) { - this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false; - this.valueHexView = idBlock.valueHex ? BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW; - this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1; - this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1; - this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false; - } - else { - this.tagClass = -1; - this.tagNumber = -1; - this.isConstructed = false; - } - } - toBER(sizeOnly = false) { - let firstOctet = 0; - switch (this.tagClass) { - case 1: - firstOctet |= 0x00; - break; - case 2: - firstOctet |= 0x40; - break; - case 3: - firstOctet |= 0x80; - break; - case 4: - firstOctet |= 0xC0; - break; - default: - this.error = "Unknown tag class"; - return EMPTY_BUFFER$1; - } - if (this.isConstructed) - firstOctet |= 0x20; - if (this.tagNumber < 31 && !this.isHexOnly) { - const retView = new Uint8Array(1); - if (!sizeOnly) { - let number = this.tagNumber; - number &= 0x1F; - firstOctet |= number; - retView[0] = firstOctet; - } - return retView.buffer; - } - if (!this.isHexOnly) { - const encodedBuf = utilToBase(this.tagNumber, 7); - const encodedView = new Uint8Array(encodedBuf); - const size = encodedBuf.byteLength; - const retView = new Uint8Array(size + 1); - retView[0] = (firstOctet | 0x1F); - if (!sizeOnly) { - for (let i = 0; i < (size - 1); i++) - retView[i + 1] = encodedView[i] | 0x80; - retView[size] = encodedView[size - 1]; - } - return retView.buffer; - } - const retView = new Uint8Array(this.valueHexView.byteLength + 1); - retView[0] = (firstOctet | 0x1F); - if (!sizeOnly) { - const curView = this.valueHexView; - for (let i = 0; i < (curView.length - 1); i++) - retView[i + 1] = curView[i] | 0x80; - retView[this.valueHexView.byteLength] = curView[curView.length - 1]; - } - return retView.buffer; - } - fromBER(inputBuffer, inputOffset, inputLength) { - const inputView = BufferSourceConverter.toUint8Array(inputBuffer); - if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { - return -1; - } - const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); - if (intBuffer.length === 0) { - this.error = "Zero buffer length"; - return -1; - } - const tagClassMask = intBuffer[0] & 0xC0; - switch (tagClassMask) { - case 0x00: - this.tagClass = (1); - break; - case 0x40: - this.tagClass = (2); - break; - case 0x80: - this.tagClass = (3); - break; - case 0xC0: - this.tagClass = (4); - break; - default: - this.error = "Unknown tag class"; - return -1; - } - this.isConstructed = (intBuffer[0] & 0x20) === 0x20; - this.isHexOnly = false; - const tagNumberMask = intBuffer[0] & 0x1F; - if (tagNumberMask !== 0x1F) { - this.tagNumber = (tagNumberMask); - this.blockLength = 1; - } - else { - let count = 1; - let intTagNumberBuffer = this.valueHexView = new Uint8Array(255); - let tagNumberBufferMaxLength = 255; - while (intBuffer[count] & 0x80) { - intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; - count++; - if (count >= intBuffer.length) { - this.error = "End of input reached before message was fully decoded"; - return -1; - } - if (count === tagNumberBufferMaxLength) { - tagNumberBufferMaxLength += 255; - const tempBufferView = new Uint8Array(tagNumberBufferMaxLength); - for (let i = 0; i < intTagNumberBuffer.length; i++) - tempBufferView[i] = intTagNumberBuffer[i]; - intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength); - } - } - this.blockLength = (count + 1); - intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; - const tempBufferView = new Uint8Array(count); - for (let i = 0; i < count; i++) - tempBufferView[i] = intTagNumberBuffer[i]; - intTagNumberBuffer = this.valueHexView = new Uint8Array(count); - intTagNumberBuffer.set(tempBufferView); - if (this.blockLength <= 9) - this.tagNumber = utilFromBase(intTagNumberBuffer, 7); - else { - this.isHexOnly = true; - this.warnings.push("Tag too long, represented as hex-coded"); - } - } - if (((this.tagClass === 1)) && - (this.isConstructed)) { - switch (this.tagNumber) { - case 1: - case 2: - case 5: - case 6: - case 9: - case 13: - case 14: - case 23: - case 24: - case 31: - case 32: - case 33: - case 34: - this.error = "Constructed encoding used for primitive type"; - return -1; - } - } - return (inputOffset + this.blockLength); - } - toJSON() { - return { - ...super.toJSON(), - tagClass: this.tagClass, - tagNumber: this.tagNumber, - isConstructed: this.isConstructed, - }; - } -} +class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) { + constructor({ idBlock = {} } = {}) { + var _a, _b, _c, _d; + super(); + if (idBlock) { + this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false; + this.valueHexView = idBlock.valueHex + ? BufferSourceConverter.toUint8Array(idBlock.valueHex) + : EMPTY_VIEW; + this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1; + this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1; + this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false; + } + else { + this.tagClass = -1; + this.tagNumber = -1; + this.isConstructed = false; + } + } + toBER(sizeOnly = false) { + let firstOctet = 0; + switch (this.tagClass) { + case 1: + firstOctet |= 0x00; + break; + case 2: + firstOctet |= 0x40; + break; + case 3: + firstOctet |= 0x80; + break; + case 4: + firstOctet |= 0xC0; + break; + default: + this.error = "Unknown tag class"; + return EMPTY_BUFFER$1; + } + if (this.isConstructed) + firstOctet |= 0x20; + if (this.tagNumber < 31 && !this.isHexOnly) { + const retView = new Uint8Array(1); + if (!sizeOnly) { + let number = this.tagNumber; + number &= 0x1F; + firstOctet |= number; + retView[0] = firstOctet; + } + return retView.buffer; + } + if (!this.isHexOnly) { + const encodedBuf = utilToBase(this.tagNumber, 7); + const encodedView = new Uint8Array(encodedBuf); + const size = encodedBuf.byteLength; + const retView = new Uint8Array(size + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + for (let i = 0; i < (size - 1); i++) + retView[i + 1] = encodedView[i] | 0x80; + retView[size] = encodedView[size - 1]; + } + return retView.buffer; + } + const retView = new Uint8Array(this.valueHexView.byteLength + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + const curView = this.valueHexView; + for (let i = 0; i < (curView.length - 1); i++) + retView[i + 1] = curView[i] | 0x80; + retView[this.valueHexView.byteLength] = curView[curView.length - 1]; + } + return retView.buffer; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + const tagClassMask = intBuffer[0] & 0xC0; + switch (tagClassMask) { + case 0x00: + this.tagClass = (1); + break; + case 0x40: + this.tagClass = (2); + break; + case 0x80: + this.tagClass = (3); + break; + case 0xC0: + this.tagClass = (4); + break; + default: + this.error = "Unknown tag class"; + return -1; + } + this.isConstructed = (intBuffer[0] & 0x20) === 0x20; + this.isHexOnly = false; + const tagNumberMask = intBuffer[0] & 0x1F; + if (tagNumberMask !== 0x1F) { + this.tagNumber = (tagNumberMask); + this.blockLength = 1; + } + else { + let count = 1; + let intTagNumberBuffer = this.valueHexView = new Uint8Array(255); + let tagNumberBufferMaxLength = 255; + while (intBuffer[count] & 0x80) { + intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; + count++; + if (count >= intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (count === tagNumberBufferMaxLength) { + tagNumberBufferMaxLength += 255; + const tempBufferView = new Uint8Array(tagNumberBufferMaxLength); + for (let i = 0; i < intTagNumberBuffer.length; i++) + tempBufferView[i] = intTagNumberBuffer[i]; + intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength); + } + } + this.blockLength = (count + 1); + intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; + const tempBufferView = new Uint8Array(count); + for (let i = 0; i < count; i++) + tempBufferView[i] = intTagNumberBuffer[i]; + intTagNumberBuffer = this.valueHexView = new Uint8Array(count); + intTagNumberBuffer.set(tempBufferView); + if (this.blockLength <= 9) + this.tagNumber = utilFromBase(intTagNumberBuffer, 7); + else { + this.isHexOnly = true; + this.warnings.push("Tag too long, represented as hex-coded"); + } + } + if (((this.tagClass === 1)) + && (this.isConstructed)) { + switch (this.tagNumber) { + case 1: + case 2: + case 5: + case 6: + case 9: + case 13: + case 14: + case 23: + case 24: + case 31: + case 32: + case 33: + case 34: + this.error = "Constructed encoding used for primitive type"; + return -1; + } + } + return (inputOffset + this.blockLength); + } + toJSON() { + return { + ...super.toJSON(), + tagClass: this.tagClass, + tagNumber: this.tagNumber, + isConstructed: this.isConstructed, + }; + } +} LocalIdentificationBlock.NAME = "identificationBlock"; -class LocalLengthBlock extends LocalBaseBlock { - constructor({ lenBlock = {}, } = {}) { - var _a, _b, _c; - super(); - this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false; - this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false; - this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0; - } - fromBER(inputBuffer, inputOffset, inputLength) { - const view = BufferSourceConverter.toUint8Array(inputBuffer); - if (!checkBufferParams(this, view, inputOffset, inputLength)) { - return -1; - } - const intBuffer = view.subarray(inputOffset, inputOffset + inputLength); - if (intBuffer.length === 0) { - this.error = "Zero buffer length"; - return -1; - } - if (intBuffer[0] === 0xFF) { - this.error = "Length block 0xFF is reserved by standard"; - return -1; - } - this.isIndefiniteForm = intBuffer[0] === 0x80; - if (this.isIndefiniteForm) { - this.blockLength = 1; - return (inputOffset + this.blockLength); - } - this.longFormUsed = !!(intBuffer[0] & 0x80); - if (this.longFormUsed === false) { - this.length = (intBuffer[0]); - this.blockLength = 1; - return (inputOffset + this.blockLength); - } - const count = intBuffer[0] & 0x7F; - if (count > 8) { - this.error = "Too big integer"; - return -1; - } - if ((count + 1) > intBuffer.length) { - this.error = "End of input reached before message was fully decoded"; - return -1; - } - const lenOffset = inputOffset + 1; - const lengthBufferView = view.subarray(lenOffset, lenOffset + count); - if (lengthBufferView[count - 1] === 0x00) - this.warnings.push("Needlessly long encoded length"); - this.length = utilFromBase(lengthBufferView, 8); - if (this.longFormUsed && (this.length <= 127)) - this.warnings.push("Unnecessary usage of long length form"); - this.blockLength = count + 1; - return (inputOffset + this.blockLength); - } - toBER(sizeOnly = false) { - let retBuf; - let retView; - if (this.length > 127) - this.longFormUsed = true; - if (this.isIndefiniteForm) { - retBuf = new ArrayBuffer(1); - if (sizeOnly === false) { - retView = new Uint8Array(retBuf); - retView[0] = 0x80; - } - return retBuf; - } - if (this.longFormUsed) { - const encodedBuf = utilToBase(this.length, 8); - if (encodedBuf.byteLength > 127) { - this.error = "Too big length"; - return (EMPTY_BUFFER$1); - } - retBuf = new ArrayBuffer(encodedBuf.byteLength + 1); - if (sizeOnly) - return retBuf; - const encodedView = new Uint8Array(encodedBuf); - retView = new Uint8Array(retBuf); - retView[0] = encodedBuf.byteLength | 0x80; - for (let i = 0; i < encodedBuf.byteLength; i++) - retView[i + 1] = encodedView[i]; - return retBuf; - } - retBuf = new ArrayBuffer(1); - if (sizeOnly === false) { - retView = new Uint8Array(retBuf); - retView[0] = this.length; - } - return retBuf; - } - toJSON() { - return { - ...super.toJSON(), - isIndefiniteForm: this.isIndefiniteForm, - longFormUsed: this.longFormUsed, - length: this.length, - }; - } -} +class LocalLengthBlock extends LocalBaseBlock { + constructor({ lenBlock = {} } = {}) { + var _a, _b, _c; + super(); + this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false; + this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false; + this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const intBuffer = view.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + if (intBuffer[0] === 0xFF) { + this.error = "Length block 0xFF is reserved by standard"; + return -1; + } + this.isIndefiniteForm = intBuffer[0] === 0x80; + if (this.isIndefiniteForm) { + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + this.longFormUsed = !!(intBuffer[0] & 0x80); + if (this.longFormUsed === false) { + this.length = (intBuffer[0]); + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + const count = intBuffer[0] & 0x7F; + if (count > 8) { + this.error = "Too big integer"; + return -1; + } + if ((count + 1) > intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + const lenOffset = inputOffset + 1; + const lengthBufferView = view.subarray(lenOffset, lenOffset + count); + if (lengthBufferView[count - 1] === 0x00) + this.warnings.push("Needlessly long encoded length"); + this.length = utilFromBase(lengthBufferView, 8); + if (this.longFormUsed && (this.length <= 127)) + this.warnings.push("Unnecessary usage of long length form"); + this.blockLength = count + 1; + return (inputOffset + this.blockLength); + } + toBER(sizeOnly = false) { + let retBuf; + let retView; + if (this.length > 127) + this.longFormUsed = true; + if (this.isIndefiniteForm) { + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = 0x80; + } + return retBuf; + } + if (this.longFormUsed) { + const encodedBuf = utilToBase(this.length, 8); + if (encodedBuf.byteLength > 127) { + this.error = "Too big length"; + return (EMPTY_BUFFER$1); + } + retBuf = new ArrayBuffer(encodedBuf.byteLength + 1); + if (sizeOnly) + return retBuf; + const encodedView = new Uint8Array(encodedBuf); + retView = new Uint8Array(retBuf); + retView[0] = encodedBuf.byteLength | 0x80; + for (let i = 0; i < encodedBuf.byteLength; i++) + retView[i + 1] = encodedView[i]; + return retBuf; + } + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = this.length; + } + return retBuf; + } + toJSON() { + return { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + longFormUsed: this.longFormUsed, + length: this.length, + }; + } +} LocalLengthBlock.NAME = "lengthBlock"; const typeStore = {}; -class BaseBlock extends LocalBaseBlock { - constructor({ name = EMPTY_STRING$1, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) { - super(parameters); - this.name = name; - this.optional = optional; - if (primitiveSchema) { - this.primitiveSchema = primitiveSchema; - } - this.idBlock = new LocalIdentificationBlock(parameters); - this.lenBlock = new LocalLengthBlock(parameters); - this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters); - } - fromBER(inputBuffer, inputOffset, inputLength) { - const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); - if (resultOffset === -1) { - this.error = this.valueBlock.error; - return resultOffset; - } - if (!this.idBlock.error.length) - this.blockLength += this.idBlock.blockLength; - if (!this.lenBlock.error.length) - this.blockLength += this.lenBlock.blockLength; - if (!this.valueBlock.error.length) - this.blockLength += this.valueBlock.blockLength; - return resultOffset; - } - toBER(sizeOnly, writer) { - const _writer = writer || new ViewWriter(); - if (!writer) { - prepareIndefiniteForm(this); - } - const idBlockBuf = this.idBlock.toBER(sizeOnly); - _writer.write(idBlockBuf); - if (this.lenBlock.isIndefiniteForm) { - _writer.write(new Uint8Array([0x80]).buffer); - this.valueBlock.toBER(sizeOnly, _writer); - _writer.write(new ArrayBuffer(2)); - } - else { - const valueBlockBuf = this.valueBlock.toBER(sizeOnly); - this.lenBlock.length = valueBlockBuf.byteLength; - const lenBlockBuf = this.lenBlock.toBER(sizeOnly); - _writer.write(lenBlockBuf); - _writer.write(valueBlockBuf); - } - if (!writer) { - return _writer.final(); - } - return EMPTY_BUFFER$1; - } - toJSON() { - const object = { - ...super.toJSON(), - idBlock: this.idBlock.toJSON(), - lenBlock: this.lenBlock.toJSON(), - valueBlock: this.valueBlock.toJSON(), - name: this.name, - optional: this.optional, - }; - if (this.primitiveSchema) - object.primitiveSchema = this.primitiveSchema.toJSON(); - return object; - } - toString(encoding = "ascii") { - if (encoding === "ascii") { - return this.onAsciiEncoding(); - } - return Convert.ToHex(this.toBER()); - } - onAsciiEncoding() { - return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`; - } - isEqual(other) { - if (this === other) { - return true; - } - if (!(other instanceof this.constructor)) { - return false; - } - const thisRaw = this.toBER(); - const otherRaw = other.toBER(); - return isEqualBuffer(thisRaw, otherRaw); - } -} -BaseBlock.NAME = "BaseBlock"; -function prepareIndefiniteForm(baseBlock) { - if (baseBlock instanceof typeStore.Constructed) { - for (const value of baseBlock.valueBlock.value) { - if (prepareIndefiniteForm(value)) { - baseBlock.lenBlock.isIndefiniteForm = true; - } - } - } - return !!baseBlock.lenBlock.isIndefiniteForm; +class BaseBlock extends LocalBaseBlock { + constructor({ name = EMPTY_STRING$1, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) { + super(parameters); + this.name = name; + this.optional = optional; + if (primitiveSchema) { + this.primitiveSchema = primitiveSchema; + } + this.idBlock = new LocalIdentificationBlock(parameters); + this.lenBlock = new LocalLengthBlock(parameters); + this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) + ? inputLength + : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + if (!writer) { + prepareIndefiniteForm(this); + } + const idBlockBuf = this.idBlock.toBER(sizeOnly); + _writer.write(idBlockBuf); + if (this.lenBlock.isIndefiniteForm) { + _writer.write(new Uint8Array([0x80]).buffer); + this.valueBlock.toBER(sizeOnly, _writer); + _writer.write(new ArrayBuffer(2)); + } + else { + const valueBlockBuf = this.valueBlock.toBER(sizeOnly); + this.lenBlock.length = valueBlockBuf.byteLength; + const lenBlockBuf = this.lenBlock.toBER(sizeOnly); + _writer.write(lenBlockBuf); + _writer.write(valueBlockBuf); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER$1; + } + toJSON() { + const object = { + ...super.toJSON(), + idBlock: this.idBlock.toJSON(), + lenBlock: this.lenBlock.toJSON(), + valueBlock: this.valueBlock.toJSON(), + name: this.name, + optional: this.optional, + }; + if (this.primitiveSchema) + object.primitiveSchema = this.primitiveSchema.toJSON(); + return object; + } + toString(encoding = "ascii") { + if (encoding === "ascii") { + return this.onAsciiEncoding(); + } + return Convert.ToHex(this.toBER()); + } + onAsciiEncoding() { + const name = this.constructor.NAME; + const value = Convert.ToHex(this.valueBlock.valueBeforeDecodeView); + return `${name} : ${value}`; + } + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof this.constructor)) { + return false; + } + const thisRaw = this.toBER(); + const otherRaw = other.toBER(); + return isEqualBuffer(thisRaw, otherRaw); + } +} +BaseBlock.NAME = "BaseBlock"; +function prepareIndefiniteForm(baseBlock) { + var _a; + if (baseBlock instanceof typeStore.Constructed) { + for (const value of baseBlock.valueBlock.value) { + if (prepareIndefiniteForm(value)) { + baseBlock.lenBlock.isIndefiniteForm = true; + } + } + } + return !!((_a = baseBlock.lenBlock) === null || _a === void 0 ? void 0 : _a.isIndefiniteForm); } -class BaseStringBlock extends BaseBlock { - constructor({ value = EMPTY_STRING$1, ...parameters } = {}, stringValueBlockType) { - super(parameters, stringValueBlockType); - if (value) { - this.fromString(value); - } - } - getValue() { - return this.valueBlock.value; - } - setValue(value) { - this.valueBlock.value = value; - } - fromBER(inputBuffer, inputOffset, inputLength) { - const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); - if (resultOffset === -1) { - this.error = this.valueBlock.error; - return resultOffset; - } - this.fromBuffer(this.valueBlock.valueHexView); - if (!this.idBlock.error.length) - this.blockLength += this.idBlock.blockLength; - if (!this.lenBlock.error.length) - this.blockLength += this.lenBlock.blockLength; - if (!this.valueBlock.error.length) - this.blockLength += this.valueBlock.blockLength; - return resultOffset; - } - onAsciiEncoding() { - return `${this.constructor.NAME} : '${this.valueBlock.value}'`; - } -} +class BaseStringBlock extends BaseBlock { + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + constructor({ value = EMPTY_STRING$1, ...parameters } = {}, stringValueBlockType) { + super(parameters, stringValueBlockType); + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) + ? inputLength + : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + this.fromBuffer(this.valueBlock.valueHexView); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : '${this.valueBlock.value}'`; + } +} BaseStringBlock.NAME = "BaseStringBlock"; -class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) { - constructor({ isHexOnly = true, ...parameters } = {}) { - super(parameters); - this.isHexOnly = isHexOnly; - } -} +class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) { + constructor({ isHexOnly = true, ...parameters } = {}) { + super(parameters); + this.isHexOnly = isHexOnly; + } +} LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock"; -var _a$w; -class Primitive extends BaseBlock { - constructor(parameters = {}) { - super(parameters, LocalPrimitiveValueBlock); - this.idBlock.isConstructed = false; - } -} -_a$w = Primitive; -(() => { - typeStore.Primitive = _a$w; -})(); +var _a$w; +class Primitive extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalPrimitiveValueBlock); + this.idBlock.isConstructed = false; + } +} +_a$w = Primitive; +(() => { + typeStore.Primitive = _a$w; +})(); Primitive.NAME = "PRIMITIVE"; -function localChangeType(inputObject, newType) { - if (inputObject instanceof newType) { - return inputObject; - } - const newObject = new newType(); - newObject.idBlock = inputObject.idBlock; - newObject.lenBlock = inputObject.lenBlock; - newObject.warnings = inputObject.warnings; - newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView; - return newObject; -} -function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) { - const incomingOffset = inputOffset; - let returnObject = new BaseBlock({}, ValueBlock); - const baseBlock = new LocalBaseBlock(); - if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) { - returnObject.error = baseBlock.error; - return { - offset: -1, - result: returnObject - }; - } - const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength); - if (!intBuffer.length) { - returnObject.error = "Zero buffer length"; - return { - offset: -1, - result: returnObject - }; - } - let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength); - if (returnObject.idBlock.warnings.length) { - returnObject.warnings.concat(returnObject.idBlock.warnings); - } - if (resultOffset === -1) { - returnObject.error = returnObject.idBlock.error; - return { - offset: -1, - result: returnObject - }; - } - inputOffset = resultOffset; - inputLength -= returnObject.idBlock.blockLength; - resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength); - if (returnObject.lenBlock.warnings.length) { - returnObject.warnings.concat(returnObject.lenBlock.warnings); - } - if (resultOffset === -1) { - returnObject.error = returnObject.lenBlock.error; - return { - offset: -1, - result: returnObject - }; - } - inputOffset = resultOffset; - inputLength -= returnObject.lenBlock.blockLength; - if (!returnObject.idBlock.isConstructed && - returnObject.lenBlock.isIndefiniteForm) { - returnObject.error = "Indefinite length form used for primitive encoding form"; - return { - offset: -1, - result: returnObject - }; - } - let newASN1Type = BaseBlock; - switch (returnObject.idBlock.tagClass) { - case 1: - if ((returnObject.idBlock.tagNumber >= 37) && - (returnObject.idBlock.isHexOnly === false)) { - returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard"; - return { - offset: -1, - result: returnObject - }; - } - switch (returnObject.idBlock.tagNumber) { - case 0: - if ((returnObject.idBlock.isConstructed) && - (returnObject.lenBlock.length > 0)) { - returnObject.error = "Type [UNIVERSAL 0] is reserved"; - return { - offset: -1, - result: returnObject - }; - } - newASN1Type = typeStore.EndOfContent; - break; - case 1: - newASN1Type = typeStore.Boolean; - break; - case 2: - newASN1Type = typeStore.Integer; - break; - case 3: - newASN1Type = typeStore.BitString; - break; - case 4: - newASN1Type = typeStore.OctetString; - break; - case 5: - newASN1Type = typeStore.Null; - break; - case 6: - newASN1Type = typeStore.ObjectIdentifier; - break; - case 10: - newASN1Type = typeStore.Enumerated; - break; - case 12: - newASN1Type = typeStore.Utf8String; - break; - case 13: - newASN1Type = typeStore.RelativeObjectIdentifier; - break; - case 14: - newASN1Type = typeStore.TIME; - break; - case 15: - returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard"; - return { - offset: -1, - result: returnObject - }; - case 16: - newASN1Type = typeStore.Sequence; - break; - case 17: - newASN1Type = typeStore.Set; - break; - case 18: - newASN1Type = typeStore.NumericString; - break; - case 19: - newASN1Type = typeStore.PrintableString; - break; - case 20: - newASN1Type = typeStore.TeletexString; - break; - case 21: - newASN1Type = typeStore.VideotexString; - break; - case 22: - newASN1Type = typeStore.IA5String; - break; - case 23: - newASN1Type = typeStore.UTCTime; - break; - case 24: - newASN1Type = typeStore.GeneralizedTime; - break; - case 25: - newASN1Type = typeStore.GraphicString; - break; - case 26: - newASN1Type = typeStore.VisibleString; - break; - case 27: - newASN1Type = typeStore.GeneralString; - break; - case 28: - newASN1Type = typeStore.UniversalString; - break; - case 29: - newASN1Type = typeStore.CharacterString; - break; - case 30: - newASN1Type = typeStore.BmpString; - break; - case 31: - newASN1Type = typeStore.DATE; - break; - case 32: - newASN1Type = typeStore.TimeOfDay; - break; - case 33: - newASN1Type = typeStore.DateTime; - break; - case 34: - newASN1Type = typeStore.Duration; - break; - default: { - const newObject = returnObject.idBlock.isConstructed - ? new typeStore.Constructed() - : new typeStore.Primitive(); - newObject.idBlock = returnObject.idBlock; - newObject.lenBlock = returnObject.lenBlock; - newObject.warnings = returnObject.warnings; - returnObject = newObject; - } - } - break; - case 2: - case 3: - case 4: - default: { - newASN1Type = returnObject.idBlock.isConstructed - ? typeStore.Constructed - : typeStore.Primitive; - } - } - returnObject = localChangeType(returnObject, newASN1Type); - resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length); - returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength); - return { - offset: resultOffset, - result: returnObject - }; -} -function fromBER(inputBuffer) { - if (!inputBuffer.byteLength) { - const result = new BaseBlock({}, ValueBlock); - result.error = "Input buffer has zero length"; - return { - offset: -1, - result - }; - } - return localFromBER(BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength); +function localChangeType(inputObject, newType) { + if (inputObject instanceof newType) { + return inputObject; + } + const newObject = new newType(); + newObject.idBlock = inputObject.idBlock; + newObject.lenBlock = inputObject.lenBlock; + newObject.warnings = inputObject.warnings; + newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView; + return newObject; +} +function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) { + const incomingOffset = inputOffset; + let returnObject = new BaseBlock({}, ValueBlock); + const baseBlock = new LocalBaseBlock(); + if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) { + returnObject.error = baseBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength); + if (!intBuffer.length) { + returnObject.error = "Zero buffer length"; + return { + offset: -1, + result: returnObject, + }; + } + let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.idBlock.warnings.length) { + returnObject.warnings.concat(returnObject.idBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.idBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.idBlock.blockLength; + resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.lenBlock.warnings.length) { + returnObject.warnings.concat(returnObject.lenBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.lenBlock.error; + return { + offset: -1, + result: returnObject, + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.lenBlock.blockLength; + if (!returnObject.idBlock.isConstructed + && returnObject.lenBlock.isIndefiniteForm) { + returnObject.error = "Indefinite length form used for primitive encoding form"; + return { + offset: -1, + result: returnObject, + }; + } + let newASN1Type = BaseBlock; + switch (returnObject.idBlock.tagClass) { + case 1: + if ((returnObject.idBlock.tagNumber >= 37) + && (returnObject.idBlock.isHexOnly === false)) { + returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject, + }; + } + switch (returnObject.idBlock.tagNumber) { + case 0: + if ((returnObject.idBlock.isConstructed) + && (returnObject.lenBlock.length > 0)) { + returnObject.error = "Type [UNIVERSAL 0] is reserved"; + return { + offset: -1, + result: returnObject, + }; + } + newASN1Type = typeStore.EndOfContent; + break; + case 1: + newASN1Type = typeStore.Boolean; + break; + case 2: + newASN1Type = typeStore.Integer; + break; + case 3: + newASN1Type = typeStore.BitString; + break; + case 4: + newASN1Type = typeStore.OctetString; + break; + case 5: + newASN1Type = typeStore.Null; + break; + case 6: + newASN1Type = typeStore.ObjectIdentifier; + break; + case 10: + newASN1Type = typeStore.Enumerated; + break; + case 12: + newASN1Type = typeStore.Utf8String; + break; + case 13: + newASN1Type = typeStore.RelativeObjectIdentifier; + break; + case 14: + newASN1Type = typeStore.TIME; + break; + case 15: + returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject, + }; + case 16: + newASN1Type = typeStore.Sequence; + break; + case 17: + newASN1Type = typeStore.Set; + break; + case 18: + newASN1Type = typeStore.NumericString; + break; + case 19: + newASN1Type = typeStore.PrintableString; + break; + case 20: + newASN1Type = typeStore.TeletexString; + break; + case 21: + newASN1Type = typeStore.VideotexString; + break; + case 22: + newASN1Type = typeStore.IA5String; + break; + case 23: + newASN1Type = typeStore.UTCTime; + break; + case 24: + newASN1Type = typeStore.GeneralizedTime; + break; + case 25: + newASN1Type = typeStore.GraphicString; + break; + case 26: + newASN1Type = typeStore.VisibleString; + break; + case 27: + newASN1Type = typeStore.GeneralString; + break; + case 28: + newASN1Type = typeStore.UniversalString; + break; + case 29: + newASN1Type = typeStore.CharacterString; + break; + case 30: + newASN1Type = typeStore.BmpString; + break; + case 31: + newASN1Type = typeStore.DATE; + break; + case 32: + newASN1Type = typeStore.TimeOfDay; + break; + case 33: + newASN1Type = typeStore.DateTime; + break; + case 34: + newASN1Type = typeStore.Duration; + break; + default: { + const newObject = returnObject.idBlock.isConstructed + ? new typeStore.Constructed() + : new typeStore.Primitive(); + newObject.idBlock = returnObject.idBlock; + newObject.lenBlock = returnObject.lenBlock; + newObject.warnings = returnObject.warnings; + returnObject = newObject; + } + } + break; + case 2: + case 3: + case 4: + default: { + newASN1Type = returnObject.idBlock.isConstructed + ? typeStore.Constructed + : typeStore.Primitive; + } + } + returnObject = localChangeType(returnObject, newASN1Type); + resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length); + returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength); + return { + offset: resultOffset, + result: returnObject, + }; +} +function fromBER(inputBuffer) { + if (!inputBuffer.byteLength) { + const result = new BaseBlock({}, ValueBlock); + result.error = "Input buffer has zero length"; + return { + offset: -1, + result, + }; + } + return localFromBER(BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength); } -function checkLen(indefiniteLength, length) { - if (indefiniteLength) { - return 1; - } - return length; -} -class LocalConstructedValueBlock extends ValueBlock { - constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) { - super(parameters); - this.value = value; - this.isIndefiniteForm = isIndefiniteForm; - } - fromBER(inputBuffer, inputOffset, inputLength) { - const view = BufferSourceConverter.toUint8Array(inputBuffer); - if (!checkBufferParams(this, view, inputOffset, inputLength)) { - return -1; - } - this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength); - if (this.valueBeforeDecodeView.length === 0) { - this.warnings.push("Zero buffer length"); - return inputOffset; - } - let currentOffset = inputOffset; - while (checkLen(this.isIndefiniteForm, inputLength) > 0) { - const returnObject = localFromBER(view, currentOffset, inputLength); - if (returnObject.offset === -1) { - this.error = returnObject.result.error; - this.warnings.concat(returnObject.result.warnings); - return -1; - } - currentOffset = returnObject.offset; - this.blockLength += returnObject.result.blockLength; - inputLength -= returnObject.result.blockLength; - this.value.push(returnObject.result); - if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) { - break; - } - } - if (this.isIndefiniteForm) { - if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) { - this.value.pop(); - } - else { - this.warnings.push("No EndOfContent block encoded"); - } - } - return currentOffset; - } - toBER(sizeOnly, writer) { - const _writer = writer || new ViewWriter(); - for (let i = 0; i < this.value.length; i++) { - this.value[i].toBER(sizeOnly, _writer); - } - if (!writer) { - return _writer.final(); - } - return EMPTY_BUFFER$1; - } - toJSON() { - const object = { - ...super.toJSON(), - isIndefiniteForm: this.isIndefiniteForm, - value: [], - }; - for (const value of this.value) { - object.value.push(value.toJSON()); - } - return object; - } -} +function checkLen(indefiniteLength, length) { + if (indefiniteLength) { + return 1; + } + return length; +} +class LocalConstructedValueBlock extends ValueBlock { + constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.isIndefiniteForm = isIndefiniteForm; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength); + if (this.valueBeforeDecodeView.length === 0) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + let currentOffset = inputOffset; + while (checkLen(this.isIndefiniteForm, inputLength) > 0) { + const returnObject = localFromBER(view, currentOffset, inputLength); + if (returnObject.offset === -1) { + this.error = returnObject.result.error; + this.warnings.concat(returnObject.result.warnings); + return -1; + } + currentOffset = returnObject.offset; + this.blockLength += returnObject.result.blockLength; + inputLength -= returnObject.result.blockLength; + this.value.push(returnObject.result); + if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) { + break; + } + } + if (this.isIndefiniteForm) { + if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) { + this.value.pop(); + } + else { + this.warnings.push("No EndOfContent block encoded"); + } + } + return currentOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + for (let i = 0; i < this.value.length; i++) { + this.value[i].toBER(sizeOnly, _writer); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER$1; + } + toJSON() { + const object = { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + value: [], + }; + for (const value of this.value) { + object.value.push(value.toJSON()); + } + return object; + } +} LocalConstructedValueBlock.NAME = "ConstructedValueBlock"; -var _a$v; -class Constructed extends BaseBlock { - constructor(parameters = {}) { - super(parameters, LocalConstructedValueBlock); - this.idBlock.isConstructed = true; - } - fromBER(inputBuffer, inputOffset, inputLength) { - this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; - const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); - if (resultOffset === -1) { - this.error = this.valueBlock.error; - return resultOffset; - } - if (!this.idBlock.error.length) - this.blockLength += this.idBlock.blockLength; - if (!this.lenBlock.error.length) - this.blockLength += this.lenBlock.blockLength; - if (!this.valueBlock.error.length) - this.blockLength += this.valueBlock.blockLength; - return resultOffset; - } - onAsciiEncoding() { - const values = []; - for (const value of this.valueBlock.value) { - values.push(value.toString("ascii").split("\n").map(o => ` ${o}`).join("\n")); - } - const blockName = this.idBlock.tagClass === 3 - ? `[${this.idBlock.tagNumber}]` - : this.constructor.NAME; - return values.length - ? `${blockName} :\n${values.join("\n")}` - : `${blockName} :`; - } -} -_a$v = Constructed; -(() => { - typeStore.Constructed = _a$v; -})(); +var _a$v; +class Constructed extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalConstructedValueBlock); + this.idBlock.isConstructed = true; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + const values = []; + for (const value of this.valueBlock.value) { + values.push(value.toString("ascii").split("\n").map((o) => ` ${o}`).join("\n")); + } + const blockName = this.idBlock.tagClass === 3 + ? `[${this.idBlock.tagNumber}]` + : this.constructor.NAME; + return values.length + ? `${blockName} :\n${values.join("\n")}` + : `${blockName} :`; + } +} +_a$v = Constructed; +(() => { + typeStore.Constructed = _a$v; +})(); Constructed.NAME = "CONSTRUCTED"; -class LocalEndOfContentValueBlock extends ValueBlock { - fromBER(inputBuffer, inputOffset, inputLength) { - return inputOffset; - } - toBER(sizeOnly) { - return EMPTY_BUFFER$1; - } -} +class LocalEndOfContentValueBlock extends ValueBlock { + fromBER(inputBuffer, inputOffset, _inputLength) { + return inputOffset; + } + toBER(_sizeOnly) { + return EMPTY_BUFFER$1; + } +} LocalEndOfContentValueBlock.override = "EndOfContentValueBlock"; -var _a$u; -class EndOfContent extends BaseBlock { - constructor(parameters = {}) { - super(parameters, LocalEndOfContentValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 0; - } -} -_a$u = EndOfContent; -(() => { - typeStore.EndOfContent = _a$u; -})(); +var _a$u; +class EndOfContent extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalEndOfContentValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 0; + } +} +_a$u = EndOfContent; +(() => { + typeStore.EndOfContent = _a$u; +})(); EndOfContent.NAME = END_OF_CONTENT_NAME; -var _a$t; -class Null extends BaseBlock { - constructor(parameters = {}) { - super(parameters, ValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 5; - } - fromBER(inputBuffer, inputOffset, inputLength) { - if (this.lenBlock.length > 0) - this.warnings.push("Non-zero length of value block for Null type"); - if (!this.idBlock.error.length) - this.blockLength += this.idBlock.blockLength; - if (!this.lenBlock.error.length) - this.blockLength += this.lenBlock.blockLength; - this.blockLength += inputLength; - if ((inputOffset + inputLength) > inputBuffer.byteLength) { - this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; - return -1; - } - return (inputOffset + inputLength); - } - toBER(sizeOnly, writer) { - const retBuf = new ArrayBuffer(2); - if (!sizeOnly) { - const retView = new Uint8Array(retBuf); - retView[0] = 0x05; - retView[1] = 0x00; - } - if (writer) { - writer.write(retBuf); - } - return retBuf; - } - onAsciiEncoding() { - return `${this.constructor.NAME}`; - } -} -_a$t = Null; -(() => { - typeStore.Null = _a$t; -})(); +var _a$t; +class Null extends BaseBlock { + constructor(parameters = {}) { + super(parameters, ValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 5; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (this.lenBlock.length > 0) + this.warnings.push("Non-zero length of value block for Null type"); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + this.blockLength += inputLength; + if ((inputOffset + inputLength) > inputBuffer.byteLength) { + this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return -1; + } + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + const retBuf = new ArrayBuffer(2); + if (!sizeOnly) { + const retView = new Uint8Array(retBuf); + retView[0] = 0x05; + retView[1] = 0x00; + } + if (writer) { + writer.write(retBuf); + } + return retBuf; + } + onAsciiEncoding() { + return `${this.constructor.NAME}`; + } +} +_a$t = Null; +(() => { + typeStore.Null = _a$t; +})(); Null.NAME = "NULL"; -class LocalBooleanValueBlock extends HexBlock(ValueBlock) { - constructor({ value, ...parameters } = {}) { - super(parameters); - if (parameters.valueHex) { - this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex); - } - else { - this.valueHexView = new Uint8Array(1); - } - if (value) { - this.value = value; - } - } - get value() { - for (const octet of this.valueHexView) { - if (octet > 0) { - return true; - } - } - return false; - } - set value(value) { - this.valueHexView[0] = value ? 0xFF : 0x00; - } - fromBER(inputBuffer, inputOffset, inputLength) { - const inputView = BufferSourceConverter.toUint8Array(inputBuffer); - if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { - return -1; - } - this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength); - if (inputLength > 1) - this.warnings.push("Boolean value encoded in more then 1 octet"); - this.isHexOnly = true; - utilDecodeTC.call(this); - this.blockLength = inputLength; - return (inputOffset + inputLength); - } - toBER() { - return this.valueHexView.slice(); - } - toJSON() { - return { - ...super.toJSON(), - value: this.value, - }; - } -} +class LocalBooleanValueBlock extends HexBlock(ValueBlock) { + get value() { + for (const octet of this.valueHexView) { + if (octet > 0) { + return true; + } + } + return false; + } + set value(value) { + this.valueHexView[0] = value ? 0xFF : 0x00; + } + constructor({ value, ...parameters } = {}) { + super(parameters); + if (parameters.valueHex) { + this.valueHexView = BufferSourceConverter.toUint8Array(parameters.valueHex); + } + else { + this.valueHexView = new Uint8Array(1); + } + if (value) { + this.value = value; + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength); + if (inputLength > 1) + this.warnings.push("Boolean value encoded in more then 1 octet"); + this.isHexOnly = true; + utilDecodeTC.call(this); + this.blockLength = inputLength; + return (inputOffset + inputLength); + } + toBER() { + return this.valueHexView.slice(); + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} LocalBooleanValueBlock.NAME = "BooleanValueBlock"; -var _a$s; -class Boolean extends BaseBlock { - constructor(parameters = {}) { - super(parameters, LocalBooleanValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 1; - } - getValue() { - return this.valueBlock.value; - } - setValue(value) { - this.valueBlock.value = value; - } - onAsciiEncoding() { - return `${this.constructor.NAME} : ${this.getValue}`; - } -} -_a$s = Boolean; -(() => { - typeStore.Boolean = _a$s; -})(); +var _a$s; +class Boolean extends BaseBlock { + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + constructor(parameters = {}) { + super(parameters, LocalBooleanValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 1; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.getValue}`; + } +} +_a$s = Boolean; +(() => { + typeStore.Boolean = _a$s; +})(); Boolean.NAME = "BOOLEAN"; -class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) { - constructor({ isConstructed = false, ...parameters } = {}) { - super(parameters); - this.isConstructed = isConstructed; - } - fromBER(inputBuffer, inputOffset, inputLength) { - let resultOffset = 0; - if (this.isConstructed) { - this.isHexOnly = false; - resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); - if (resultOffset === -1) - return resultOffset; - for (let i = 0; i < this.value.length; i++) { - const currentBlockName = this.value[i].constructor.NAME; - if (currentBlockName === END_OF_CONTENT_NAME) { - if (this.isIndefiniteForm) - break; - else { - this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only"; - return -1; - } - } - if (currentBlockName !== OCTET_STRING_NAME) { - this.error = "OCTET STRING may consists of OCTET STRINGs only"; - return -1; - } - } - } - else { - this.isHexOnly = true; - resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); - this.blockLength = inputLength; - } - return resultOffset; - } - toBER(sizeOnly, writer) { - if (this.isConstructed) - return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); - return sizeOnly - ? new ArrayBuffer(this.valueHexView.byteLength) - : this.valueHexView.slice().buffer; - } - toJSON() { - return { - ...super.toJSON(), - isConstructed: this.isConstructed, - }; - } -} +class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ isConstructed = false, ...parameters } = {}) { + super(parameters); + this.isConstructed = isConstructed; + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = 0; + if (this.isConstructed) { + this.isHexOnly = false; + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) + return resultOffset; + for (let i = 0; i < this.value.length; i++) { + const currentBlockName = this.value[i].constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + if (currentBlockName !== OCTET_STRING_NAME) { + this.error = "OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + } + else { + this.isHexOnly = true; + resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + this.blockLength = inputLength; + } + return resultOffset; + } + toBER(sizeOnly, writer) { + if (this.isConstructed) + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + return sizeOnly + ? new ArrayBuffer(this.valueHexView.byteLength) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isConstructed: this.isConstructed, + }; + } +} LocalOctetStringValueBlock.NAME = "OctetStringValueBlock"; -var _a$r; -class OctetString extends BaseBlock { - constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { - var _b, _c; - (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); - super({ - idBlock: { - isConstructed: parameters.isConstructed, - ...idBlock, - }, - lenBlock: { - ...lenBlock, - isIndefiniteForm: !!parameters.isIndefiniteForm, - }, - ...parameters, - }, LocalOctetStringValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 4; - } - fromBER(inputBuffer, inputOffset, inputLength) { - this.valueBlock.isConstructed = this.idBlock.isConstructed; - this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; - if (inputLength === 0) { - if (this.idBlock.error.length === 0) - this.blockLength += this.idBlock.blockLength; - if (this.lenBlock.error.length === 0) - this.blockLength += this.lenBlock.blockLength; - return inputOffset; - } - if (!this.valueBlock.isConstructed) { - const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; - const buf = view.subarray(inputOffset, inputOffset + inputLength); - try { - if (buf.byteLength) { - const asn = localFromBER(buf, 0, buf.byteLength); - if (asn.offset !== -1 && asn.offset === inputLength) { - this.valueBlock.value = [asn.result]; - } - } - } - catch (e) { - } - } - return super.fromBER(inputBuffer, inputOffset, inputLength); - } - onAsciiEncoding() { - if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { - return Constructed.prototype.onAsciiEncoding.call(this); - } - return `${this.constructor.NAME} : ${Convert.ToHex(this.valueBlock.valueHexView)}`; - } - getValue() { - if (!this.idBlock.isConstructed) { - return this.valueBlock.valueHexView.slice().buffer; - } - const array = []; - for (const content of this.valueBlock.value) { - if (content instanceof OctetString) { - array.push(content.valueBlock.valueHexView); - } - } - return BufferSourceConverter.concat(array); - } -} -_a$r = OctetString; -(() => { - typeStore.OctetString = _a$r; -})(); +var _a$r; +class OctetString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalOctetStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 4; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + if (inputLength === 0) { + if (this.idBlock.error.length === 0) + this.blockLength += this.idBlock.blockLength; + if (this.lenBlock.error.length === 0) + this.blockLength += this.lenBlock.blockLength; + return inputOffset; + } + if (!this.valueBlock.isConstructed) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + const buf = view.subarray(inputOffset, inputOffset + inputLength); + try { + if (buf.byteLength) { + const asn = localFromBER(buf, 0, buf.byteLength); + if (asn.offset !== -1 && asn.offset === inputLength) { + this.valueBlock.value = [asn.result]; + } + } + } + catch { + } + } + return super.fromBER(inputBuffer, inputOffset, inputLength); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + const name = this.constructor.NAME; + const value = Convert.ToHex(this.valueBlock.valueHexView); + return `${name} : ${value}`; + } + getValue() { + if (!this.idBlock.isConstructed) { + return this.valueBlock.valueHexView.slice().buffer; + } + const array = []; + for (const content of this.valueBlock.value) { + if (content instanceof _a$r) { + array.push(content.valueBlock.valueHexView); + } + } + return BufferSourceConverter.concat(array); + } +} +_a$r = OctetString; +(() => { + typeStore.OctetString = _a$r; +})(); OctetString.NAME = OCTET_STRING_NAME; -class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) { - constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) { - super(parameters); - this.unusedBits = unusedBits; - this.isConstructed = isConstructed; - this.blockLength = this.valueHexView.byteLength; - } - fromBER(inputBuffer, inputOffset, inputLength) { - if (!inputLength) { - return inputOffset; - } - let resultOffset = -1; - if (this.isConstructed) { - resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); - if (resultOffset === -1) - return resultOffset; - for (const value of this.value) { - const currentBlockName = value.constructor.NAME; - if (currentBlockName === END_OF_CONTENT_NAME) { - if (this.isIndefiniteForm) - break; - else { - this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only"; - return -1; - } - } - if (currentBlockName !== BIT_STRING_NAME) { - this.error = "BIT STRING may consists of BIT STRINGs only"; - return -1; - } - const valueBlock = value.valueBlock; - if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) { - this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only"; - return -1; - } - this.unusedBits = valueBlock.unusedBits; - } - return resultOffset; - } - const inputView = BufferSourceConverter.toUint8Array(inputBuffer); - if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { - return -1; - } - const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); - this.unusedBits = intBuffer[0]; - if (this.unusedBits > 7) { - this.error = "Unused bits for BitString must be in range 0-7"; - return -1; - } - if (!this.unusedBits) { - const buf = intBuffer.subarray(1); - try { - if (buf.byteLength) { - const asn = localFromBER(buf, 0, buf.byteLength); - if (asn.offset !== -1 && asn.offset === (inputLength - 1)) { - this.value = [asn.result]; - } - } - } - catch (e) { - } - } - this.valueHexView = intBuffer.subarray(1); - this.blockLength = intBuffer.length; - return (inputOffset + inputLength); - } - toBER(sizeOnly, writer) { - if (this.isConstructed) { - return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); - } - if (sizeOnly) { - return new ArrayBuffer(this.valueHexView.byteLength + 1); - } - if (!this.valueHexView.byteLength) { - return EMPTY_BUFFER$1; - } - const retView = new Uint8Array(this.valueHexView.length + 1); - retView[0] = this.unusedBits; - retView.set(this.valueHexView, 1); - return retView.buffer; - } - toJSON() { - return { - ...super.toJSON(), - unusedBits: this.unusedBits, - isConstructed: this.isConstructed, - }; - } -} +class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) { + super(parameters); + this.unusedBits = unusedBits; + this.isConstructed = isConstructed; + this.blockLength = this.valueHexView.byteLength; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + let resultOffset = -1; + if (this.isConstructed) { + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) + return resultOffset; + for (const value of this.value) { + const currentBlockName = value.constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only"; + return -1; + } + } + if (currentBlockName !== BIT_STRING_NAME) { + this.error = "BIT STRING may consists of BIT STRINGs only"; + return -1; + } + const valueBlock = value.valueBlock; + if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) { + this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only"; + return -1; + } + this.unusedBits = valueBlock.unusedBits; + } + return resultOffset; + } + const inputView = BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.unusedBits = intBuffer[0]; + if (this.unusedBits > 7) { + this.error = "Unused bits for BitString must be in range 0-7"; + return -1; + } + if (!this.unusedBits) { + const buf = intBuffer.subarray(1); + try { + if (buf.byteLength) { + const asn = localFromBER(buf, 0, buf.byteLength); + if (asn.offset !== -1 && asn.offset === (inputLength - 1)) { + this.value = [asn.result]; + } + } + } + catch { + } + } + this.valueHexView = intBuffer.subarray(1); + this.blockLength = intBuffer.length; + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + if (this.isConstructed) { + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength + 1); + } + if (!this.valueHexView.byteLength) { + return EMPTY_BUFFER$1; + } + const retView = new Uint8Array(this.valueHexView.length + 1); + retView[0] = this.unusedBits; + retView.set(this.valueHexView, 1); + return retView.buffer; + } + toJSON() { + return { + ...super.toJSON(), + unusedBits: this.unusedBits, + isConstructed: this.isConstructed, + }; + } +} LocalBitStringValueBlock.NAME = "BitStringValueBlock"; -var _a$q; -class BitString extends BaseBlock { - constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { - var _b, _c; - (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); - super({ - idBlock: { - isConstructed: parameters.isConstructed, - ...idBlock, - }, - lenBlock: { - ...lenBlock, - isIndefiniteForm: !!parameters.isIndefiniteForm, - }, - ...parameters, - }, LocalBitStringValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 3; - } - fromBER(inputBuffer, inputOffset, inputLength) { - this.valueBlock.isConstructed = this.idBlock.isConstructed; - this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; - return super.fromBER(inputBuffer, inputOffset, inputLength); - } - onAsciiEncoding() { - if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { - return Constructed.prototype.onAsciiEncoding.call(this); - } - else { - const bits = []; - const valueHex = this.valueBlock.valueHexView; - for (const byte of valueHex) { - bits.push(byte.toString(2).padStart(8, "0")); - } - const bitsStr = bits.join(""); - return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`; - } - } -} -_a$q = BitString; -(() => { - typeStore.BitString = _a$q; -})(); +var _a$q; +class BitString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalBitStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 3; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + return super.fromBER(inputBuffer, inputOffset, inputLength); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + else { + const bits = []; + const valueHex = this.valueBlock.valueHexView; + for (const byte of valueHex) { + bits.push(byte.toString(2).padStart(8, "0")); + } + const bitsStr = bits.join(""); + const name = this.constructor.NAME; + const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits); + return `${name} : ${value}`; + } + } +} +_a$q = BitString; +(() => { + typeStore.BitString = _a$q; +})(); BitString.NAME = BIT_STRING_NAME; -var _a$p; -function viewAdd(first, second) { - const c = new Uint8Array([0]); - const firstView = new Uint8Array(first); - const secondView = new Uint8Array(second); - let firstViewCopy = firstView.slice(0); - const firstViewCopyLength = firstViewCopy.length - 1; - const secondViewCopy = secondView.slice(0); - const secondViewCopyLength = secondViewCopy.length - 1; - let value = 0; - const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength; - let counter = 0; - for (let i = max; i >= 0; i--, counter++) { - switch (true) { - case (counter < secondViewCopy.length): - value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0]; - break; - default: - value = firstViewCopy[firstViewCopyLength - counter] + c[0]; - } - c[0] = value / 10; - switch (true) { - case (counter >= firstViewCopy.length): - firstViewCopy = utilConcatView(new Uint8Array([value % 10]), firstViewCopy); - break; - default: - firstViewCopy[firstViewCopyLength - counter] = value % 10; - } - } - if (c[0] > 0) - firstViewCopy = utilConcatView(c, firstViewCopy); - return firstViewCopy; -} -function power2(n) { - if (n >= powers2.length) { - for (let p = powers2.length; p <= n; p++) { - const c = new Uint8Array([0]); - let digits = (powers2[p - 1]).slice(0); - for (let i = (digits.length - 1); i >= 0; i--) { - const newValue = new Uint8Array([(digits[i] << 1) + c[0]]); - c[0] = newValue[0] / 10; - digits[i] = newValue[0] % 10; - } - if (c[0] > 0) - digits = utilConcatView(c, digits); - powers2.push(digits); - } - } - return powers2[n]; -} -function viewSub(first, second) { - let b = 0; - const firstView = new Uint8Array(first); - const secondView = new Uint8Array(second); - const firstViewCopy = firstView.slice(0); - const firstViewCopyLength = firstViewCopy.length - 1; - const secondViewCopy = secondView.slice(0); - const secondViewCopyLength = secondViewCopy.length - 1; - let value; - let counter = 0; - for (let i = secondViewCopyLength; i >= 0; i--, counter++) { - value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b; - switch (true) { - case (value < 0): - b = 1; - firstViewCopy[firstViewCopyLength - counter] = value + 10; - break; - default: - b = 0; - firstViewCopy[firstViewCopyLength - counter] = value; - } - } - if (b > 0) { - for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) { - value = firstViewCopy[firstViewCopyLength - counter] - b; - if (value < 0) { - b = 1; - firstViewCopy[firstViewCopyLength - counter] = value + 10; - } - else { - b = 0; - firstViewCopy[firstViewCopyLength - counter] = value; - break; - } - } - } - return firstViewCopy.slice(); -} -class LocalIntegerValueBlock extends HexBlock(ValueBlock) { - constructor({ value, ...parameters } = {}) { - super(parameters); - this._valueDec = 0; - if (parameters.valueHex) { - this.setValueHex(); - } - if (value !== undefined) { - this.valueDec = value; - } - } - setValueHex() { - if (this.valueHexView.length >= 4) { - this.warnings.push("Too big Integer for decoding, hex only"); - this.isHexOnly = true; - this._valueDec = 0; - } - else { - this.isHexOnly = false; - if (this.valueHexView.length > 0) { - this._valueDec = utilDecodeTC.call(this); - } - } - } - set valueDec(v) { - this._valueDec = v; - this.isHexOnly = false; - this.valueHexView = new Uint8Array(utilEncodeTC(v)); - } - get valueDec() { - return this._valueDec; - } - fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) { - const offset = this.fromBER(inputBuffer, inputOffset, inputLength); - if (offset === -1) - return offset; - const view = this.valueHexView; - if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) { - this.valueHexView = view.subarray(1); - } - else { - if (expectedLength !== 0) { - if (view.length < expectedLength) { - if ((expectedLength - view.length) > 1) - expectedLength = view.length + 1; - this.valueHexView = view.subarray(expectedLength - view.length); - } - } - } - return offset; - } - toDER(sizeOnly = false) { - const view = this.valueHexView; - switch (true) { - case ((view[0] & 0x80) !== 0): - { - const updatedView = new Uint8Array(this.valueHexView.length + 1); - updatedView[0] = 0x00; - updatedView.set(view, 1); - this.valueHexView = updatedView; - } - break; - case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)): - { - this.valueHexView = this.valueHexView.subarray(1); - } - break; - } - return this.toBER(sizeOnly); - } - fromBER(inputBuffer, inputOffset, inputLength) { - const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); - if (resultOffset === -1) { - return resultOffset; - } - this.setValueHex(); - return resultOffset; - } - toBER(sizeOnly) { - return sizeOnly - ? new ArrayBuffer(this.valueHexView.length) - : this.valueHexView.slice().buffer; - } - toJSON() { - return { - ...super.toJSON(), - valueDec: this.valueDec, - }; - } - toString() { - const firstBit = (this.valueHexView.length * 8) - 1; - let digits = new Uint8Array((this.valueHexView.length * 8) / 3); - let bitNumber = 0; - let currentByte; - const asn1View = this.valueHexView; - let result = ""; - let flag = false; - for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) { - currentByte = asn1View[byteNumber]; - for (let i = 0; i < 8; i++) { - if ((currentByte & 1) === 1) { - switch (bitNumber) { - case firstBit: - digits = viewSub(power2(bitNumber), digits); - result = "-"; - break; - default: - digits = viewAdd(digits, power2(bitNumber)); - } - } - bitNumber++; - currentByte >>= 1; - } - } - for (let i = 0; i < digits.length; i++) { - if (digits[i]) - flag = true; - if (flag) - result += digitsString.charAt(digits[i]); - } - if (flag === false) - result += digitsString.charAt(0); - return result; - } -} -_a$p = LocalIntegerValueBlock; -LocalIntegerValueBlock.NAME = "IntegerValueBlock"; -(() => { - Object.defineProperty(_a$p.prototype, "valueHex", { - set: function (v) { - this.valueHexView = new Uint8Array(v); - this.setValueHex(); - }, - get: function () { - return this.valueHexView.slice().buffer; - }, - }); +var _a$p; +function viewAdd(first, second) { + const c = new Uint8Array([0]); + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + let firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value = 0; + const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength; + let counter = 0; + for (let i = max; i >= 0; i--, counter++) { + switch (true) { + case (counter < secondViewCopy.length): + value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0]; + break; + default: + value = firstViewCopy[firstViewCopyLength - counter] + c[0]; + } + c[0] = value / 10; + switch (true) { + case (counter >= firstViewCopy.length): + firstViewCopy = utilConcatView(new Uint8Array([value % 10]), firstViewCopy); + break; + default: + firstViewCopy[firstViewCopyLength - counter] = value % 10; + } + } + if (c[0] > 0) + firstViewCopy = utilConcatView(c, firstViewCopy); + return firstViewCopy; +} +function power2(n) { + if (n >= powers2.length) { + for (let p = powers2.length; p <= n; p++) { + const c = new Uint8Array([0]); + let digits = (powers2[p - 1]).slice(0); + for (let i = (digits.length - 1); i >= 0; i--) { + const newValue = new Uint8Array([(digits[i] << 1) + c[0]]); + c[0] = newValue[0] / 10; + digits[i] = newValue[0] % 10; + } + if (c[0] > 0) + digits = utilConcatView(c, digits); + powers2.push(digits); + } + } + return powers2[n]; +} +function viewSub(first, second) { + let b = 0; + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + const firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value; + let counter = 0; + for (let i = secondViewCopyLength; i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b; + switch (true) { + case (value < 0): + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + break; + default: + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + } + } + if (b > 0) { + for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - b; + if (value < 0) { + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + } + else { + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + break; + } + } + } + return firstViewCopy.slice(); +} +class LocalIntegerValueBlock extends HexBlock(ValueBlock) { + setValueHex() { + if (this.valueHexView.length >= 4) { + this.warnings.push("Too big Integer for decoding, hex only"); + this.isHexOnly = true; + this._valueDec = 0; + } + else { + this.isHexOnly = false; + if (this.valueHexView.length > 0) { + this._valueDec = utilDecodeTC.call(this); + } + } + } + constructor({ value, ...parameters } = {}) { + super(parameters); + this._valueDec = 0; + if (parameters.valueHex) { + this.setValueHex(); + } + if (value !== undefined) { + this.valueDec = value; + } + } + set valueDec(v) { + this._valueDec = v; + this.isHexOnly = false; + this.valueHexView = new Uint8Array(utilEncodeTC(v)); + } + get valueDec() { + return this._valueDec; + } + fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) { + const offset = this.fromBER(inputBuffer, inputOffset, inputLength); + if (offset === -1) + return offset; + const view = this.valueHexView; + if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) { + this.valueHexView = view.subarray(1); + } + else { + if (expectedLength !== 0) { + if (view.length < expectedLength) { + if ((expectedLength - view.length) > 1) + expectedLength = view.length + 1; + this.valueHexView = view.subarray(expectedLength - view.length); + } + } + } + return offset; + } + toDER(sizeOnly = false) { + const view = this.valueHexView; + switch (true) { + case ((view[0] & 0x80) !== 0): + { + const updatedView = new Uint8Array(this.valueHexView.length + 1); + updatedView[0] = 0x00; + updatedView.set(view, 1); + this.valueHexView = updatedView; + } + break; + case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)): + { + this.valueHexView = this.valueHexView.subarray(1); + } + break; + } + return this.toBER(sizeOnly); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) { + return resultOffset; + } + this.setValueHex(); + return resultOffset; + } + toBER(sizeOnly) { + return sizeOnly + ? new ArrayBuffer(this.valueHexView.length) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } + toString() { + const firstBit = (this.valueHexView.length * 8) - 1; + let digits = new Uint8Array((this.valueHexView.length * 8) / 3); + let bitNumber = 0; + let currentByte; + const asn1View = this.valueHexView; + let result = ""; + let flag = false; + for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) { + currentByte = asn1View[byteNumber]; + for (let i = 0; i < 8; i++) { + if ((currentByte & 1) === 1) { + switch (bitNumber) { + case firstBit: + digits = viewSub(power2(bitNumber), digits); + result = "-"; + break; + default: + digits = viewAdd(digits, power2(bitNumber)); + } + } + bitNumber++; + currentByte >>= 1; + } + } + for (let i = 0; i < digits.length; i++) { + if (digits[i]) + flag = true; + if (flag) + result += digitsString.charAt(digits[i]); + } + if (flag === false) + result += digitsString.charAt(0); + return result; + } +} +_a$p = LocalIntegerValueBlock; +LocalIntegerValueBlock.NAME = "IntegerValueBlock"; +(() => { + Object.defineProperty(_a$p.prototype, "valueHex", { + set: function (v) { + this.valueHexView = new Uint8Array(v); + this.setValueHex(); + }, + get: function () { + return this.valueHexView.slice().buffer; + }, + }); })(); -var _a$o; -class Integer extends BaseBlock { - constructor(parameters = {}) { - super(parameters, LocalIntegerValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 2; - } - toBigInt() { - assertBigInt(); - return BigInt(this.valueBlock.toString()); - } - static fromBigInt(value) { - assertBigInt(); - const bigIntValue = BigInt(value); - const writer = new ViewWriter(); - const hex = bigIntValue.toString(16).replace(/^-/, ""); - const view = new Uint8Array(Convert.FromHex(hex)); - if (bigIntValue < 0) { - const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0)); - first[0] |= 0x80; - const firstInt = BigInt(`0x${Convert.ToHex(first)}`); - const secondInt = firstInt + bigIntValue; - const second = BufferSourceConverter.toUint8Array(Convert.FromHex(secondInt.toString(16))); - second[0] |= 0x80; - writer.write(second); - } - else { - if (view[0] & 0x80) { - writer.write(new Uint8Array([0])); - } - writer.write(view); - } - const res = new Integer({ - valueHex: writer.final(), - }); - return res; - } - convertToDER() { - const integer = new Integer({ valueHex: this.valueBlock.valueHexView }); - integer.valueBlock.toDER(); - return integer; - } - convertFromDER() { - return new Integer({ - valueHex: this.valueBlock.valueHexView[0] === 0 - ? this.valueBlock.valueHexView.subarray(1) - : this.valueBlock.valueHexView, - }); - } - onAsciiEncoding() { - return `${this.constructor.NAME} : ${this.valueBlock.toString()}`; - } -} -_a$o = Integer; -(() => { - typeStore.Integer = _a$o; -})(); +var _a$o; +class Integer extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalIntegerValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 2; + } + toBigInt() { + assertBigInt(); + return BigInt(this.valueBlock.toString()); + } + static fromBigInt(value) { + assertBigInt(); + const bigIntValue = BigInt(value); + const writer = new ViewWriter(); + const hex = bigIntValue.toString(16).replace(/^-/, ""); + const view = new Uint8Array(Convert.FromHex(hex)); + if (bigIntValue < 0) { + const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0)); + first[0] |= 0x80; + const firstInt = BigInt(`0x${Convert.ToHex(first)}`); + const secondInt = firstInt + bigIntValue; + const second = BufferSourceConverter.toUint8Array(Convert.FromHex(secondInt.toString(16))); + second[0] |= 0x80; + writer.write(second); + } + else { + if (view[0] & 0x80) { + writer.write(new Uint8Array([0])); + } + writer.write(view); + } + const res = new _a$o({ valueHex: writer.final() }); + return res; + } + convertToDER() { + const integer = new _a$o({ valueHex: this.valueBlock.valueHexView }); + integer.valueBlock.toDER(); + return integer; + } + convertFromDER() { + return new _a$o({ + valueHex: this.valueBlock.valueHexView[0] === 0 + ? this.valueBlock.valueHexView.subarray(1) + : this.valueBlock.valueHexView, + }); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString()}`; + } +} +_a$o = Integer; +(() => { + typeStore.Integer = _a$o; +})(); Integer.NAME = "INTEGER"; -var _a$n; -class Enumerated extends Integer { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 10; - } -} -_a$n = Enumerated; -(() => { - typeStore.Enumerated = _a$n; -})(); +var _a$n; +class Enumerated extends Integer { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 10; + } +} +_a$n = Enumerated; +(() => { + typeStore.Enumerated = _a$n; +})(); Enumerated.NAME = "ENUMERATED"; -class LocalSidValueBlock extends HexBlock(ValueBlock) { - constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) { - super(parameters); - this.valueDec = valueDec; - this.isFirstSid = isFirstSid; - } - fromBER(inputBuffer, inputOffset, inputLength) { - if (!inputLength) { - return inputOffset; - } - const inputView = BufferSourceConverter.toUint8Array(inputBuffer); - if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { - return -1; - } - const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); - this.valueHexView = new Uint8Array(inputLength); - for (let i = 0; i < inputLength; i++) { - this.valueHexView[i] = intBuffer[i] & 0x7F; - this.blockLength++; - if ((intBuffer[i] & 0x80) === 0x00) - break; - } - const tempView = new Uint8Array(this.blockLength); - for (let i = 0; i < this.blockLength; i++) { - tempView[i] = this.valueHexView[i]; - } - this.valueHexView = tempView; - if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { - this.error = "End of input reached before message was fully decoded"; - return -1; - } - if (this.valueHexView[0] === 0x00) - this.warnings.push("Needlessly long format of SID encoding"); - if (this.blockLength <= 8) - this.valueDec = utilFromBase(this.valueHexView, 7); - else { - this.isHexOnly = true; - this.warnings.push("Too big SID for decoding, hex only"); - } - return (inputOffset + this.blockLength); - } - set valueBigInt(value) { - assertBigInt(); - let bits = BigInt(value).toString(2); - while (bits.length % 7) { - bits = "0" + bits; - } - const bytes = new Uint8Array(bits.length / 7); - for (let i = 0; i < bytes.length; i++) { - bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0); - } - this.fromBER(bytes.buffer, 0, bytes.length); - } - toBER(sizeOnly) { - if (this.isHexOnly) { - if (sizeOnly) - return (new ArrayBuffer(this.valueHexView.byteLength)); - const curView = this.valueHexView; - const retView = new Uint8Array(this.blockLength); - for (let i = 0; i < (this.blockLength - 1); i++) - retView[i] = curView[i] | 0x80; - retView[this.blockLength - 1] = curView[this.blockLength - 1]; - return retView.buffer; - } - const encodedBuf = utilToBase(this.valueDec, 7); - if (encodedBuf.byteLength === 0) { - this.error = "Error during encoding SID value"; - return EMPTY_BUFFER$1; - } - const retView = new Uint8Array(encodedBuf.byteLength); - if (!sizeOnly) { - const encodedView = new Uint8Array(encodedBuf); - const len = encodedBuf.byteLength - 1; - for (let i = 0; i < len; i++) - retView[i] = encodedView[i] | 0x80; - retView[len] = encodedView[len]; - } - return retView; - } - toString() { - let result = ""; - if (this.isHexOnly) - result = Convert.ToHex(this.valueHexView); - else { - if (this.isFirstSid) { - let sidValue = this.valueDec; - if (this.valueDec <= 39) - result = "0."; - else { - if (this.valueDec <= 79) { - result = "1."; - sidValue -= 40; - } - else { - result = "2."; - sidValue -= 80; - } - } - result += sidValue.toString(); - } - else - result = this.valueDec.toString(); - } - return result; - } - toJSON() { - return { - ...super.toJSON(), - valueDec: this.valueDec, - isFirstSid: this.isFirstSid, - }; - } -} +class LocalSidValueBlock extends HexBlock(ValueBlock) { + constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + this.isFirstSid = isFirstSid; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + const inputView = BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) { + tempView[i] = this.valueHexView[i]; + } + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + set valueBigInt(value) { + assertBigInt(); + let bits = BigInt(value).toString(2); + while (bits.length % 7) { + bits = "0" + bits; + } + const bytes = new Uint8Array(bits.length / 7); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0); + } + this.fromBER(bytes.buffer, 0, bytes.length); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER$1; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = Convert.ToHex(this.valueHexView); + else { + if (this.isFirstSid) { + let sidValue = this.valueDec; + if (this.valueDec <= 39) + result = "0."; + else { + if (this.valueDec <= 79) { + result = "1."; + sidValue -= 40; + } + else { + result = "2."; + sidValue -= 80; + } + } + result += sidValue.toString(); + } + else + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + isFirstSid: this.isFirstSid, + }; + } +} LocalSidValueBlock.NAME = "sidBlock"; -class LocalObjectIdentifierValueBlock extends ValueBlock { - constructor({ value = EMPTY_STRING$1, ...parameters } = {}) { - super(parameters); - this.value = []; - if (value) { - this.fromString(value); - } - } - fromBER(inputBuffer, inputOffset, inputLength) { - let resultOffset = inputOffset; - while (inputLength > 0) { - const sidBlock = new LocalSidValueBlock(); - resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); - if (resultOffset === -1) { - this.blockLength = 0; - this.error = sidBlock.error; - return resultOffset; - } - if (this.value.length === 0) - sidBlock.isFirstSid = true; - this.blockLength += sidBlock.blockLength; - inputLength -= sidBlock.blockLength; - this.value.push(sidBlock); - } - return resultOffset; - } - toBER(sizeOnly) { - const retBuffers = []; - for (let i = 0; i < this.value.length; i++) { - const valueBuf = this.value[i].toBER(sizeOnly); - if (valueBuf.byteLength === 0) { - this.error = this.value[i].error; - return EMPTY_BUFFER$1; - } - retBuffers.push(valueBuf); - } - return concat(retBuffers); - } - fromString(string) { - this.value = []; - let pos1 = 0; - let pos2 = 0; - let sid = ""; - let flag = false; - do { - pos2 = string.indexOf(".", pos1); - if (pos2 === -1) - sid = string.substring(pos1); - else - sid = string.substring(pos1, pos2); - pos1 = pos2 + 1; - if (flag) { - const sidBlock = this.value[0]; - let plus = 0; - switch (sidBlock.valueDec) { - case 0: - break; - case 1: - plus = 40; - break; - case 2: - plus = 80; - break; - default: - this.value = []; - return; - } - const parsedSID = parseInt(sid, 10); - if (isNaN(parsedSID)) - return; - sidBlock.valueDec = parsedSID + plus; - flag = false; - } - else { - const sidBlock = new LocalSidValueBlock(); - if (sid > Number.MAX_SAFE_INTEGER) { - assertBigInt(); - const sidValue = BigInt(sid); - sidBlock.valueBigInt = sidValue; - } - else { - sidBlock.valueDec = parseInt(sid, 10); - if (isNaN(sidBlock.valueDec)) - return; - } - if (!this.value.length) { - sidBlock.isFirstSid = true; - flag = true; - } - this.value.push(sidBlock); - } - } while (pos2 !== -1); - } - toString() { - let result = ""; - let isHexOnly = false; - for (let i = 0; i < this.value.length; i++) { - isHexOnly = this.value[i].isHexOnly; - let sidStr = this.value[i].toString(); - if (i !== 0) - result = `${result}.`; - if (isHexOnly) { - sidStr = `{${sidStr}}`; - if (this.value[i].isFirstSid) - result = `2.{${sidStr} - 80}`; - else - result += sidStr; - } - else - result += sidStr; - } - return result; - } - toJSON() { - const object = { - ...super.toJSON(), - value: this.toString(), - sidArray: [], - }; - for (let i = 0; i < this.value.length; i++) { - object.sidArray.push(this.value[i].toJSON()); - } - return object; - } -} +class LocalObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING$1, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + if (this.value.length === 0) + sidBlock.isFirstSid = true; + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER$1; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + let flag = false; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + if (flag) { + const sidBlock = this.value[0]; + let plus = 0; + switch (sidBlock.valueDec) { + case 0: + break; + case 1: + plus = 40; + break; + case 2: + plus = 80; + break; + default: + this.value = []; + return; + } + const parsedSID = parseInt(sid, 10); + if (isNaN(parsedSID)) + return; + sidBlock.valueDec = parsedSID + plus; + flag = false; + } + else { + const sidBlock = new LocalSidValueBlock(); + if (sid > Number.MAX_SAFE_INTEGER) { + assertBigInt(); + const sidValue = BigInt(sid); + sidBlock.valueBigInt = sidValue; + } + else { + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return; + } + if (!this.value.length) { + sidBlock.isFirstSid = true; + flag = true; + } + this.value.push(sidBlock); + } + } while (pos2 !== -1); + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + if (this.value[i].isFirstSid) + result = `2.{${sidStr} - 80}`; + else + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) { + object.sidArray.push(this.value[i].toJSON()); + } + return object; + } +} LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock"; -var _a$m; -class ObjectIdentifier extends BaseBlock { - constructor(parameters = {}) { - super(parameters, LocalObjectIdentifierValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 6; - } - getValue() { - return this.valueBlock.toString(); - } - setValue(value) { - this.valueBlock.fromString(value); - } - onAsciiEncoding() { - return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; - } - toJSON() { - return { - ...super.toJSON(), - value: this.getValue(), - }; - } -} -_a$m = ObjectIdentifier; -(() => { - typeStore.ObjectIdentifier = _a$m; -})(); -ObjectIdentifier.NAME = "OBJECT IDENTIFIER"; - -class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) { - constructor({ valueDec = 0, ...parameters } = {}) { - super(parameters); - this.valueDec = valueDec; - } - fromBER(inputBuffer, inputOffset, inputLength) { - if (inputLength === 0) - return inputOffset; - const inputView = BufferSourceConverter.toUint8Array(inputBuffer); - if (!checkBufferParams(this, inputView, inputOffset, inputLength)) - return -1; - const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); - this.valueHexView = new Uint8Array(inputLength); - for (let i = 0; i < inputLength; i++) { - this.valueHexView[i] = intBuffer[i] & 0x7F; - this.blockLength++; - if ((intBuffer[i] & 0x80) === 0x00) - break; - } - const tempView = new Uint8Array(this.blockLength); - for (let i = 0; i < this.blockLength; i++) - tempView[i] = this.valueHexView[i]; - this.valueHexView = tempView; - if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { - this.error = "End of input reached before message was fully decoded"; - return -1; - } - if (this.valueHexView[0] === 0x00) - this.warnings.push("Needlessly long format of SID encoding"); - if (this.blockLength <= 8) - this.valueDec = utilFromBase(this.valueHexView, 7); - else { - this.isHexOnly = true; - this.warnings.push("Too big SID for decoding, hex only"); - } - return (inputOffset + this.blockLength); - } - toBER(sizeOnly) { - if (this.isHexOnly) { - if (sizeOnly) - return (new ArrayBuffer(this.valueHexView.byteLength)); - const curView = this.valueHexView; - const retView = new Uint8Array(this.blockLength); - for (let i = 0; i < (this.blockLength - 1); i++) - retView[i] = curView[i] | 0x80; - retView[this.blockLength - 1] = curView[this.blockLength - 1]; - return retView.buffer; - } - const encodedBuf = utilToBase(this.valueDec, 7); - if (encodedBuf.byteLength === 0) { - this.error = "Error during encoding SID value"; - return EMPTY_BUFFER$1; - } - const retView = new Uint8Array(encodedBuf.byteLength); - if (!sizeOnly) { - const encodedView = new Uint8Array(encodedBuf); - const len = encodedBuf.byteLength - 1; - for (let i = 0; i < len; i++) - retView[i] = encodedView[i] | 0x80; - retView[len] = encodedView[len]; - } - return retView.buffer; - } - toString() { - let result = ""; - if (this.isHexOnly) - result = Convert.ToHex(this.valueHexView); - else { - result = this.valueDec.toString(); - } - return result; - } - toJSON() { - return { - ...super.toJSON(), - valueDec: this.valueDec, - }; - } -} +var _a$m; +class ObjectIdentifier extends BaseBlock { + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + constructor(parameters = {}) { + super(parameters, LocalObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 6; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$m = ObjectIdentifier; +(() => { + typeStore.ObjectIdentifier = _a$m; +})(); +ObjectIdentifier.NAME = "OBJECT IDENTIFIER"; + +class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) { + constructor({ valueDec = 0, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (inputLength === 0) + return inputOffset; + const inputView = BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) + return -1; + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) + tempView[i] = this.valueHexView[i]; + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER$1; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView.buffer; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = Convert.ToHex(this.valueHexView); + else { + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } +} LocalRelativeSidValueBlock.NAME = "relativeSidBlock"; -class LocalRelativeObjectIdentifierValueBlock extends ValueBlock { - constructor({ value = EMPTY_STRING$1, ...parameters } = {}) { - super(parameters); - this.value = []; - if (value) { - this.fromString(value); - } - } - fromBER(inputBuffer, inputOffset, inputLength) { - let resultOffset = inputOffset; - while (inputLength > 0) { - const sidBlock = new LocalRelativeSidValueBlock(); - resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); - if (resultOffset === -1) { - this.blockLength = 0; - this.error = sidBlock.error; - return resultOffset; - } - this.blockLength += sidBlock.blockLength; - inputLength -= sidBlock.blockLength; - this.value.push(sidBlock); - } - return resultOffset; - } - toBER(sizeOnly, writer) { - const retBuffers = []; - for (let i = 0; i < this.value.length; i++) { - const valueBuf = this.value[i].toBER(sizeOnly); - if (valueBuf.byteLength === 0) { - this.error = this.value[i].error; - return EMPTY_BUFFER$1; - } - retBuffers.push(valueBuf); - } - return concat(retBuffers); - } - fromString(string) { - this.value = []; - let pos1 = 0; - let pos2 = 0; - let sid = ""; - do { - pos2 = string.indexOf(".", pos1); - if (pos2 === -1) - sid = string.substring(pos1); - else - sid = string.substring(pos1, pos2); - pos1 = pos2 + 1; - const sidBlock = new LocalRelativeSidValueBlock(); - sidBlock.valueDec = parseInt(sid, 10); - if (isNaN(sidBlock.valueDec)) - return true; - this.value.push(sidBlock); - } while (pos2 !== -1); - return true; - } - toString() { - let result = ""; - let isHexOnly = false; - for (let i = 0; i < this.value.length; i++) { - isHexOnly = this.value[i].isHexOnly; - let sidStr = this.value[i].toString(); - if (i !== 0) - result = `${result}.`; - if (isHexOnly) { - sidStr = `{${sidStr}}`; - result += sidStr; - } - else - result += sidStr; - } - return result; - } - toJSON() { - const object = { - ...super.toJSON(), - value: this.toString(), - sidArray: [], - }; - for (let i = 0; i < this.value.length; i++) - object.sidArray.push(this.value[i].toJSON()); - return object; - } -} +class LocalRelativeObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING$1, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalRelativeSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly, _writer) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER$1; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + const sidBlock = new LocalRelativeSidValueBlock(); + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return true; + this.value.push(sidBlock); + } while (pos2 !== -1); + return true; + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) + object.sidArray.push(this.value[i].toJSON()); + return object; + } +} LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock"; -var _a$l; -class RelativeObjectIdentifier extends BaseBlock { - constructor(parameters = {}) { - super(parameters, LocalRelativeObjectIdentifierValueBlock); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 13; - } - getValue() { - return this.valueBlock.toString(); - } - setValue(value) { - this.valueBlock.fromString(value); - } - onAsciiEncoding() { - return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; - } - toJSON() { - return { - ...super.toJSON(), - value: this.getValue(), - }; - } -} -_a$l = RelativeObjectIdentifier; -(() => { - typeStore.RelativeObjectIdentifier = _a$l; -})(); +var _a$l; +class RelativeObjectIdentifier extends BaseBlock { + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + constructor(parameters = {}) { + super(parameters, LocalRelativeObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 13; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$l = RelativeObjectIdentifier; +(() => { + typeStore.RelativeObjectIdentifier = _a$l; +})(); RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier"; -var _a$k; -class Sequence extends Constructed { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 16; - } -} -_a$k = Sequence; -(() => { - typeStore.Sequence = _a$k; -})(); +var _a$k; +class Sequence extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 16; + } +} +_a$k = Sequence; +(() => { + typeStore.Sequence = _a$k; +})(); Sequence.NAME = "SEQUENCE"; -var _a$j; -class Set extends Constructed { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 17; - } -} -_a$j = Set; -(() => { - typeStore.Set = _a$j; -})(); +var _a$j; +class Set extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 17; + } +} +_a$j = Set; +(() => { + typeStore.Set = _a$j; +})(); Set.NAME = "SET"; -class LocalStringValueBlock extends HexBlock(ValueBlock) { - constructor({ ...parameters } = {}) { - super(parameters); - this.isHexOnly = true; - this.value = EMPTY_STRING$1; - } - toJSON() { - return { - ...super.toJSON(), - value: this.value, - }; - } -} +class LocalStringValueBlock extends HexBlock(ValueBlock) { + constructor({ ...parameters } = {}) { + super(parameters); + this.isHexOnly = true; + this.value = EMPTY_STRING$1; + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} LocalStringValueBlock.NAME = "StringValueBlock"; -class LocalSimpleStringValueBlock extends LocalStringValueBlock { -} +class LocalSimpleStringValueBlock extends LocalStringValueBlock { +} LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock"; -class LocalSimpleStringBlock extends BaseStringBlock { - constructor({ ...parameters } = {}) { - super(parameters, LocalSimpleStringValueBlock); - } - fromBuffer(inputBuffer) { - this.valueBlock.value = String.fromCharCode.apply(null, BufferSourceConverter.toUint8Array(inputBuffer)); - } - fromString(inputString) { - const strLen = inputString.length; - const view = this.valueBlock.valueHexView = new Uint8Array(strLen); - for (let i = 0; i < strLen; i++) - view[i] = inputString.charCodeAt(i); - this.valueBlock.value = inputString; - } -} +class LocalSimpleStringBlock extends BaseStringBlock { + constructor({ ...parameters } = {}) { + super(parameters, LocalSimpleStringValueBlock); + } + fromBuffer(inputBuffer) { + this.valueBlock.value = String.fromCharCode.apply(null, BufferSourceConverter.toUint8Array(inputBuffer)); + } + fromString(inputString) { + const strLen = inputString.length; + const view = this.valueBlock.valueHexView = new Uint8Array(strLen); + for (let i = 0; i < strLen; i++) + view[i] = inputString.charCodeAt(i); + this.valueBlock.value = inputString; + } +} LocalSimpleStringBlock.NAME = "SIMPLE STRING"; -class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { - fromBuffer(inputBuffer) { - this.valueBlock.valueHexView = BufferSourceConverter.toUint8Array(inputBuffer); - try { - this.valueBlock.value = Convert.ToUtf8String(inputBuffer); - } - catch (ex) { - this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`); - this.valueBlock.value = Convert.ToBinary(inputBuffer); - } - } - fromString(inputString) { - this.valueBlock.valueHexView = new Uint8Array(Convert.FromUtf8String(inputString)); - this.valueBlock.value = inputString; - } -} +class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.valueHexView = BufferSourceConverter.toUint8Array(inputBuffer); + try { + this.valueBlock.value = Convert.ToUtf8String(inputBuffer); + } + catch (ex) { + this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`); + this.valueBlock.value = Convert.ToBinary(inputBuffer); + } + } + fromString(inputString) { + this.valueBlock.valueHexView = new Uint8Array(Convert.FromUtf8String(inputString)); + this.valueBlock.value = inputString; + } +} LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock"; -var _a$i; -class Utf8String extends LocalUtf8StringValueBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 12; - } -} -_a$i = Utf8String; -(() => { - typeStore.Utf8String = _a$i; -})(); +var _a$i; +class Utf8String extends LocalUtf8StringValueBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 12; + } +} +_a$i = Utf8String; +(() => { + typeStore.Utf8String = _a$i; +})(); Utf8String.NAME = "UTF8String"; -class LocalBmpStringValueBlock extends LocalSimpleStringBlock { - fromBuffer(inputBuffer) { - this.valueBlock.value = Convert.ToUtf16String(inputBuffer); - this.valueBlock.valueHexView = BufferSourceConverter.toUint8Array(inputBuffer); - } - fromString(inputString) { - this.valueBlock.value = inputString; - this.valueBlock.valueHexView = new Uint8Array(Convert.FromUtf16String(inputString)); - } -} +class LocalBmpStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.value = Convert.ToUtf16String(inputBuffer); + this.valueBlock.valueHexView = BufferSourceConverter.toUint8Array(inputBuffer); + } + fromString(inputString) { + this.valueBlock.value = inputString; + this.valueBlock.valueHexView = new Uint8Array(Convert.FromUtf16String(inputString)); + } +} LocalBmpStringValueBlock.NAME = "BmpStringValueBlock"; -var _a$h; -class BmpString extends LocalBmpStringValueBlock { - constructor({ ...parameters } = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 30; - } -} -_a$h = BmpString; -(() => { - typeStore.BmpString = _a$h; -})(); +var _a$h; +class BmpString extends LocalBmpStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 30; + } +} +_a$h = BmpString; +(() => { + typeStore.BmpString = _a$h; +})(); BmpString.NAME = "BMPString"; -class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { - fromBuffer(inputBuffer) { - const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0); - const valueView = new Uint8Array(copyBuffer); - for (let i = 0; i < valueView.length; i += 4) { - valueView[i] = valueView[i + 3]; - valueView[i + 1] = valueView[i + 2]; - valueView[i + 2] = 0x00; - valueView[i + 3] = 0x00; - } - this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer)); - } - fromString(inputString) { - const strLength = inputString.length; - const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4); - for (let i = 0; i < strLength; i++) { - const codeBuf = utilToBase(inputString.charCodeAt(i), 8); - const codeView = new Uint8Array(codeBuf); - if (codeView.length > 4) - continue; - const dif = 4 - codeView.length; - for (let j = (codeView.length - 1); j >= 0; j--) - valueHexView[i * 4 + j + dif] = codeView[j]; - } - this.valueBlock.value = inputString; - } -} +class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0); + const valueView = new Uint8Array(copyBuffer); + for (let i = 0; i < valueView.length; i += 4) { + valueView[i] = valueView[i + 3]; + valueView[i + 1] = valueView[i + 2]; + valueView[i + 2] = 0x00; + valueView[i + 3] = 0x00; + } + this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer)); + } + fromString(inputString) { + const strLength = inputString.length; + const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4); + for (let i = 0; i < strLength; i++) { + const codeBuf = utilToBase(inputString.charCodeAt(i), 8); + const codeView = new Uint8Array(codeBuf); + if (codeView.length > 4) + continue; + const dif = 4 - codeView.length; + for (let j = (codeView.length - 1); j >= 0; j--) + valueHexView[i * 4 + j + dif] = codeView[j]; + } + this.valueBlock.value = inputString; + } +} LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock"; -var _a$g; -class UniversalString extends LocalUniversalStringValueBlock { - constructor({ ...parameters } = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 28; - } -} -_a$g = UniversalString; -(() => { - typeStore.UniversalString = _a$g; -})(); +var _a$g; +class UniversalString extends LocalUniversalStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 28; + } +} +_a$g = UniversalString; +(() => { + typeStore.UniversalString = _a$g; +})(); UniversalString.NAME = "UniversalString"; -var _a$f; -class NumericString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 18; - } -} -_a$f = NumericString; -(() => { - typeStore.NumericString = _a$f; -})(); +var _a$f; +class NumericString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 18; + } +} +_a$f = NumericString; +(() => { + typeStore.NumericString = _a$f; +})(); NumericString.NAME = "NumericString"; -var _a$e; -class PrintableString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 19; - } -} -_a$e = PrintableString; -(() => { - typeStore.PrintableString = _a$e; -})(); +var _a$e; +class PrintableString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 19; + } +} +_a$e = PrintableString; +(() => { + typeStore.PrintableString = _a$e; +})(); PrintableString.NAME = "PrintableString"; -var _a$d; -class TeletexString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 20; - } -} -_a$d = TeletexString; -(() => { - typeStore.TeletexString = _a$d; -})(); +var _a$d; +class TeletexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 20; + } +} +_a$d = TeletexString; +(() => { + typeStore.TeletexString = _a$d; +})(); TeletexString.NAME = "TeletexString"; -var _a$c; -class VideotexString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 21; - } -} -_a$c = VideotexString; -(() => { - typeStore.VideotexString = _a$c; -})(); +var _a$c; +class VideotexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 21; + } +} +_a$c = VideotexString; +(() => { + typeStore.VideotexString = _a$c; +})(); VideotexString.NAME = "VideotexString"; -var _a$b; -class IA5String extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 22; - } -} -_a$b = IA5String; -(() => { - typeStore.IA5String = _a$b; -})(); +var _a$b; +class IA5String extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 22; + } +} +_a$b = IA5String; +(() => { + typeStore.IA5String = _a$b; +})(); IA5String.NAME = "IA5String"; -var _a$a; -class GraphicString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 25; - } -} -_a$a = GraphicString; -(() => { - typeStore.GraphicString = _a$a; -})(); +var _a$a; +class GraphicString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 25; + } +} +_a$a = GraphicString; +(() => { + typeStore.GraphicString = _a$a; +})(); GraphicString.NAME = "GraphicString"; -var _a$9; -class VisibleString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 26; - } -} -_a$9 = VisibleString; -(() => { - typeStore.VisibleString = _a$9; -})(); +var _a$9; +class VisibleString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 26; + } +} +_a$9 = VisibleString; +(() => { + typeStore.VisibleString = _a$9; +})(); VisibleString.NAME = "VisibleString"; -var _a$8; -class GeneralString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 27; - } -} -_a$8 = GeneralString; -(() => { - typeStore.GeneralString = _a$8; -})(); +var _a$8; +class GeneralString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 27; + } +} +_a$8 = GeneralString; +(() => { + typeStore.GeneralString = _a$8; +})(); GeneralString.NAME = "GeneralString"; -var _a$7; -class CharacterString extends LocalSimpleStringBlock { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 29; - } -} -_a$7 = CharacterString; -(() => { - typeStore.CharacterString = _a$7; -})(); +var _a$7; +class CharacterString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 29; + } +} +_a$7 = CharacterString; +(() => { + typeStore.CharacterString = _a$7; +})(); CharacterString.NAME = "CharacterString"; -var _a$6; -class UTCTime extends VisibleString { - constructor({ value, valueDate, ...parameters } = {}) { - super(parameters); - this.year = 0; - this.month = 0; - this.day = 0; - this.hour = 0; - this.minute = 0; - this.second = 0; - if (value) { - this.fromString(value); - this.valueBlock.valueHexView = new Uint8Array(value.length); - for (let i = 0; i < value.length; i++) - this.valueBlock.valueHexView[i] = value.charCodeAt(i); - } - if (valueDate) { - this.fromDate(valueDate); - this.valueBlock.valueHexView = new Uint8Array(this.toBuffer()); - } - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 23; - } - fromBuffer(inputBuffer) { - this.fromString(String.fromCharCode.apply(null, BufferSourceConverter.toUint8Array(inputBuffer))); - } - toBuffer() { - const str = this.toString(); - const buffer = new ArrayBuffer(str.length); - const view = new Uint8Array(buffer); - for (let i = 0; i < str.length; i++) - view[i] = str.charCodeAt(i); - return buffer; - } - fromDate(inputDate) { - this.year = inputDate.getUTCFullYear(); - this.month = inputDate.getUTCMonth() + 1; - this.day = inputDate.getUTCDate(); - this.hour = inputDate.getUTCHours(); - this.minute = inputDate.getUTCMinutes(); - this.second = inputDate.getUTCSeconds(); - } - toDate() { - return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second))); - } - fromString(inputString) { - const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig; - const parserArray = parser.exec(inputString); - if (parserArray === null) { - this.error = "Wrong input string for conversion"; - return; - } - const year = parseInt(parserArray[1], 10); - if (year >= 50) - this.year = 1900 + year; - else - this.year = 2000 + year; - this.month = parseInt(parserArray[2], 10); - this.day = parseInt(parserArray[3], 10); - this.hour = parseInt(parserArray[4], 10); - this.minute = parseInt(parserArray[5], 10); - this.second = parseInt(parserArray[6], 10); - } - toString(encoding = "iso") { - if (encoding === "iso") { - const outputArray = new Array(7); - outputArray[0] = padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2); - outputArray[1] = padNumber(this.month, 2); - outputArray[2] = padNumber(this.day, 2); - outputArray[3] = padNumber(this.hour, 2); - outputArray[4] = padNumber(this.minute, 2); - outputArray[5] = padNumber(this.second, 2); - outputArray[6] = "Z"; - return outputArray.join(""); - } - return super.toString(encoding); - } - onAsciiEncoding() { - return `${this.constructor.NAME} : ${this.toDate().toISOString()}`; - } - toJSON() { - return { - ...super.toJSON(), - year: this.year, - month: this.month, - day: this.day, - hour: this.hour, - minute: this.minute, - second: this.second, - }; - } -} -_a$6 = UTCTime; -(() => { - typeStore.UTCTime = _a$6; -})(); +var _a$6; +class UTCTime extends VisibleString { + constructor({ value, valueDate, ...parameters } = {}) { + super(parameters); + this.year = 0; + this.month = 0; + this.day = 0; + this.hour = 0; + this.minute = 0; + this.second = 0; + if (value) { + this.fromString(value); + this.valueBlock.valueHexView = new Uint8Array(value.length); + for (let i = 0; i < value.length; i++) + this.valueBlock.valueHexView[i] = value.charCodeAt(i); + } + if (valueDate) { + this.fromDate(valueDate); + this.valueBlock.valueHexView = new Uint8Array(this.toBuffer()); + } + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 23; + } + fromBuffer(inputBuffer) { + this.fromString(String.fromCharCode.apply(null, BufferSourceConverter.toUint8Array(inputBuffer))); + } + toBuffer() { + const str = this.toString(); + const buffer = new ArrayBuffer(str.length); + const view = new Uint8Array(buffer); + for (let i = 0; i < str.length; i++) + view[i] = str.charCodeAt(i); + return buffer; + } + fromDate(inputDate) { + this.year = inputDate.getUTCFullYear(); + this.month = inputDate.getUTCMonth() + 1; + this.day = inputDate.getUTCDate(); + this.hour = inputDate.getUTCHours(); + this.minute = inputDate.getUTCMinutes(); + this.second = inputDate.getUTCSeconds(); + } + toDate() { + return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second))); + } + fromString(inputString) { + const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig; + const parserArray = parser.exec(inputString); + if (parserArray === null) { + this.error = "Wrong input string for conversion"; + return; + } + const year = parseInt(parserArray[1], 10); + if (year >= 50) + this.year = 1900 + year; + else + this.year = 2000 + year; + this.month = parseInt(parserArray[2], 10); + this.day = parseInt(parserArray[3], 10); + this.hour = parseInt(parserArray[4], 10); + this.minute = parseInt(parserArray[5], 10); + this.second = parseInt(parserArray[6], 10); + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = new Array(7); + outputArray[0] = padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2); + outputArray[1] = padNumber(this.month, 2); + outputArray[2] = padNumber(this.day, 2); + outputArray[3] = padNumber(this.hour, 2); + outputArray[4] = padNumber(this.minute, 2); + outputArray[5] = padNumber(this.second, 2); + outputArray[6] = "Z"; + return outputArray.join(""); + } + return super.toString(encoding); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.toDate().toISOString()}`; + } + toJSON() { + return { + ...super.toJSON(), + year: this.year, + month: this.month, + day: this.day, + hour: this.hour, + minute: this.minute, + second: this.second, + }; + } +} +_a$6 = UTCTime; +(() => { + typeStore.UTCTime = _a$6; +})(); UTCTime.NAME = "UTCTime"; -var _a$5; -class GeneralizedTime extends UTCTime { - constructor(parameters = {}) { - var _b; - super(parameters); - (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 24; - } - fromDate(inputDate) { - super.fromDate(inputDate); - this.millisecond = inputDate.getUTCMilliseconds(); - } - toDate() { - return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond))); - } - fromString(inputString) { - let isUTC = false; - let timeString = ""; - let dateTimeString = ""; - let fractionPart = 0; - let parser; - let hourDifference = 0; - let minuteDifference = 0; - if (inputString[inputString.length - 1] === "Z") { - timeString = inputString.substring(0, inputString.length - 1); - isUTC = true; - } - else { - const number = new Number(inputString[inputString.length - 1]); - if (isNaN(number.valueOf())) - throw new Error("Wrong input string for conversion"); - timeString = inputString; - } - if (isUTC) { - if (timeString.indexOf("+") !== -1) - throw new Error("Wrong input string for conversion"); - if (timeString.indexOf("-") !== -1) - throw new Error("Wrong input string for conversion"); - } - else { - let multiplier = 1; - let differencePosition = timeString.indexOf("+"); - let differenceString = ""; - if (differencePosition === -1) { - differencePosition = timeString.indexOf("-"); - multiplier = -1; - } - if (differencePosition !== -1) { - differenceString = timeString.substring(differencePosition + 1); - timeString = timeString.substring(0, differencePosition); - if ((differenceString.length !== 2) && (differenceString.length !== 4)) - throw new Error("Wrong input string for conversion"); - let number = parseInt(differenceString.substring(0, 2), 10); - if (isNaN(number.valueOf())) - throw new Error("Wrong input string for conversion"); - hourDifference = multiplier * number; - if (differenceString.length === 4) { - number = parseInt(differenceString.substring(2, 4), 10); - if (isNaN(number.valueOf())) - throw new Error("Wrong input string for conversion"); - minuteDifference = multiplier * number; - } - } - } - let fractionPointPosition = timeString.indexOf("."); - if (fractionPointPosition === -1) - fractionPointPosition = timeString.indexOf(","); - if (fractionPointPosition !== -1) { - const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`); - if (isNaN(fractionPartCheck.valueOf())) - throw new Error("Wrong input string for conversion"); - fractionPart = fractionPartCheck.valueOf(); - dateTimeString = timeString.substring(0, fractionPointPosition); - } - else - dateTimeString = timeString; - switch (true) { - case (dateTimeString.length === 8): - parser = /(\d{4})(\d{2})(\d{2})/ig; - if (fractionPointPosition !== -1) - throw new Error("Wrong input string for conversion"); - break; - case (dateTimeString.length === 10): - parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig; - if (fractionPointPosition !== -1) { - let fractionResult = 60 * fractionPart; - this.minute = Math.floor(fractionResult); - fractionResult = 60 * (fractionResult - this.minute); - this.second = Math.floor(fractionResult); - fractionResult = 1000 * (fractionResult - this.second); - this.millisecond = Math.floor(fractionResult); - } - break; - case (dateTimeString.length === 12): - parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig; - if (fractionPointPosition !== -1) { - let fractionResult = 60 * fractionPart; - this.second = Math.floor(fractionResult); - fractionResult = 1000 * (fractionResult - this.second); - this.millisecond = Math.floor(fractionResult); - } - break; - case (dateTimeString.length === 14): - parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig; - if (fractionPointPosition !== -1) { - const fractionResult = 1000 * fractionPart; - this.millisecond = Math.floor(fractionResult); - } - break; - default: - throw new Error("Wrong input string for conversion"); - } - const parserArray = parser.exec(dateTimeString); - if (parserArray === null) - throw new Error("Wrong input string for conversion"); - for (let j = 1; j < parserArray.length; j++) { - switch (j) { - case 1: - this.year = parseInt(parserArray[j], 10); - break; - case 2: - this.month = parseInt(parserArray[j], 10); - break; - case 3: - this.day = parseInt(parserArray[j], 10); - break; - case 4: - this.hour = parseInt(parserArray[j], 10) + hourDifference; - break; - case 5: - this.minute = parseInt(parserArray[j], 10) + minuteDifference; - break; - case 6: - this.second = parseInt(parserArray[j], 10); - break; - default: - throw new Error("Wrong input string for conversion"); - } - } - if (isUTC === false) { - const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); - this.year = tempDate.getUTCFullYear(); - this.month = tempDate.getUTCMonth(); - this.day = tempDate.getUTCDay(); - this.hour = tempDate.getUTCHours(); - this.minute = tempDate.getUTCMinutes(); - this.second = tempDate.getUTCSeconds(); - this.millisecond = tempDate.getUTCMilliseconds(); - } - } - toString(encoding = "iso") { - if (encoding === "iso") { - const outputArray = []; - outputArray.push(padNumber(this.year, 4)); - outputArray.push(padNumber(this.month, 2)); - outputArray.push(padNumber(this.day, 2)); - outputArray.push(padNumber(this.hour, 2)); - outputArray.push(padNumber(this.minute, 2)); - outputArray.push(padNumber(this.second, 2)); - if (this.millisecond !== 0) { - outputArray.push("."); - outputArray.push(padNumber(this.millisecond, 3)); - } - outputArray.push("Z"); - return outputArray.join(""); - } - return super.toString(encoding); - } - toJSON() { - return { - ...super.toJSON(), - millisecond: this.millisecond, - }; - } -} -_a$5 = GeneralizedTime; -(() => { - typeStore.GeneralizedTime = _a$5; -})(); +var _a$5; +class GeneralizedTime extends UTCTime { + constructor(parameters = {}) { + var _b; + super(parameters); + (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 24; + } + fromDate(inputDate) { + super.fromDate(inputDate); + this.millisecond = inputDate.getUTCMilliseconds(); + } + toDate() { + const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond); + return (new Date(utcDate)); + } + fromString(inputString) { + let isUTC = false; + let timeString = ""; + let dateTimeString = ""; + let fractionPart = 0; + let parser; + let hourDifference = 0; + let minuteDifference = 0; + if (inputString[inputString.length - 1] === "Z") { + timeString = inputString.substring(0, inputString.length - 1); + isUTC = true; + } + else { + const number = new Number(inputString[inputString.length - 1]); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + timeString = inputString; + } + if (isUTC) { + if (timeString.indexOf("+") !== -1) + throw new Error("Wrong input string for conversion"); + if (timeString.indexOf("-") !== -1) + throw new Error("Wrong input string for conversion"); + } + else { + let multiplier = 1; + let differencePosition = timeString.indexOf("+"); + let differenceString = ""; + if (differencePosition === -1) { + differencePosition = timeString.indexOf("-"); + multiplier = -1; + } + if (differencePosition !== -1) { + differenceString = timeString.substring(differencePosition + 1); + timeString = timeString.substring(0, differencePosition); + if ((differenceString.length !== 2) && (differenceString.length !== 4)) + throw new Error("Wrong input string for conversion"); + let number = parseInt(differenceString.substring(0, 2), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + hourDifference = multiplier * number; + if (differenceString.length === 4) { + number = parseInt(differenceString.substring(2, 4), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + minuteDifference = multiplier * number; + } + } + } + let fractionPointPosition = timeString.indexOf("."); + if (fractionPointPosition === -1) + fractionPointPosition = timeString.indexOf(","); + if (fractionPointPosition !== -1) { + const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`); + if (isNaN(fractionPartCheck.valueOf())) + throw new Error("Wrong input string for conversion"); + fractionPart = fractionPartCheck.valueOf(); + dateTimeString = timeString.substring(0, fractionPointPosition); + } + else + dateTimeString = timeString; + switch (true) { + case (dateTimeString.length === 8): + parser = /(\d{4})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) + throw new Error("Wrong input string for conversion"); + break; + case (dateTimeString.length === 10): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.minute = Math.floor(fractionResult); + fractionResult = 60 * (fractionResult - this.minute); + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 12): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 14): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + const fractionResult = 1000 * fractionPart; + this.millisecond = Math.floor(fractionResult); + } + break; + default: + throw new Error("Wrong input string for conversion"); + } + const parserArray = parser.exec(dateTimeString); + if (parserArray === null) + throw new Error("Wrong input string for conversion"); + for (let j = 1; j < parserArray.length; j++) { + switch (j) { + case 1: + this.year = parseInt(parserArray[j], 10); + break; + case 2: + this.month = parseInt(parserArray[j], 10); + break; + case 3: + this.day = parseInt(parserArray[j], 10); + break; + case 4: + this.hour = parseInt(parserArray[j], 10) + hourDifference; + break; + case 5: + this.minute = parseInt(parserArray[j], 10) + minuteDifference; + break; + case 6: + this.second = parseInt(parserArray[j], 10); + break; + default: + throw new Error("Wrong input string for conversion"); + } + } + if (isUTC === false) { + const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); + this.year = tempDate.getUTCFullYear(); + this.month = tempDate.getUTCMonth(); + this.day = tempDate.getUTCDay(); + this.hour = tempDate.getUTCHours(); + this.minute = tempDate.getUTCMinutes(); + this.second = tempDate.getUTCSeconds(); + this.millisecond = tempDate.getUTCMilliseconds(); + } + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = []; + outputArray.push(padNumber(this.year, 4)); + outputArray.push(padNumber(this.month, 2)); + outputArray.push(padNumber(this.day, 2)); + outputArray.push(padNumber(this.hour, 2)); + outputArray.push(padNumber(this.minute, 2)); + outputArray.push(padNumber(this.second, 2)); + if (this.millisecond !== 0) { + outputArray.push("."); + outputArray.push(padNumber(this.millisecond, 3)); + } + outputArray.push("Z"); + return outputArray.join(""); + } + return super.toString(encoding); + } + toJSON() { + return { + ...super.toJSON(), + millisecond: this.millisecond, + }; + } +} +_a$5 = GeneralizedTime; +(() => { + typeStore.GeneralizedTime = _a$5; +})(); GeneralizedTime.NAME = "GeneralizedTime"; -var _a$4; -class DATE$2 extends Utf8String { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 31; - } -} -_a$4 = DATE$2; -(() => { - typeStore.DATE = _a$4; -})(); +var _a$4; +let DATE$2 = class DATE extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 31; + } +}; +_a$4 = DATE$2; +(() => { + typeStore.DATE = _a$4; +})(); DATE$2.NAME = "DATE"; -var _a$3; -class TimeOfDay extends Utf8String { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 32; - } -} -_a$3 = TimeOfDay; -(() => { - typeStore.TimeOfDay = _a$3; -})(); +var _a$3; +class TimeOfDay extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 32; + } +} +_a$3 = TimeOfDay; +(() => { + typeStore.TimeOfDay = _a$3; +})(); TimeOfDay.NAME = "TimeOfDay"; -var _a$2; -class DateTime extends Utf8String { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 33; - } -} -_a$2 = DateTime; -(() => { - typeStore.DateTime = _a$2; -})(); -DateTime.NAME = "DateTime"; - -var _a$1; -class Duration extends Utf8String { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 34; - } -} -_a$1 = Duration; -(() => { - typeStore.Duration = _a$1; -})(); -Duration.NAME = "Duration"; - -var _a$x; -class TIME extends Utf8String { - constructor(parameters = {}) { - super(parameters); - this.idBlock.tagClass = 1; - this.idBlock.tagNumber = 14; - } -} -_a$x = TIME; -(() => { - typeStore.TIME = _a$x; -})(); -TIME.NAME = "TIME"; - -class Any { - constructor({ name = EMPTY_STRING$1, optional = false, } = {}) { - this.name = name; - this.optional = optional; - } +var _a$2; +class DateTime extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 33; + } } +_a$2 = DateTime; +(() => { + typeStore.DateTime = _a$2; +})(); +DateTime.NAME = "DateTime"; -class Choice extends Any { - constructor({ value = [], ...parameters } = {}) { - super(parameters); - this.value = value; - } +var _a$1; +class Duration extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 34; + } } +_a$1 = Duration; +(() => { + typeStore.Duration = _a$1; +})(); +Duration.NAME = "Duration"; -class Repeated extends Any { - constructor({ value = new Any(), local = false, ...parameters } = {}) { - super(parameters); - this.value = value; - this.local = local; - } +var _a$x; +class TIME extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 14; + } } +_a$x = TIME; +(() => { + typeStore.TIME = _a$x; +})(); +TIME.NAME = "TIME"; -class RawData { - constructor({ data = EMPTY_VIEW } = {}) { - this.dataView = BufferSourceConverter.toUint8Array(data); - } - get data() { - return this.dataView.slice().buffer; - } - set data(value) { - this.dataView = BufferSourceConverter.toUint8Array(value); - } - fromBER(inputBuffer, inputOffset, inputLength) { - const endLength = inputOffset + inputLength; - this.dataView = BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength); - return endLength; - } - toBER(sizeOnly) { - return this.dataView.slice().buffer; - } +class Any { + constructor({ name = EMPTY_STRING$1, optional = false } = {}) { + this.name = name; + this.optional = optional; + } } -function compareSchema(root, inputData, inputSchema) { - if (inputSchema instanceof Choice) { - for (let j = 0; j < inputSchema.value.length; j++) { - const result = compareSchema(root, inputData, inputSchema.value[j]); - if (result.verified) { - return { - verified: true, - result: root - }; - } - } - { - const _result = { - verified: false, - result: { - error: "Wrong values for Choice type" - }, - }; - if (inputSchema.hasOwnProperty(NAME)) - _result.name = inputSchema.name; - return _result; - } - } - if (inputSchema instanceof Any) { - if (inputSchema.hasOwnProperty(NAME)) - root[inputSchema.name] = inputData; - return { - verified: true, - result: root - }; - } - if ((root instanceof Object) === false) { - return { - verified: false, - result: { error: "Wrong root object" } - }; - } - if ((inputData instanceof Object) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 data" } - }; - } - if ((inputSchema instanceof Object) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - if ((ID_BLOCK in inputSchema) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - if ((FROM_BER in inputSchema.idBlock) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - if ((TO_BER in inputSchema.idBlock) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - const encodedId = inputSchema.idBlock.toBER(false); - if (encodedId.byteLength === 0) { - return { - verified: false, - result: { error: "Error encoding idBlock for ASN.1 schema" } - }; - } - const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength); - if (decodedOffset === -1) { - return { - verified: false, - result: { error: "Error decoding idBlock for ASN.1 schema" } - }; - } - if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) { - return { - verified: false, - result: root - }; - } - if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) { - return { - verified: false, - result: root - }; - } - if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) { - return { - verified: false, - result: root - }; - } - if (!(IS_HEX_ONLY in inputSchema.idBlock)) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) { - return { - verified: false, - result: root - }; - } - if (inputSchema.idBlock.isHexOnly) { - if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) { - return { - verified: false, - result: { error: "Wrong ASN.1 schema" } - }; - } - const schemaView = inputSchema.idBlock.valueHexView; - const asn1View = inputData.idBlock.valueHexView; - if (schemaView.length !== asn1View.length) { - return { - verified: false, - result: root - }; - } - for (let i = 0; i < schemaView.length; i++) { - if (schemaView[i] !== asn1View[1]) { - return { - verified: false, - result: root - }; - } - } - } - if (inputSchema.name) { - inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); - if (inputSchema.name) - root[inputSchema.name] = inputData; - } - if (inputSchema instanceof typeStore.Constructed) { - let admission = 0; - let result = { - verified: false, - result: { - error: "Unknown error", - } - }; - let maxLength = inputSchema.valueBlock.value.length; - if (maxLength > 0) { - if (inputSchema.valueBlock.value[0] instanceof Repeated) { - maxLength = inputData.valueBlock.value.length; - } - } - if (maxLength === 0) { - return { - verified: true, - result: root - }; - } - if ((inputData.valueBlock.value.length === 0) && - (inputSchema.valueBlock.value.length !== 0)) { - let _optional = true; - for (let i = 0; i < inputSchema.valueBlock.value.length; i++) - _optional = _optional && (inputSchema.valueBlock.value[i].optional || false); - if (_optional) { - return { - verified: true, - result: root - }; - } - if (inputSchema.name) { - inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); - if (inputSchema.name) - delete root[inputSchema.name]; - } - root.error = "Inconsistent object length"; - return { - verified: false, - result: root - }; - } - for (let i = 0; i < maxLength; i++) { - if ((i - admission) >= inputData.valueBlock.value.length) { - if (inputSchema.valueBlock.value[i].optional === false) { - const _result = { - verified: false, - result: root - }; - root.error = "Inconsistent length between ASN.1 data and schema"; - if (inputSchema.name) { - inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); - if (inputSchema.name) { - delete root[inputSchema.name]; - _result.name = inputSchema.name; - } - } - return _result; - } - } - else { - if (inputSchema.valueBlock.value[0] instanceof Repeated) { - result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value); - if (result.verified === false) { - if (inputSchema.valueBlock.value[0].optional) - admission++; - else { - if (inputSchema.name) { - inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); - if (inputSchema.name) - delete root[inputSchema.name]; - } - return result; - } - } - if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) { - let arrayRoot = {}; - if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local)) - arrayRoot = inputData; - else - arrayRoot = root; - if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined") - arrayRoot[inputSchema.valueBlock.value[0].name] = []; - arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]); - } - } - else { - result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]); - if (result.verified === false) { - if (inputSchema.valueBlock.value[i].optional) - admission++; - else { - if (inputSchema.name) { - inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); - if (inputSchema.name) - delete root[inputSchema.name]; - } - return result; - } - } - } - } - } - if (result.verified === false) { - const _result = { - verified: false, - result: root - }; - if (inputSchema.name) { - inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); - if (inputSchema.name) { - delete root[inputSchema.name]; - _result.name = inputSchema.name; - } - } - return _result; - } - return { - verified: true, - result: root - }; - } - if (inputSchema.primitiveSchema && - (VALUE_HEX_VIEW in inputData.valueBlock)) { - const asn1 = localFromBER(inputData.valueBlock.valueHexView); - if (asn1.offset === -1) { - const _result = { - verified: false, - result: asn1.result - }; - if (inputSchema.name) { - inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); - if (inputSchema.name) { - delete root[inputSchema.name]; - _result.name = inputSchema.name; - } - } - return _result; - } - return compareSchema(root, asn1.result, inputSchema.primitiveSchema); - } - return { - verified: true, - result: root - }; +class Choice extends Any { + constructor({ value = [], ...parameters } = {}) { + super(parameters); + this.value = value; + } } -const EMPTY_BUFFER = new ArrayBuffer(0); -const EMPTY_STRING = ""; - -class ArgumentError extends TypeError { - constructor() { - super(...arguments); - this.name = ArgumentError.NAME; - } - static isType(value, type) { - if (typeof type === "string") { - if (type === "Array" && Array.isArray(value)) { - return true; - } - else if (type === "ArrayBuffer" && value instanceof ArrayBuffer) { - return true; - } - else if (type === "ArrayBufferView" && ArrayBuffer.isView(value)) { - return true; - } - else if (typeof value === type) { - return true; - } - } - else if (value instanceof type) { - return true; - } - return false; - } - static assert(value, name, ...types) { - for (const type of types) { - if (this.isType(value, type)) { - return; - } - } - const typeNames = types.map(o => o instanceof Function && "name" in o ? o.name : `${o}`); - throw new ArgumentError(`Parameter '${name}' is not of type ${typeNames.length > 1 ? `(${typeNames.join(" or ")})` : typeNames[0]}`); - } -} -ArgumentError.NAME = "ArgumentError"; - -class ParameterError extends TypeError { - constructor(field, target = null, message) { - super(); - this.name = ParameterError.NAME; - this.field = field; - if (target) { - this.target = target; - } - if (message) { - this.message = message; - } - else { - this.message = `Absent mandatory parameter '${field}' ${target ? ` in '${target}'` : EMPTY_STRING}`; - } - } - static assert(...args) { - let target = null; - let params; - let fields; - if (typeof args[0] === "string") { - target = args[0]; - params = args[1]; - fields = args.slice(2); - } - else { - params = args[0]; - fields = args.slice(1); - } - ArgumentError.assert(params, "parameters", "object"); - for (const field of fields) { - const value = params[field]; - if (value === undefined || value === null) { - throw new ParameterError(field, target); - } - } - } - static assertEmpty(value, name, target) { - if (value === undefined || value === null) { - throw new ParameterError(name, target); - } - } -} -ParameterError.NAME = "ParameterError"; - -class AsnError extends Error { - static assertSchema(asn1, target) { - if (!asn1.verified) { - throw new Error(`Object's schema was not verified against input data for ${target}`); - } - } - static assert(asn, target) { - if (asn.offset === -1) { - throw new AsnError(`Error during parsing of ASN.1 data. Data is not correct for '${target}'.`); - } - } - constructor(message) { - super(message); - this.name = "AsnError"; - } +class Repeated extends Any { + constructor({ value = new Any(), local = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.local = local; + } } -class PkiObject { - static blockName() { - return this.CLASS_NAME; - } - static fromBER(raw) { - const asn1 = fromBER(raw); - AsnError.assert(asn1, this.name); - try { - return new this({ schema: asn1.result }); - } - catch (e) { - throw new AsnError(`Cannot create '${this.CLASS_NAME}' from ASN.1 object`); - } - } - static defaultValues(memberName) { - throw new Error(`Invalid member name for ${this.CLASS_NAME} class: ${memberName}`); - } - static schema(parameters = {}) { - throw new Error(`Method '${this.CLASS_NAME}.schema' should be overridden`); - } - get className() { - return this.constructor.CLASS_NAME; - } - toString(encoding = "hex") { - let schema; - try { - schema = this.toSchema(); - } - catch (_a) { - schema = this.toSchema(true); - } - return Convert.ToString(schema.toBER(), encoding); - } -} -PkiObject.CLASS_NAME = "PkiObject"; - -function stringPrep(inputString) { - let isSpace = false; - let cutResult = EMPTY_STRING; - const result = inputString.trim(); - for (let i = 0; i < result.length; i++) { - if (result.charCodeAt(i) === 32) { - if (isSpace === false) - isSpace = true; - } - else { - if (isSpace) { - cutResult += " "; - isSpace = false; - } - cutResult += result[i]; - } - } - return cutResult.toLowerCase(); +class RawData { + get data() { + return this.dataView.slice().buffer; + } + set data(value) { + this.dataView = BufferSourceConverter.toUint8Array(value); + } + constructor({ data = EMPTY_VIEW } = {}) { + this.dataView = BufferSourceConverter.toUint8Array(data); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const endLength = inputOffset + inputLength; + this.dataView = BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength); + return endLength; + } + toBER(_sizeOnly) { + return this.dataView.slice().buffer; + } } -const TYPE$5 = "type"; -const VALUE$6 = "value"; -class AttributeTypeAndValue extends PkiObject { - constructor(parameters = {}) { - super(); - this.type = getParametersValue(parameters, TYPE$5, AttributeTypeAndValue.defaultValues(TYPE$5)); - this.value = getParametersValue(parameters, VALUE$6, AttributeTypeAndValue.defaultValues(VALUE$6)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TYPE$5: - return EMPTY_STRING; - case VALUE$6: - return {}; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.type || EMPTY_STRING) }), - new Any({ name: (names.value || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - TYPE$5, - "typeValue" - ]); - const asn1 = compareSchema(schema, schema, AttributeTypeAndValue.schema({ - names: { - type: TYPE$5, - value: "typeValue" - } - })); - AsnError.assertSchema(asn1, this.className); - this.type = asn1.result.type.valueBlock.toString(); - this.value = asn1.result.typeValue; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.type }), - this.value - ] - })); - } - toJSON() { - const _object = { - type: this.type - }; - if (Object.keys(this.value).length !== 0) { - _object.value = (this.value).toJSON(); - } - else { - _object.value = this.value; - } - return _object; - } - isEqual(compareTo) { - const stringBlockNames = [ - Utf8String.blockName(), - BmpString.blockName(), - UniversalString.blockName(), - NumericString.blockName(), - PrintableString.blockName(), - TeletexString.blockName(), - VideotexString.blockName(), - IA5String.blockName(), - GraphicString.blockName(), - VisibleString.blockName(), - GeneralString.blockName(), - CharacterString.blockName() - ]; - if (compareTo instanceof ArrayBuffer) { - return BufferSourceConverter.isEqual(this.value.valueBeforeDecodeView, compareTo); - } - if (compareTo.constructor.blockName() === AttributeTypeAndValue.blockName()) { - if (this.type !== compareTo.type) - return false; - const isStringPair = [false, false]; - const thisName = this.value.constructor.blockName(); - for (const name of stringBlockNames) { - if (thisName === name) { - isStringPair[0] = true; - } - if (compareTo.value.constructor.blockName() === name) { - isStringPair[1] = true; - } - } - if (isStringPair[0] !== isStringPair[1]) { - return false; - } - const isString = (isStringPair[0] && isStringPair[1]); - if (isString) { - const value1 = stringPrep(this.value.valueBlock.value); - const value2 = stringPrep(compareTo.value.valueBlock.value); - if (value1.localeCompare(value2) !== 0) - return false; - } - else { - if (!BufferSourceConverter.isEqual(this.value.valueBeforeDecodeView, compareTo.value.valueBeforeDecodeView)) - return false; - } - return true; - } - return false; - } -} -AttributeTypeAndValue.CLASS_NAME = "AttributeTypeAndValue"; - -const TYPE_AND_VALUES = "typesAndValues"; -const VALUE_BEFORE_DECODE = "valueBeforeDecode"; -const RDN = "RDN"; -class RelativeDistinguishedNames extends PkiObject { - constructor(parameters = {}) { - super(); - this.typesAndValues = getParametersValue(parameters, TYPE_AND_VALUES, RelativeDistinguishedNames.defaultValues(TYPE_AND_VALUES)); - this.valueBeforeDecode = getParametersValue(parameters, VALUE_BEFORE_DECODE, RelativeDistinguishedNames.defaultValues(VALUE_BEFORE_DECODE)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TYPE_AND_VALUES: - return []; - case VALUE_BEFORE_DECODE: - return EMPTY_BUFFER; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TYPE_AND_VALUES: - return (memberValue.length === 0); - case VALUE_BEFORE_DECODE: - return (memberValue.byteLength === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.repeatedSequence || EMPTY_STRING), - value: new Set({ - value: [ - new Repeated({ - name: (names.repeatedSet || EMPTY_STRING), - value: AttributeTypeAndValue.schema(names.typeAndValue || {}) - }) - ] - }) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - RDN, - TYPE_AND_VALUES - ]); - const asn1 = compareSchema(schema, schema, RelativeDistinguishedNames.schema({ - names: { - blockName: RDN, - repeatedSet: TYPE_AND_VALUES - } - })); - AsnError.assertSchema(asn1, this.className); - if (TYPE_AND_VALUES in asn1.result) { - this.typesAndValues = Array.from(asn1.result.typesAndValues, element => new AttributeTypeAndValue({ schema: element })); - } - this.valueBeforeDecode = asn1.result.RDN.valueBeforeDecodeView.slice().buffer; - } - toSchema() { - if (this.valueBeforeDecode.byteLength === 0) { - return (new Sequence({ - value: [new Set({ - value: Array.from(this.typesAndValues, o => o.toSchema()) - })] - })); - } - const asn1 = fromBER(this.valueBeforeDecode); - AsnError.assert(asn1, "RelativeDistinguishedNames"); - if (!(asn1.result instanceof Sequence)) { - throw new Error("ASN.1 result should be SEQUENCE"); - } - return asn1.result; - } - toJSON() { - return { - typesAndValues: Array.from(this.typesAndValues, o => o.toJSON()) - }; - } - isEqual(compareTo) { - if (compareTo instanceof RelativeDistinguishedNames) { - if (this.typesAndValues.length !== compareTo.typesAndValues.length) - return false; - for (const [index, typeAndValue] of this.typesAndValues.entries()) { - if (typeAndValue.isEqual(compareTo.typesAndValues[index]) === false) - return false; - } - return true; - } - if (compareTo instanceof ArrayBuffer) { - return isEqualBuffer(this.valueBeforeDecode, compareTo); - } - return false; - } -} -RelativeDistinguishedNames.CLASS_NAME = "RelativeDistinguishedNames"; +function compareSchema(root, inputData, inputSchema) { + if (inputSchema instanceof Choice) { + for (const element of inputSchema.value) { + const result = compareSchema(root, inputData, element); + if (result.verified) { + return { + verified: true, + result: root, + }; + } + } + { + const _result = { + verified: false, + result: { error: "Wrong values for Choice type" }, + }; + if (inputSchema.hasOwnProperty(NAME)) + _result.name = inputSchema.name; + return _result; + } + } + if (inputSchema instanceof Any) { + if (inputSchema.hasOwnProperty(NAME)) + root[inputSchema.name] = inputData; + return { + verified: true, + result: root, + }; + } + if ((root instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong root object" }, + }; + } + if ((inputData instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 data" }, + }; + } + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((ID_BLOCK in inputSchema) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((FROM_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if ((TO_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + const encodedId = inputSchema.idBlock.toBER(false); + if (encodedId.byteLength === 0) { + return { + verified: false, + result: { error: "Error encoding idBlock for ASN.1 schema" }, + }; + } + const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength); + if (decodedOffset === -1) { + return { + verified: false, + result: { error: "Error decoding idBlock for ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) { + return { + verified: false, + result: root, + }; + } + if (!(IS_HEX_ONLY in inputSchema.idBlock)) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) { + return { + verified: false, + result: root, + }; + } + if (inputSchema.idBlock.isHexOnly) { + if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" }, + }; + } + const schemaView = inputSchema.idBlock.valueHexView; + const asn1View = inputData.idBlock.valueHexView; + if (schemaView.length !== asn1View.length) { + return { + verified: false, + result: root, + }; + } + for (let i = 0; i < schemaView.length; i++) { + if (schemaView[i] !== asn1View[1]) { + return { + verified: false, + result: root, + }; + } + } + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); + if (inputSchema.name) + root[inputSchema.name] = inputData; + } + if (inputSchema instanceof typeStore.Constructed) { + let admission = 0; + let result = { + verified: false, + result: { error: "Unknown error" }, + }; + let maxLength = inputSchema.valueBlock.value.length; + if (maxLength > 0) { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + maxLength = inputData.valueBlock.value.length; + } + } + if (maxLength === 0) { + return { + verified: true, + result: root, + }; + } + if ((inputData.valueBlock.value.length === 0) + && (inputSchema.valueBlock.value.length !== 0)) { + let _optional = true; + for (let i = 0; i < inputSchema.valueBlock.value.length; i++) + _optional = _optional && (inputSchema.valueBlock.value[i].optional || false); + if (_optional) { + return { + verified: true, + result: root, + }; + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); + if (inputSchema.name) + delete root[inputSchema.name]; + } + root.error = "Inconsistent object length"; + return { + verified: false, + result: root, + }; + } + for (let i = 0; i < maxLength; i++) { + if ((i - admission) >= inputData.valueBlock.value.length) { + if (inputSchema.valueBlock.value[i].optional === false) { + const _result = { + verified: false, + result: root, + }; + root.error = "Inconsistent length between ASN.1 data and schema"; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + } + else { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value); + if (result.verified === false) { + if (inputSchema.valueBlock.value[0].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) { + let arrayRoot = {}; + if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local)) + arrayRoot = inputData; + else + arrayRoot = root; + if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined") + arrayRoot[inputSchema.valueBlock.value[0].name] = []; + arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]); + } + } + else { + result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]); + if (result.verified === false) { + if (inputSchema.valueBlock.value[i].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + } + } + } + if (result.verified === false) { + const _result = { + verified: false, + result: root, + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return { + verified: true, + result: root, + }; + } + if (inputSchema.primitiveSchema + && (VALUE_HEX_VIEW in inputData.valueBlock)) { + const asn1 = localFromBER(inputData.valueBlock.valueHexView); + if (asn1.offset === -1) { + const _result = { + verified: false, + result: asn1.result, + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING$1); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return compareSchema(root, asn1.result, inputSchema.primitiveSchema); + } + return { + verified: true, + result: root, + }; +} -const TYPE$4 = "type"; -const VALUE$5 = "value"; -function builtInStandardAttributes(parameters = {}, optional = false) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - optional, - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 2, - tagNumber: 1 - }, - name: (names.country_name || EMPTY_STRING), - value: [ - new Choice({ - value: [ - new NumericString(), - new PrintableString() - ] - }) - ] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 2, - tagNumber: 2 - }, - name: (names.administration_domain_name || EMPTY_STRING), - value: [ - new Choice({ - value: [ - new NumericString(), - new PrintableString() - ] - }) - ] - }), - new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - name: (names.network_address || EMPTY_STRING), - isHexOnly: true - }), - new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - name: (names.terminal_identifier || EMPTY_STRING), - isHexOnly: true - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - name: (names.private_domain_name || EMPTY_STRING), - value: [ - new Choice({ - value: [ - new NumericString(), - new PrintableString() - ] - }) - ] - }), - new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - name: (names.organization_name || EMPTY_STRING), - isHexOnly: true - }), - new Primitive({ - optional: true, - name: (names.numeric_user_identifier || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 4 - }, - isHexOnly: true - }), - new Constructed({ - optional: true, - name: (names.personal_name || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 5 - }, - value: [ - new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - isHexOnly: true - }), - new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - isHexOnly: true - }), - new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - isHexOnly: true - }), - new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - isHexOnly: true - }) - ] - }), - new Constructed({ - optional: true, - name: (names.organizational_unit_names || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 6 - }, - value: [ - new Repeated({ - value: new PrintableString() - }) - ] - }) - ] - })); -} -function builtInDomainDefinedAttributes(optional = false) { - return (new Sequence({ - optional, - value: [ - new PrintableString(), - new PrintableString() - ] - })); -} -function extensionAttributes(optional = false) { - return (new Set({ - optional, - value: [ - new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - isHexOnly: true - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [new Any()] - }) - ] - })); -} -class GeneralName extends PkiObject { - constructor(parameters = {}) { - super(); - this.type = getParametersValue(parameters, TYPE$4, GeneralName.defaultValues(TYPE$4)); - this.value = getParametersValue(parameters, VALUE$5, GeneralName.defaultValues(VALUE$5)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TYPE$4: - return 9; - case VALUE$5: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TYPE$4: - return (memberValue === GeneralName.defaultValues(memberName)); - case VALUE$5: - return (Object.keys(memberValue).length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Choice({ - value: [ - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier(), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Any()] - }) - ] - }), - new Primitive({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 1 - } - }), - new Primitive({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 2 - } - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - name: (names.blockName || EMPTY_STRING), - value: [ - builtInStandardAttributes((names.builtInStandardAttributes || {}), false), - builtInDomainDefinedAttributes(true), - extensionAttributes(true) - ] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 4 - }, - name: (names.blockName || EMPTY_STRING), - value: [RelativeDistinguishedNames.schema(names.directoryName || {})] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 5 - }, - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Choice({ - value: [ - new TeletexString(), - new PrintableString(), - new UniversalString(), - new Utf8String(), - new BmpString() - ] - }) - ] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new Choice({ - value: [ - new TeletexString(), - new PrintableString(), - new UniversalString(), - new Utf8String(), - new BmpString() - ] - }) - ] - }) - ] - }), - new Primitive({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 6 - } - }), - new Primitive({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 7 - } - }), - new Primitive({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 8 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - "blockName", - "otherName", - "rfc822Name", - "dNSName", - "x400Address", - "directoryName", - "ediPartyName", - "uniformResourceIdentifier", - "iPAddress", - "registeredID" - ]); - const asn1 = compareSchema(schema, schema, GeneralName.schema({ - names: { - blockName: "blockName", - otherName: "otherName", - rfc822Name: "rfc822Name", - dNSName: "dNSName", - x400Address: "x400Address", - directoryName: { - names: { - blockName: "directoryName" - } - }, - ediPartyName: "ediPartyName", - uniformResourceIdentifier: "uniformResourceIdentifier", - iPAddress: "iPAddress", - registeredID: "registeredID" - } - })); - AsnError.assertSchema(asn1, this.className); - this.type = asn1.result.blockName.idBlock.tagNumber; - switch (this.type) { - case 0: - this.value = asn1.result.blockName; - break; - case 1: - case 2: - case 6: - { - const value = asn1.result.blockName; - value.idBlock.tagClass = 1; - value.idBlock.tagNumber = 22; - const valueBER = value.toBER(false); - const asnValue = fromBER(valueBER); - AsnError.assert(asnValue, "GeneralName value"); - this.value = asnValue.result.valueBlock.value; - } - break; - case 3: - this.value = asn1.result.blockName; - break; - case 4: - this.value = new RelativeDistinguishedNames({ schema: asn1.result.directoryName }); - break; - case 5: - this.value = asn1.result.ediPartyName; - break; - case 7: - this.value = new OctetString({ valueHex: asn1.result.blockName.valueBlock.valueHex }); - break; - case 8: - { - const value = asn1.result.blockName; - value.idBlock.tagClass = 1; - value.idBlock.tagNumber = 6; - const valueBER = value.toBER(false); - const asnValue = fromBER(valueBER); - AsnError.assert(asnValue, "GeneralName registeredID"); - this.value = asnValue.result.valueBlock.toString(); - } - break; - } - } - toSchema() { - switch (this.type) { - case 0: - case 3: - case 5: - return new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: this.type - }, - value: [ - this.value - ] - }); - case 1: - case 2: - case 6: - { - const value = new IA5String({ value: this.value }); - value.idBlock.tagClass = 3; - value.idBlock.tagNumber = this.type; - return value; - } - case 4: - return new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 4 - }, - value: [this.value.toSchema()] - }); - case 7: - { - const value = this.value; - value.idBlock.tagClass = 3; - value.idBlock.tagNumber = this.type; - return value; - } - case 8: - { - const value = new ObjectIdentifier({ value: this.value }); - value.idBlock.tagClass = 3; - value.idBlock.tagNumber = this.type; - return value; - } - default: - return GeneralName.schema(); - } - } - toJSON() { - const _object = { - type: this.type, - value: EMPTY_STRING - }; - if ((typeof this.value) === "string") - _object.value = this.value; - else { - try { - _object.value = this.value.toJSON(); - } - catch (ex) { - } - } - return _object; - } -} -GeneralName.CLASS_NAME = "GeneralName"; +const EMPTY_BUFFER = new ArrayBuffer(0); +const EMPTY_STRING = ""; -const ACCESS_METHOD = "accessMethod"; -const ACCESS_LOCATION = "accessLocation"; -const CLEAR_PROPS$1v = [ - ACCESS_METHOD, - ACCESS_LOCATION, -]; -class AccessDescription extends PkiObject { - constructor(parameters = {}) { - super(); - this.accessMethod = getParametersValue(parameters, ACCESS_METHOD, AccessDescription.defaultValues(ACCESS_METHOD)); - this.accessLocation = getParametersValue(parameters, ACCESS_LOCATION, AccessDescription.defaultValues(ACCESS_LOCATION)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ACCESS_METHOD: - return EMPTY_STRING; - case ACCESS_LOCATION: - return new GeneralName(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.accessMethod || EMPTY_STRING) }), - GeneralName.schema(names.accessLocation || {}) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1v); - const asn1 = compareSchema(schema, schema, AccessDescription.schema({ - names: { - accessMethod: ACCESS_METHOD, - accessLocation: { - names: { - blockName: ACCESS_LOCATION - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.accessMethod = asn1.result.accessMethod.valueBlock.toString(); - this.accessLocation = new GeneralName({ schema: asn1.result.accessLocation }); - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.accessMethod }), - this.accessLocation.toSchema() - ] - })); - } - toJSON() { - return { - accessMethod: this.accessMethod, - accessLocation: this.accessLocation.toJSON() - }; - } -} -AccessDescription.CLASS_NAME = "AccessDescription"; +class ArgumentError extends TypeError { + constructor() { + super(...arguments); + this.name = ArgumentError.NAME; + } + static isType(value, type) { + if (typeof type === "string") { + if (type === "Array" && Array.isArray(value)) { + return true; + } + else if (type === "ArrayBuffer" && value instanceof ArrayBuffer) { + return true; + } + else if (type === "ArrayBufferView" && ArrayBuffer.isView(value)) { + return true; + } + else if (typeof value === type) { + return true; + } + } + else if (value instanceof type) { + return true; + } + return false; + } + static assert(value, name, ...types) { + for (const type of types) { + if (this.isType(value, type)) { + return; + } + } + const typeNames = types.map(o => o instanceof Function && "name" in o ? o.name : `${o}`); + throw new ArgumentError(`Parameter '${name}' is not of type ${typeNames.length > 1 ? `(${typeNames.join(" or ")})` : typeNames[0]}`); + } +} +ArgumentError.NAME = "ArgumentError"; -const SECONDS = "seconds"; -const MILLIS = "millis"; -const MICROS = "micros"; -class Accuracy extends PkiObject { - constructor(parameters = {}) { - super(); - if (SECONDS in parameters) { - this.seconds = getParametersValue(parameters, SECONDS, Accuracy.defaultValues(SECONDS)); - } - if (MILLIS in parameters) { - this.millis = getParametersValue(parameters, MILLIS, Accuracy.defaultValues(MILLIS)); - } - if (MICROS in parameters) { - this.micros = getParametersValue(parameters, MICROS, Accuracy.defaultValues(MICROS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case SECONDS: - case MILLIS: - case MICROS: - return 0; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case SECONDS: - case MILLIS: - case MICROS: - return (memberValue === Accuracy.defaultValues(memberName)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - optional: true, - value: [ - new Integer({ - optional: true, - name: (names.seconds || EMPTY_STRING) - }), - new Primitive({ - name: (names.millis || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - } - }), - new Primitive({ - name: (names.micros || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - SECONDS, - MILLIS, - MICROS, - ]); - const asn1 = compareSchema(schema, schema, Accuracy.schema({ - names: { - seconds: SECONDS, - millis: MILLIS, - micros: MICROS, - } - })); - AsnError.assertSchema(asn1, this.className); - if ("seconds" in asn1.result) { - this.seconds = asn1.result.seconds.valueBlock.valueDec; - } - if ("millis" in asn1.result) { - const intMillis = new Integer({ valueHex: asn1.result.millis.valueBlock.valueHex }); - this.millis = intMillis.valueBlock.valueDec; - } - if ("micros" in asn1.result) { - const intMicros = new Integer({ valueHex: asn1.result.micros.valueBlock.valueHex }); - this.micros = intMicros.valueBlock.valueDec; - } - } - toSchema() { - const outputArray = []; - if (this.seconds !== undefined) - outputArray.push(new Integer({ value: this.seconds })); - if (this.millis !== undefined) { - const intMillis = new Integer({ value: this.millis }); - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - valueHex: intMillis.valueBlock.valueHexView - })); - } - if (this.micros !== undefined) { - const intMicros = new Integer({ value: this.micros }); - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - valueHex: intMicros.valueBlock.valueHexView - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const _object = {}; - if (this.seconds !== undefined) - _object.seconds = this.seconds; - if (this.millis !== undefined) - _object.millis = this.millis; - if (this.micros !== undefined) - _object.micros = this.micros; - return _object; - } -} -Accuracy.CLASS_NAME = "Accuracy"; +class ParameterError extends TypeError { + static assert(...args) { + let target = null; + let params; + let fields; + if (typeof args[0] === "string") { + target = args[0]; + params = args[1]; + fields = args.slice(2); + } + else { + params = args[0]; + fields = args.slice(1); + } + ArgumentError.assert(params, "parameters", "object"); + for (const field of fields) { + const value = params[field]; + if (value === undefined || value === null) { + throw new ParameterError(field, target); + } + } + } + static assertEmpty(value, name, target) { + if (value === undefined || value === null) { + throw new ParameterError(name, target); + } + } + constructor(field, target = null, message) { + super(); + this.name = ParameterError.NAME; + this.field = field; + if (target) { + this.target = target; + } + if (message) { + this.message = message; + } + else { + this.message = `Absent mandatory parameter '${field}' ${target ? ` in '${target}'` : EMPTY_STRING}`; + } + } +} +ParameterError.NAME = "ParameterError"; -const ALGORITHM_ID = "algorithmId"; -const ALGORITHM_PARAMS = "algorithmParams"; -const ALGORITHM$2 = "algorithm"; -const PARAMS = "params"; -const CLEAR_PROPS$1u = [ - ALGORITHM$2, - PARAMS -]; -class AlgorithmIdentifier extends PkiObject { - constructor(parameters = {}) { - super(); - this.algorithmId = getParametersValue(parameters, ALGORITHM_ID, AlgorithmIdentifier.defaultValues(ALGORITHM_ID)); - if (ALGORITHM_PARAMS in parameters) { - this.algorithmParams = getParametersValue(parameters, ALGORITHM_PARAMS, AlgorithmIdentifier.defaultValues(ALGORITHM_PARAMS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ALGORITHM_ID: - return EMPTY_STRING; - case ALGORITHM_PARAMS: - return new Any(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case ALGORITHM_ID: - return (memberValue === EMPTY_STRING); - case ALGORITHM_PARAMS: - return (memberValue instanceof Any); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - optional: (names.optional || false), - value: [ - new ObjectIdentifier({ name: (names.algorithmIdentifier || EMPTY_STRING) }), - new Any({ name: (names.algorithmParams || EMPTY_STRING), optional: true }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1u); - const asn1 = compareSchema(schema, schema, AlgorithmIdentifier.schema({ - names: { - algorithmIdentifier: ALGORITHM$2, - algorithmParams: PARAMS - } - })); - AsnError.assertSchema(asn1, this.className); - this.algorithmId = asn1.result.algorithm.valueBlock.toString(); - if (PARAMS in asn1.result) { - this.algorithmParams = asn1.result.params; - } - } - toSchema() { - const outputArray = []; - outputArray.push(new ObjectIdentifier({ value: this.algorithmId })); - if (this.algorithmParams && !(this.algorithmParams instanceof Any)) { - outputArray.push(this.algorithmParams); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const object = { - algorithmId: this.algorithmId - }; - if (this.algorithmParams && !(this.algorithmParams instanceof Any)) { - object.algorithmParams = this.algorithmParams.toJSON(); - } - return object; - } - isEqual(algorithmIdentifier) { - if (!(algorithmIdentifier instanceof AlgorithmIdentifier)) { - return false; - } - if (this.algorithmId !== algorithmIdentifier.algorithmId) { - return false; - } - if (this.algorithmParams) { - if (algorithmIdentifier.algorithmParams) { - return JSON.stringify(this.algorithmParams) === JSON.stringify(algorithmIdentifier.algorithmParams); - } - return false; - } - if (algorithmIdentifier.algorithmParams) { - return false; - } - return true; - } -} -AlgorithmIdentifier.CLASS_NAME = "AlgorithmIdentifier"; +class AsnError extends Error { + static assertSchema(asn1, target) { + if (!asn1.verified) { + throw new Error(`Object's schema was not verified against input data for ${target}`); + } + } + static assert(asn, target) { + if (asn.offset === -1) { + throw new AsnError(`Error during parsing of ASN.1 data. Data is not correct for '${target}'.`); + } + } + constructor(message) { + super(message); + this.name = "AsnError"; + } +} -const ALT_NAMES = "altNames"; -const CLEAR_PROPS$1t = [ - ALT_NAMES -]; -class AltName extends PkiObject { - constructor(parameters = {}) { - super(); - this.altNames = getParametersValue(parameters, ALT_NAMES, AltName.defaultValues(ALT_NAMES)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ALT_NAMES: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.altNames || EMPTY_STRING), - value: GeneralName.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1t); - const asn1 = compareSchema(schema, schema, AltName.schema({ - names: { - altNames: ALT_NAMES - } - })); - AsnError.assertSchema(asn1, this.className); - if (ALT_NAMES in asn1.result) { - this.altNames = Array.from(asn1.result.altNames, element => new GeneralName({ schema: element })); - } - } - toSchema() { - return (new Sequence({ - value: Array.from(this.altNames, o => o.toSchema()) - })); - } - toJSON() { - return { - altNames: Array.from(this.altNames, o => o.toJSON()) - }; - } -} -AltName.CLASS_NAME = "AltName"; - -const TYPE$3 = "type"; -const VALUES$1 = "values"; -const CLEAR_PROPS$1s = [ - TYPE$3, - VALUES$1 -]; -class Attribute extends PkiObject { - constructor(parameters = {}) { - super(); - this.type = getParametersValue(parameters, TYPE$3, Attribute.defaultValues(TYPE$3)); - this.values = getParametersValue(parameters, VALUES$1, Attribute.defaultValues(VALUES$1)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TYPE$3: - return EMPTY_STRING; - case VALUES$1: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TYPE$3: - return (memberValue === EMPTY_STRING); - case VALUES$1: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.type || EMPTY_STRING) }), - new Set({ - name: (names.setName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.values || EMPTY_STRING), - value: new Any() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1s); - const asn1 = compareSchema(schema, schema, Attribute.schema({ - names: { - type: TYPE$3, - values: VALUES$1 - } - })); - AsnError.assertSchema(asn1, this.className); - this.type = asn1.result.type.valueBlock.toString(); - this.values = asn1.result.values; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.type }), - new Set({ - value: this.values - }) - ] - })); - } - toJSON() { - return { - type: this.type, - values: Array.from(this.values, o => o.toJSON()) - }; - } -} -Attribute.CLASS_NAME = "Attribute"; - -const NOT_BEFORE_TIME = "notBeforeTime"; -const NOT_AFTER_TIME = "notAfterTime"; -const CLEAR_PROPS$1r = [ - NOT_BEFORE_TIME, - NOT_AFTER_TIME, -]; -class AttCertValidityPeriod extends PkiObject { - constructor(parameters = {}) { - super(); - this.notBeforeTime = getParametersValue(parameters, NOT_BEFORE_TIME, AttCertValidityPeriod.defaultValues(NOT_BEFORE_TIME)); - this.notAfterTime = getParametersValue(parameters, NOT_AFTER_TIME, AttCertValidityPeriod.defaultValues(NOT_AFTER_TIME)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case NOT_BEFORE_TIME: - case NOT_AFTER_TIME: - return new Date(0, 0, 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new GeneralizedTime({ name: (names.notBeforeTime || EMPTY_STRING) }), - new GeneralizedTime({ name: (names.notAfterTime || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1r); - const asn1 = compareSchema(schema, schema, AttCertValidityPeriod.schema({ - names: { - notBeforeTime: NOT_BEFORE_TIME, - notAfterTime: NOT_AFTER_TIME - } - })); - AsnError.assertSchema(asn1, this.className); - this.notBeforeTime = asn1.result.notBeforeTime.toDate(); - this.notAfterTime = asn1.result.notAfterTime.toDate(); - } - toSchema() { - return (new Sequence({ - value: [ - new GeneralizedTime({ valueDate: this.notBeforeTime }), - new GeneralizedTime({ valueDate: this.notAfterTime }), - ] - })); - } - toJSON() { - return { - notBeforeTime: this.notBeforeTime, - notAfterTime: this.notAfterTime - }; - } -} -AttCertValidityPeriod.CLASS_NAME = "AttCertValidityPeriod"; +class PkiObject { + static blockName() { + return this.CLASS_NAME; + } + static fromBER(raw) { + const asn1 = fromBER(raw); + AsnError.assert(asn1, this.name); + try { + return new this({ schema: asn1.result }); + } + catch (e) { + throw new AsnError(`Cannot create '${this.CLASS_NAME}' from ASN.1 object`); + } + } + static defaultValues(memberName) { + throw new Error(`Invalid member name for ${this.CLASS_NAME} class: ${memberName}`); + } + static schema(parameters = {}) { + throw new Error(`Method '${this.CLASS_NAME}.schema' should be overridden`); + } + get className() { + return this.constructor.CLASS_NAME; + } + toString(encoding = "hex") { + let schema; + try { + schema = this.toSchema(); + } + catch { + schema = this.toSchema(true); + } + return Convert.ToString(schema.toBER(), encoding); + } +} +PkiObject.CLASS_NAME = "PkiObject"; -const NAMES = "names"; -const GENERAL_NAMES = "generalNames"; -class GeneralNames extends PkiObject { - constructor(parameters = {}) { - super(); - this.names = getParametersValue(parameters, NAMES, GeneralNames.defaultValues(NAMES)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case "names": - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}, optional = false) { - const names = getParametersValue(parameters, NAMES, {}); - return (new Sequence({ - optional, - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.generalNames || EMPTY_STRING), - value: GeneralName.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - NAMES, - GENERAL_NAMES - ]); - const asn1 = compareSchema(schema, schema, GeneralNames.schema({ - names: { - blockName: NAMES, - generalNames: GENERAL_NAMES - } - })); - AsnError.assertSchema(asn1, this.className); - this.names = Array.from(asn1.result.generalNames, element => new GeneralName({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.names, o => o.toSchema()) - })); - } - toJSON() { - return { - names: Array.from(this.names, o => o.toJSON()) - }; - } -} -GeneralNames.CLASS_NAME = "GeneralNames"; +function stringPrep(inputString) { + let isSpace = false; + let cutResult = EMPTY_STRING; + const result = inputString.trim(); + for (let i = 0; i < result.length; i++) { + if (result.charCodeAt(i) === 32) { + if (isSpace === false) + isSpace = true; + } + else { + if (isSpace) { + cutResult += " "; + isSpace = false; + } + cutResult += result[i]; + } + } + return cutResult.toLowerCase(); +} -const id_SubjectDirectoryAttributes = "2.5.29.9"; -const id_SubjectKeyIdentifier = "2.5.29.14"; -const id_KeyUsage = "2.5.29.15"; -const id_PrivateKeyUsagePeriod = "2.5.29.16"; -const id_SubjectAltName = "2.5.29.17"; -const id_IssuerAltName = "2.5.29.18"; -const id_BasicConstraints = "2.5.29.19"; -const id_CRLNumber = "2.5.29.20"; -const id_BaseCRLNumber = "2.5.29.27"; -const id_CRLReason = "2.5.29.21"; -const id_InvalidityDate = "2.5.29.24"; -const id_IssuingDistributionPoint = "2.5.29.28"; -const id_CertificateIssuer = "2.5.29.29"; -const id_NameConstraints = "2.5.29.30"; -const id_CRLDistributionPoints = "2.5.29.31"; -const id_FreshestCRL = "2.5.29.46"; -const id_CertificatePolicies = "2.5.29.32"; -const id_AnyPolicy = "2.5.29.32.0"; -const id_MicrosoftAppPolicies = "1.3.6.1.4.1.311.21.10"; -const id_PolicyMappings = "2.5.29.33"; -const id_AuthorityKeyIdentifier = "2.5.29.35"; -const id_PolicyConstraints = "2.5.29.36"; -const id_ExtKeyUsage = "2.5.29.37"; -const id_InhibitAnyPolicy = "2.5.29.54"; -const id_AuthorityInfoAccess = "1.3.6.1.5.5.7.1.1"; -const id_SubjectInfoAccess = "1.3.6.1.5.5.7.1.11"; -const id_SignedCertificateTimestampList = "1.3.6.1.4.1.11129.2.4.2"; -const id_MicrosoftCertTemplateV1 = "1.3.6.1.4.1.311.20.2"; -const id_MicrosoftPrevCaCertHash = "1.3.6.1.4.1.311.21.2"; -const id_MicrosoftCertTemplateV2 = "1.3.6.1.4.1.311.21.7"; -const id_MicrosoftCaVersion = "1.3.6.1.4.1.311.21.1"; -const id_QCStatements = "1.3.6.1.5.5.7.1.3"; -const id_ContentType_Data = "1.2.840.113549.1.7.1"; -const id_ContentType_SignedData = "1.2.840.113549.1.7.2"; -const id_ContentType_EnvelopedData = "1.2.840.113549.1.7.3"; -const id_ContentType_EncryptedData = "1.2.840.113549.1.7.6"; -const id_eContentType_TSTInfo = "1.2.840.113549.1.9.16.1.4"; -const id_CertBag_X509Certificate = "1.2.840.113549.1.9.22.1"; -const id_CertBag_SDSICertificate = "1.2.840.113549.1.9.22.2"; -const id_CertBag_AttributeCertificate = "1.2.840.113549.1.9.22.3"; -const id_CRLBag_X509CRL = "1.2.840.113549.1.9.23.1"; -const id_pkix = "1.3.6.1.5.5.7"; -const id_ad = `${id_pkix}.48`; -const id_PKIX_OCSP_Basic = `${id_ad}.1.1`; -const id_ad_caIssuers = `${id_ad}.2`; -const id_ad_ocsp = `${id_ad}.1`; -const id_sha1 = "1.3.14.3.2.26"; -const id_sha256 = "2.16.840.1.101.3.4.2.1"; -const id_sha384 = "2.16.840.1.101.3.4.2.2"; -const id_sha512 = "2.16.840.1.101.3.4.2.3"; +const TYPE$5 = "type"; +const VALUE$6 = "value"; +class AttributeTypeAndValue extends PkiObject { + constructor(parameters = {}) { + super(); + this.type = getParametersValue(parameters, TYPE$5, AttributeTypeAndValue.defaultValues(TYPE$5)); + this.value = getParametersValue(parameters, VALUE$6, AttributeTypeAndValue.defaultValues(VALUE$6)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TYPE$5: + return EMPTY_STRING; + case VALUE$6: + return {}; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.type || EMPTY_STRING) }), + new Any({ name: (names.value || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + TYPE$5, + "typeValue" + ]); + const asn1 = compareSchema(schema, schema, AttributeTypeAndValue.schema({ + names: { + type: TYPE$5, + value: "typeValue" + } + })); + AsnError.assertSchema(asn1, this.className); + this.type = asn1.result.type.valueBlock.toString(); + this.value = asn1.result.typeValue; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.type }), + this.value + ] + })); + } + toJSON() { + const _object = { + type: this.type + }; + if (Object.keys(this.value).length !== 0) { + _object.value = (this.value).toJSON(); + } + else { + _object.value = this.value; + } + return _object; + } + isEqual(compareTo) { + const stringBlockNames = [ + Utf8String.blockName(), + BmpString.blockName(), + UniversalString.blockName(), + NumericString.blockName(), + PrintableString.blockName(), + TeletexString.blockName(), + VideotexString.blockName(), + IA5String.blockName(), + GraphicString.blockName(), + VisibleString.blockName(), + GeneralString.blockName(), + CharacterString.blockName() + ]; + if (compareTo instanceof ArrayBuffer) { + return BufferSourceConverter.isEqual(this.value.valueBeforeDecodeView, compareTo); + } + if (compareTo.constructor.blockName() === AttributeTypeAndValue.blockName()) { + if (this.type !== compareTo.type) + return false; + const isStringPair = [false, false]; + const thisName = this.value.constructor.blockName(); + for (const name of stringBlockNames) { + if (thisName === name) { + isStringPair[0] = true; + } + if (compareTo.value.constructor.blockName() === name) { + isStringPair[1] = true; + } + } + if (isStringPair[0] !== isStringPair[1]) { + return false; + } + const isString = (isStringPair[0] && isStringPair[1]); + if (isString) { + const value1 = stringPrep(this.value.valueBlock.value); + const value2 = stringPrep(compareTo.value.valueBlock.value); + if (value1.localeCompare(value2) !== 0) + return false; + } + else { + if (!BufferSourceConverter.isEqual(this.value.valueBeforeDecodeView, compareTo.value.valueBeforeDecodeView)) + return false; + } + return true; + } + return false; + } +} +AttributeTypeAndValue.CLASS_NAME = "AttributeTypeAndValue"; -const KEY_IDENTIFIER$1 = "keyIdentifier"; -const AUTHORITY_CERT_ISSUER = "authorityCertIssuer"; -const AUTHORITY_CERT_SERIAL_NUMBER = "authorityCertSerialNumber"; -const CLEAR_PROPS$1q = [ - KEY_IDENTIFIER$1, - AUTHORITY_CERT_ISSUER, - AUTHORITY_CERT_SERIAL_NUMBER, -]; -class AuthorityKeyIdentifier extends PkiObject { - constructor(parameters = {}) { - super(); - if (KEY_IDENTIFIER$1 in parameters) { - this.keyIdentifier = getParametersValue(parameters, KEY_IDENTIFIER$1, AuthorityKeyIdentifier.defaultValues(KEY_IDENTIFIER$1)); - } - if (AUTHORITY_CERT_ISSUER in parameters) { - this.authorityCertIssuer = getParametersValue(parameters, AUTHORITY_CERT_ISSUER, AuthorityKeyIdentifier.defaultValues(AUTHORITY_CERT_ISSUER)); - } - if (AUTHORITY_CERT_SERIAL_NUMBER in parameters) { - this.authorityCertSerialNumber = getParametersValue(parameters, AUTHORITY_CERT_SERIAL_NUMBER, AuthorityKeyIdentifier.defaultValues(AUTHORITY_CERT_SERIAL_NUMBER)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case KEY_IDENTIFIER$1: - return new OctetString(); - case AUTHORITY_CERT_ISSUER: - return []; - case AUTHORITY_CERT_SERIAL_NUMBER: - return new Integer(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Primitive({ - name: (names.keyIdentifier || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - } - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new Repeated({ - name: (names.authorityCertIssuer || EMPTY_STRING), - value: GeneralName.schema() - }) - ] - }), - new Primitive({ - name: (names.authorityCertSerialNumber || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1q); - const asn1 = compareSchema(schema, schema, AuthorityKeyIdentifier.schema({ - names: { - keyIdentifier: KEY_IDENTIFIER$1, - authorityCertIssuer: AUTHORITY_CERT_ISSUER, - authorityCertSerialNumber: AUTHORITY_CERT_SERIAL_NUMBER - } - })); - AsnError.assertSchema(asn1, this.className); - if (KEY_IDENTIFIER$1 in asn1.result) - this.keyIdentifier = new OctetString({ valueHex: asn1.result.keyIdentifier.valueBlock.valueHex }); - if (AUTHORITY_CERT_ISSUER in asn1.result) - this.authorityCertIssuer = Array.from(asn1.result.authorityCertIssuer, o => new GeneralName({ schema: o })); - if (AUTHORITY_CERT_SERIAL_NUMBER in asn1.result) - this.authorityCertSerialNumber = new Integer({ valueHex: asn1.result.authorityCertSerialNumber.valueBlock.valueHex }); - } - toSchema() { - const outputArray = []; - if (this.keyIdentifier) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - valueHex: this.keyIdentifier.valueBlock.valueHexView - })); - } - if (this.authorityCertIssuer) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: Array.from(this.authorityCertIssuer, o => o.toSchema()) - })); - } - if (this.authorityCertSerialNumber) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - valueHex: this.authorityCertSerialNumber.valueBlock.valueHexView - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const object = {}; - if (this.keyIdentifier) { - object.keyIdentifier = this.keyIdentifier.toJSON(); - } - if (this.authorityCertIssuer) { - object.authorityCertIssuer = Array.from(this.authorityCertIssuer, o => o.toJSON()); - } - if (this.authorityCertSerialNumber) { - object.authorityCertSerialNumber = this.authorityCertSerialNumber.toJSON(); - } - return object; - } -} -AuthorityKeyIdentifier.CLASS_NAME = "AuthorityKeyIdentifier"; +const TYPE_AND_VALUES = "typesAndValues"; +const VALUE_BEFORE_DECODE = "valueBeforeDecode"; +const RDN = "RDN"; +class RelativeDistinguishedNames extends PkiObject { + constructor(parameters = {}) { + super(); + this.typesAndValues = getParametersValue(parameters, TYPE_AND_VALUES, RelativeDistinguishedNames.defaultValues(TYPE_AND_VALUES)); + this.valueBeforeDecode = getParametersValue(parameters, VALUE_BEFORE_DECODE, RelativeDistinguishedNames.defaultValues(VALUE_BEFORE_DECODE)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TYPE_AND_VALUES: + return []; + case VALUE_BEFORE_DECODE: + return EMPTY_BUFFER; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TYPE_AND_VALUES: + return (memberValue.length === 0); + case VALUE_BEFORE_DECODE: + return (memberValue.byteLength === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.repeatedSequence || EMPTY_STRING), + value: new Set({ + value: [ + new Repeated({ + name: (names.repeatedSet || EMPTY_STRING), + value: AttributeTypeAndValue.schema(names.typeAndValue || {}) + }) + ] + }) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + RDN, + TYPE_AND_VALUES + ]); + const asn1 = compareSchema(schema, schema, RelativeDistinguishedNames.schema({ + names: { + blockName: RDN, + repeatedSet: TYPE_AND_VALUES + } + })); + AsnError.assertSchema(asn1, this.className); + if (TYPE_AND_VALUES in asn1.result) { + this.typesAndValues = Array.from(asn1.result.typesAndValues, element => new AttributeTypeAndValue({ schema: element })); + } + this.valueBeforeDecode = asn1.result.RDN.valueBeforeDecodeView.slice().buffer; + } + toSchema() { + if (this.valueBeforeDecode.byteLength === 0) { + return (new Sequence({ + value: [new Set({ + value: Array.from(this.typesAndValues, o => o.toSchema()) + })] + })); + } + const asn1 = fromBER(this.valueBeforeDecode); + AsnError.assert(asn1, "RelativeDistinguishedNames"); + if (!(asn1.result instanceof Sequence)) { + throw new Error("ASN.1 result should be SEQUENCE"); + } + return asn1.result; + } + toJSON() { + return { + typesAndValues: Array.from(this.typesAndValues, o => o.toJSON()) + }; + } + isEqual(compareTo) { + if (compareTo instanceof RelativeDistinguishedNames) { + if (this.typesAndValues.length !== compareTo.typesAndValues.length) + return false; + for (const [index, typeAndValue] of this.typesAndValues.entries()) { + if (typeAndValue.isEqual(compareTo.typesAndValues[index]) === false) + return false; + } + return true; + } + if (compareTo instanceof ArrayBuffer) { + return isEqualBuffer(this.valueBeforeDecode, compareTo); + } + return false; + } +} +RelativeDistinguishedNames.CLASS_NAME = "RelativeDistinguishedNames"; -const PATH_LENGTH_CONSTRAINT = "pathLenConstraint"; -const CA = "cA"; -class BasicConstraints extends PkiObject { - constructor(parameters = {}) { - super(); - this.cA = getParametersValue(parameters, CA, false); - if (PATH_LENGTH_CONSTRAINT in parameters) { - this.pathLenConstraint = getParametersValue(parameters, PATH_LENGTH_CONSTRAINT, 0); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CA: - return false; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Boolean({ - optional: true, - name: (names.cA || EMPTY_STRING) - }), - new Integer({ - optional: true, - name: (names.pathLenConstraint || EMPTY_STRING) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - CA, - PATH_LENGTH_CONSTRAINT - ]); - const asn1 = compareSchema(schema, schema, BasicConstraints.schema({ - names: { - cA: CA, - pathLenConstraint: PATH_LENGTH_CONSTRAINT - } - })); - AsnError.assertSchema(asn1, this.className); - if (CA in asn1.result) { - this.cA = asn1.result.cA.valueBlock.value; - } - if (PATH_LENGTH_CONSTRAINT in asn1.result) { - if (asn1.result.pathLenConstraint.valueBlock.isHexOnly) { - this.pathLenConstraint = asn1.result.pathLenConstraint; - } - else { - this.pathLenConstraint = asn1.result.pathLenConstraint.valueBlock.valueDec; - } - } - } - toSchema() { - const outputArray = []; - if (this.cA !== BasicConstraints.defaultValues(CA)) - outputArray.push(new Boolean({ value: this.cA })); - if (PATH_LENGTH_CONSTRAINT in this) { - if (this.pathLenConstraint instanceof Integer) { - outputArray.push(this.pathLenConstraint); - } - else { - outputArray.push(new Integer({ value: this.pathLenConstraint })); - } - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const object = {}; - if (this.cA !== BasicConstraints.defaultValues(CA)) { - object.cA = this.cA; - } - if (PATH_LENGTH_CONSTRAINT in this) { - if (this.pathLenConstraint instanceof Integer) { - object.pathLenConstraint = this.pathLenConstraint.toJSON(); - } - else { - object.pathLenConstraint = this.pathLenConstraint; - } - } - return object; - } -} -BasicConstraints.CLASS_NAME = "BasicConstraints"; +const TYPE$4 = "type"; +const VALUE$5 = "value"; +function builtInStandardAttributes(parameters = {}, optional = false) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + optional, + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 2, + tagNumber: 1 + }, + name: (names.country_name || EMPTY_STRING), + value: [ + new Choice({ + value: [ + new NumericString(), + new PrintableString() + ] + }) + ] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 2, + tagNumber: 2 + }, + name: (names.administration_domain_name || EMPTY_STRING), + value: [ + new Choice({ + value: [ + new NumericString(), + new PrintableString() + ] + }) + ] + }), + new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + name: (names.network_address || EMPTY_STRING), + isHexOnly: true + }), + new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + name: (names.terminal_identifier || EMPTY_STRING), + isHexOnly: true + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + name: (names.private_domain_name || EMPTY_STRING), + value: [ + new Choice({ + value: [ + new NumericString(), + new PrintableString() + ] + }) + ] + }), + new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + name: (names.organization_name || EMPTY_STRING), + isHexOnly: true + }), + new Primitive({ + optional: true, + name: (names.numeric_user_identifier || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 4 + }, + isHexOnly: true + }), + new Constructed({ + optional: true, + name: (names.personal_name || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 5 + }, + value: [ + new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + isHexOnly: true + }), + new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + isHexOnly: true + }), + new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + isHexOnly: true + }), + new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + isHexOnly: true + }) + ] + }), + new Constructed({ + optional: true, + name: (names.organizational_unit_names || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 6 + }, + value: [ + new Repeated({ + value: new PrintableString() + }) + ] + }) + ] + })); +} +function builtInDomainDefinedAttributes(optional = false) { + return (new Sequence({ + optional, + value: [ + new PrintableString(), + new PrintableString() + ] + })); +} +function extensionAttributes(optional = false) { + return (new Set({ + optional, + value: [ + new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + isHexOnly: true + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [new Any()] + }) + ] + })); +} +class GeneralName extends PkiObject { + constructor(parameters = {}) { + super(); + this.type = getParametersValue(parameters, TYPE$4, GeneralName.defaultValues(TYPE$4)); + this.value = getParametersValue(parameters, VALUE$5, GeneralName.defaultValues(VALUE$5)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TYPE$4: + return 9; + case VALUE$5: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TYPE$4: + return (memberValue === GeneralName.defaultValues(memberName)); + case VALUE$5: + return (Object.keys(memberValue).length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Choice({ + value: [ + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier(), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Any()] + }) + ] + }), + new Primitive({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 1 + } + }), + new Primitive({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 2 + } + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + name: (names.blockName || EMPTY_STRING), + value: [ + builtInStandardAttributes((names.builtInStandardAttributes || {}), false), + builtInDomainDefinedAttributes(true), + extensionAttributes(true) + ] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 4 + }, + name: (names.blockName || EMPTY_STRING), + value: [RelativeDistinguishedNames.schema(names.directoryName || {})] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 5 + }, + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Choice({ + value: [ + new TeletexString(), + new PrintableString(), + new UniversalString(), + new Utf8String(), + new BmpString() + ] + }) + ] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new Choice({ + value: [ + new TeletexString(), + new PrintableString(), + new UniversalString(), + new Utf8String(), + new BmpString() + ] + }) + ] + }) + ] + }), + new Primitive({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 6 + } + }), + new Primitive({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 7 + } + }), + new Primitive({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 8 + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + "blockName", + "otherName", + "rfc822Name", + "dNSName", + "x400Address", + "directoryName", + "ediPartyName", + "uniformResourceIdentifier", + "iPAddress", + "registeredID" + ]); + const asn1 = compareSchema(schema, schema, GeneralName.schema({ + names: { + blockName: "blockName", + otherName: "otherName", + rfc822Name: "rfc822Name", + dNSName: "dNSName", + x400Address: "x400Address", + directoryName: { + names: { + blockName: "directoryName" + } + }, + ediPartyName: "ediPartyName", + uniformResourceIdentifier: "uniformResourceIdentifier", + iPAddress: "iPAddress", + registeredID: "registeredID" + } + })); + AsnError.assertSchema(asn1, this.className); + this.type = asn1.result.blockName.idBlock.tagNumber; + switch (this.type) { + case 0: + this.value = asn1.result.blockName; + break; + case 1: + case 2: + case 6: + { + const value = asn1.result.blockName; + value.idBlock.tagClass = 1; + value.idBlock.tagNumber = 22; + const valueBER = value.toBER(false); + const asnValue = fromBER(valueBER); + AsnError.assert(asnValue, "GeneralName value"); + this.value = asnValue.result.valueBlock.value; + } + break; + case 3: + this.value = asn1.result.blockName; + break; + case 4: + this.value = new RelativeDistinguishedNames({ schema: asn1.result.directoryName }); + break; + case 5: + this.value = asn1.result.ediPartyName; + break; + case 7: + this.value = new OctetString({ valueHex: asn1.result.blockName.valueBlock.valueHex }); + break; + case 8: + { + const value = asn1.result.blockName; + value.idBlock.tagClass = 1; + value.idBlock.tagNumber = 6; + const valueBER = value.toBER(false); + const asnValue = fromBER(valueBER); + AsnError.assert(asnValue, "GeneralName registeredID"); + this.value = asnValue.result.valueBlock.toString(); + } + break; + } + } + toSchema() { + switch (this.type) { + case 0: + case 3: + case 5: + return new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: this.type + }, + value: [ + this.value + ] + }); + case 1: + case 2: + case 6: + { + const value = new IA5String({ value: this.value }); + value.idBlock.tagClass = 3; + value.idBlock.tagNumber = this.type; + return value; + } + case 4: + return new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 4 + }, + value: [this.value.toSchema()] + }); + case 7: + { + const value = this.value; + value.idBlock.tagClass = 3; + value.idBlock.tagNumber = this.type; + return value; + } + case 8: + { + const value = new ObjectIdentifier({ value: this.value }); + value.idBlock.tagClass = 3; + value.idBlock.tagNumber = this.type; + return value; + } + default: + return GeneralName.schema(); + } + } + toJSON() { + const _object = { + type: this.type, + value: EMPTY_STRING + }; + if ((typeof this.value) === "string") + _object.value = this.value; + else { + try { + _object.value = this.value.toJSON(); + } + catch { + } + } + return _object; + } +} +GeneralName.CLASS_NAME = "GeneralName"; -const CERTIFICATE_INDEX = "certificateIndex"; -const KEY_INDEX = "keyIndex"; -class CAVersion extends PkiObject { - constructor(parameters = {}) { - super(); - this.certificateIndex = getParametersValue(parameters, CERTIFICATE_INDEX, CAVersion.defaultValues(CERTIFICATE_INDEX)); - this.keyIndex = getParametersValue(parameters, KEY_INDEX, CAVersion.defaultValues(KEY_INDEX)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CERTIFICATE_INDEX: - case KEY_INDEX: - return 0; - default: - return super.defaultValues(memberName); - } - } - static schema() { - return (new Integer()); - } - fromSchema(schema) { - if (schema.constructor.blockName() !== Integer.blockName()) { - throw new Error("Object's schema was not verified against input data for CAVersion"); - } - let value = schema.valueBlock.valueHex.slice(0); - const valueView = new Uint8Array(value); - switch (true) { - case (value.byteLength < 4): - { - const tempValue = new ArrayBuffer(4); - const tempValueView = new Uint8Array(tempValue); - tempValueView.set(valueView, 4 - value.byteLength); - value = tempValue.slice(0); - } - break; - case (value.byteLength > 4): - { - const tempValue = new ArrayBuffer(4); - const tempValueView = new Uint8Array(tempValue); - tempValueView.set(valueView.slice(0, 4)); - value = tempValue.slice(0); - } - break; - } - const keyIndexBuffer = value.slice(0, 2); - const keyIndexView8 = new Uint8Array(keyIndexBuffer); - let temp = keyIndexView8[0]; - keyIndexView8[0] = keyIndexView8[1]; - keyIndexView8[1] = temp; - const keyIndexView16 = new Uint16Array(keyIndexBuffer); - this.keyIndex = keyIndexView16[0]; - const certificateIndexBuffer = value.slice(2); - const certificateIndexView8 = new Uint8Array(certificateIndexBuffer); - temp = certificateIndexView8[0]; - certificateIndexView8[0] = certificateIndexView8[1]; - certificateIndexView8[1] = temp; - const certificateIndexView16 = new Uint16Array(certificateIndexBuffer); - this.certificateIndex = certificateIndexView16[0]; - } - toSchema() { - const certificateIndexBuffer = new ArrayBuffer(2); - const certificateIndexView = new Uint16Array(certificateIndexBuffer); - certificateIndexView[0] = this.certificateIndex; - const certificateIndexView8 = new Uint8Array(certificateIndexBuffer); - let temp = certificateIndexView8[0]; - certificateIndexView8[0] = certificateIndexView8[1]; - certificateIndexView8[1] = temp; - const keyIndexBuffer = new ArrayBuffer(2); - const keyIndexView = new Uint16Array(keyIndexBuffer); - keyIndexView[0] = this.keyIndex; - const keyIndexView8 = new Uint8Array(keyIndexBuffer); - temp = keyIndexView8[0]; - keyIndexView8[0] = keyIndexView8[1]; - keyIndexView8[1] = temp; - return (new Integer({ - valueHex: utilConcatBuf(keyIndexBuffer, certificateIndexBuffer) - })); - } - toJSON() { - return { - certificateIndex: this.certificateIndex, - keyIndex: this.keyIndex - }; - } -} -CAVersion.CLASS_NAME = "CAVersion"; +const ACCESS_METHOD = "accessMethod"; +const ACCESS_LOCATION = "accessLocation"; +const CLEAR_PROPS$1v = [ + ACCESS_METHOD, + ACCESS_LOCATION, +]; +class AccessDescription extends PkiObject { + constructor(parameters = {}) { + super(); + this.accessMethod = getParametersValue(parameters, ACCESS_METHOD, AccessDescription.defaultValues(ACCESS_METHOD)); + this.accessLocation = getParametersValue(parameters, ACCESS_LOCATION, AccessDescription.defaultValues(ACCESS_LOCATION)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ACCESS_METHOD: + return EMPTY_STRING; + case ACCESS_LOCATION: + return new GeneralName(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.accessMethod || EMPTY_STRING) }), + GeneralName.schema(names.accessLocation || {}) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1v); + const asn1 = compareSchema(schema, schema, AccessDescription.schema({ + names: { + accessMethod: ACCESS_METHOD, + accessLocation: { + names: { + blockName: ACCESS_LOCATION + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.accessMethod = asn1.result.accessMethod.valueBlock.toString(); + this.accessLocation = new GeneralName({ schema: asn1.result.accessLocation }); + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.accessMethod }), + this.accessLocation.toSchema() + ] + })); + } + toJSON() { + return { + accessMethod: this.accessMethod, + accessLocation: this.accessLocation.toJSON() + }; + } +} +AccessDescription.CLASS_NAME = "AccessDescription"; -const POLICY_QUALIFIER_ID = "policyQualifierId"; -const QUALIFIER = "qualifier"; -const CLEAR_PROPS$1p = [ - POLICY_QUALIFIER_ID, - QUALIFIER -]; -class PolicyQualifierInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.policyQualifierId = getParametersValue(parameters, POLICY_QUALIFIER_ID, PolicyQualifierInfo.defaultValues(POLICY_QUALIFIER_ID)); - this.qualifier = getParametersValue(parameters, QUALIFIER, PolicyQualifierInfo.defaultValues(QUALIFIER)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case POLICY_QUALIFIER_ID: - return EMPTY_STRING; - case QUALIFIER: - return new Any(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.policyQualifierId || EMPTY_STRING) }), - new Any({ name: (names.qualifier || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1p); - const asn1 = compareSchema(schema, schema, PolicyQualifierInfo.schema({ - names: { - policyQualifierId: POLICY_QUALIFIER_ID, - qualifier: QUALIFIER - } - })); - AsnError.assertSchema(asn1, this.className); - this.policyQualifierId = asn1.result.policyQualifierId.valueBlock.toString(); - this.qualifier = asn1.result.qualifier; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.policyQualifierId }), - this.qualifier - ] - })); - } - toJSON() { - return { - policyQualifierId: this.policyQualifierId, - qualifier: this.qualifier.toJSON() - }; - } -} -PolicyQualifierInfo.CLASS_NAME = "PolicyQualifierInfo"; +const SECONDS = "seconds"; +const MILLIS = "millis"; +const MICROS = "micros"; +class Accuracy extends PkiObject { + constructor(parameters = {}) { + super(); + if (SECONDS in parameters) { + this.seconds = getParametersValue(parameters, SECONDS, Accuracy.defaultValues(SECONDS)); + } + if (MILLIS in parameters) { + this.millis = getParametersValue(parameters, MILLIS, Accuracy.defaultValues(MILLIS)); + } + if (MICROS in parameters) { + this.micros = getParametersValue(parameters, MICROS, Accuracy.defaultValues(MICROS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case SECONDS: + case MILLIS: + case MICROS: + return 0; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case SECONDS: + case MILLIS: + case MICROS: + return (memberValue === Accuracy.defaultValues(memberName)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + optional: true, + value: [ + new Integer({ + optional: true, + name: (names.seconds || EMPTY_STRING) + }), + new Primitive({ + name: (names.millis || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + } + }), + new Primitive({ + name: (names.micros || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + SECONDS, + MILLIS, + MICROS, + ]); + const asn1 = compareSchema(schema, schema, Accuracy.schema({ + names: { + seconds: SECONDS, + millis: MILLIS, + micros: MICROS, + } + })); + AsnError.assertSchema(asn1, this.className); + if ("seconds" in asn1.result) { + this.seconds = asn1.result.seconds.valueBlock.valueDec; + } + if ("millis" in asn1.result) { + const intMillis = new Integer({ valueHex: asn1.result.millis.valueBlock.valueHex }); + this.millis = intMillis.valueBlock.valueDec; + } + if ("micros" in asn1.result) { + const intMicros = new Integer({ valueHex: asn1.result.micros.valueBlock.valueHex }); + this.micros = intMicros.valueBlock.valueDec; + } + } + toSchema() { + const outputArray = []; + if (this.seconds !== undefined) + outputArray.push(new Integer({ value: this.seconds })); + if (this.millis !== undefined) { + const intMillis = new Integer({ value: this.millis }); + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + valueHex: intMillis.valueBlock.valueHexView + })); + } + if (this.micros !== undefined) { + const intMicros = new Integer({ value: this.micros }); + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + valueHex: intMicros.valueBlock.valueHexView + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const _object = {}; + if (this.seconds !== undefined) + _object.seconds = this.seconds; + if (this.millis !== undefined) + _object.millis = this.millis; + if (this.micros !== undefined) + _object.micros = this.micros; + return _object; + } +} +Accuracy.CLASS_NAME = "Accuracy"; -const POLICY_IDENTIFIER = "policyIdentifier"; -const POLICY_QUALIFIERS = "policyQualifiers"; -const CLEAR_PROPS$1o = [ - POLICY_IDENTIFIER, - POLICY_QUALIFIERS -]; -class PolicyInformation extends PkiObject { - constructor(parameters = {}) { - super(); - this.policyIdentifier = getParametersValue(parameters, POLICY_IDENTIFIER, PolicyInformation.defaultValues(POLICY_IDENTIFIER)); - if (POLICY_QUALIFIERS in parameters) { - this.policyQualifiers = getParametersValue(parameters, POLICY_QUALIFIERS, PolicyInformation.defaultValues(POLICY_QUALIFIERS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case POLICY_IDENTIFIER: - return EMPTY_STRING; - case POLICY_QUALIFIERS: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.policyIdentifier || EMPTY_STRING) }), - new Sequence({ - optional: true, - value: [ - new Repeated({ - name: (names.policyQualifiers || EMPTY_STRING), - value: PolicyQualifierInfo.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1o); - const asn1 = compareSchema(schema, schema, PolicyInformation.schema({ - names: { - policyIdentifier: POLICY_IDENTIFIER, - policyQualifiers: POLICY_QUALIFIERS - } - })); - AsnError.assertSchema(asn1, this.className); - this.policyIdentifier = asn1.result.policyIdentifier.valueBlock.toString(); - if (POLICY_QUALIFIERS in asn1.result) { - this.policyQualifiers = Array.from(asn1.result.policyQualifiers, element => new PolicyQualifierInfo({ schema: element })); - } - } - toSchema() { - const outputArray = []; - outputArray.push(new ObjectIdentifier({ value: this.policyIdentifier })); - if (this.policyQualifiers) { - outputArray.push(new Sequence({ - value: Array.from(this.policyQualifiers, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - policyIdentifier: this.policyIdentifier - }; - if (this.policyQualifiers) - res.policyQualifiers = Array.from(this.policyQualifiers, o => o.toJSON()); - return res; - } -} -PolicyInformation.CLASS_NAME = "PolicyInformation"; +const ALGORITHM_ID = "algorithmId"; +const ALGORITHM_PARAMS = "algorithmParams"; +const ALGORITHM$2 = "algorithm"; +const PARAMS = "params"; +const CLEAR_PROPS$1u = [ + ALGORITHM$2, + PARAMS +]; +class AlgorithmIdentifier extends PkiObject { + constructor(parameters = {}) { + super(); + this.algorithmId = getParametersValue(parameters, ALGORITHM_ID, AlgorithmIdentifier.defaultValues(ALGORITHM_ID)); + if (ALGORITHM_PARAMS in parameters) { + this.algorithmParams = getParametersValue(parameters, ALGORITHM_PARAMS, AlgorithmIdentifier.defaultValues(ALGORITHM_PARAMS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ALGORITHM_ID: + return EMPTY_STRING; + case ALGORITHM_PARAMS: + return new Any(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case ALGORITHM_ID: + return (memberValue === EMPTY_STRING); + case ALGORITHM_PARAMS: + return (memberValue instanceof Any); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + optional: (names.optional || false), + value: [ + new ObjectIdentifier({ name: (names.algorithmIdentifier || EMPTY_STRING) }), + new Any({ name: (names.algorithmParams || EMPTY_STRING), optional: true }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1u); + const asn1 = compareSchema(schema, schema, AlgorithmIdentifier.schema({ + names: { + algorithmIdentifier: ALGORITHM$2, + algorithmParams: PARAMS + } + })); + AsnError.assertSchema(asn1, this.className); + this.algorithmId = asn1.result.algorithm.valueBlock.toString(); + if (PARAMS in asn1.result) { + this.algorithmParams = asn1.result.params; + } + } + toSchema() { + const outputArray = []; + outputArray.push(new ObjectIdentifier({ value: this.algorithmId })); + if (this.algorithmParams && !(this.algorithmParams instanceof Any)) { + outputArray.push(this.algorithmParams); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const object = { + algorithmId: this.algorithmId + }; + if (this.algorithmParams && !(this.algorithmParams instanceof Any)) { + object.algorithmParams = this.algorithmParams.toJSON(); + } + return object; + } + isEqual(algorithmIdentifier) { + if (!(algorithmIdentifier instanceof AlgorithmIdentifier)) { + return false; + } + if (this.algorithmId !== algorithmIdentifier.algorithmId) { + return false; + } + if (this.algorithmParams) { + if (algorithmIdentifier.algorithmParams) { + return JSON.stringify(this.algorithmParams) === JSON.stringify(algorithmIdentifier.algorithmParams); + } + return false; + } + if (algorithmIdentifier.algorithmParams) { + return false; + } + return true; + } +} +AlgorithmIdentifier.CLASS_NAME = "AlgorithmIdentifier"; -const CERTIFICATE_POLICIES = "certificatePolicies"; -const CLEAR_PROPS$1n = [ - CERTIFICATE_POLICIES, -]; -class CertificatePolicies extends PkiObject { - constructor(parameters = {}) { - super(); - this.certificatePolicies = getParametersValue(parameters, CERTIFICATE_POLICIES, CertificatePolicies.defaultValues(CERTIFICATE_POLICIES)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CERTIFICATE_POLICIES: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.certificatePolicies || EMPTY_STRING), - value: PolicyInformation.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1n); - const asn1 = compareSchema(schema, schema, CertificatePolicies.schema({ - names: { - certificatePolicies: CERTIFICATE_POLICIES - } - })); - AsnError.assertSchema(asn1, this.className); - this.certificatePolicies = Array.from(asn1.result.certificatePolicies, element => new PolicyInformation({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.certificatePolicies, o => o.toSchema()) - })); - } - toJSON() { - return { - certificatePolicies: Array.from(this.certificatePolicies, o => o.toJSON()) - }; - } -} -CertificatePolicies.CLASS_NAME = "CertificatePolicies"; +const ALT_NAMES = "altNames"; +const CLEAR_PROPS$1t = [ + ALT_NAMES +]; +class AltName extends PkiObject { + constructor(parameters = {}) { + super(); + this.altNames = getParametersValue(parameters, ALT_NAMES, AltName.defaultValues(ALT_NAMES)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ALT_NAMES: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.altNames || EMPTY_STRING), + value: GeneralName.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1t); + const asn1 = compareSchema(schema, schema, AltName.schema({ + names: { + altNames: ALT_NAMES + } + })); + AsnError.assertSchema(asn1, this.className); + if (ALT_NAMES in asn1.result) { + this.altNames = Array.from(asn1.result.altNames, element => new GeneralName({ schema: element })); + } + } + toSchema() { + return (new Sequence({ + value: Array.from(this.altNames, o => o.toSchema()) + })); + } + toJSON() { + return { + altNames: Array.from(this.altNames, o => o.toJSON()) + }; + } +} +AltName.CLASS_NAME = "AltName"; -const TEMPLATE_ID = "templateID"; -const TEMPLATE_MAJOR_VERSION = "templateMajorVersion"; -const TEMPLATE_MINOR_VERSION = "templateMinorVersion"; -const CLEAR_PROPS$1m = [ - TEMPLATE_ID, - TEMPLATE_MAJOR_VERSION, - TEMPLATE_MINOR_VERSION -]; -class CertificateTemplate extends PkiObject { - constructor(parameters = {}) { - super(); - this.templateID = getParametersValue(parameters, TEMPLATE_ID, CertificateTemplate.defaultValues(TEMPLATE_ID)); - if (TEMPLATE_MAJOR_VERSION in parameters) { - this.templateMajorVersion = getParametersValue(parameters, TEMPLATE_MAJOR_VERSION, CertificateTemplate.defaultValues(TEMPLATE_MAJOR_VERSION)); - } - if (TEMPLATE_MINOR_VERSION in parameters) { - this.templateMinorVersion = getParametersValue(parameters, TEMPLATE_MINOR_VERSION, CertificateTemplate.defaultValues(TEMPLATE_MINOR_VERSION)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TEMPLATE_ID: - return EMPTY_STRING; - case TEMPLATE_MAJOR_VERSION: - case TEMPLATE_MINOR_VERSION: - return 0; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.templateID || EMPTY_STRING) }), - new Integer({ - name: (names.templateMajorVersion || EMPTY_STRING), - optional: true - }), - new Integer({ - name: (names.templateMinorVersion || EMPTY_STRING), - optional: true - }), - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1m); - const asn1 = compareSchema(schema, schema, CertificateTemplate.schema({ - names: { - templateID: TEMPLATE_ID, - templateMajorVersion: TEMPLATE_MAJOR_VERSION, - templateMinorVersion: TEMPLATE_MINOR_VERSION - } - })); - AsnError.assertSchema(asn1, this.className); - this.templateID = asn1.result.templateID.valueBlock.toString(); - if (TEMPLATE_MAJOR_VERSION in asn1.result) { - this.templateMajorVersion = asn1.result.templateMajorVersion.valueBlock.valueDec; - } - if (TEMPLATE_MINOR_VERSION in asn1.result) { - this.templateMinorVersion = asn1.result.templateMinorVersion.valueBlock.valueDec; - } - } - toSchema() { - const outputArray = []; - outputArray.push(new ObjectIdentifier({ value: this.templateID })); - if (TEMPLATE_MAJOR_VERSION in this) { - outputArray.push(new Integer({ value: this.templateMajorVersion })); - } - if (TEMPLATE_MINOR_VERSION in this) { - outputArray.push(new Integer({ value: this.templateMinorVersion })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - templateID: this.templateID - }; - if (TEMPLATE_MAJOR_VERSION in this) - res.templateMajorVersion = this.templateMajorVersion; - if (TEMPLATE_MINOR_VERSION in this) - res.templateMinorVersion = this.templateMinorVersion; - return res; - } +const TYPE$3 = "type"; +const VALUES$1 = "values"; +const CLEAR_PROPS$1s = [ + TYPE$3, + VALUES$1 +]; +class Attribute extends PkiObject { + constructor(parameters = {}) { + super(); + this.type = getParametersValue(parameters, TYPE$3, Attribute.defaultValues(TYPE$3)); + this.values = getParametersValue(parameters, VALUES$1, Attribute.defaultValues(VALUES$1)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TYPE$3: + return EMPTY_STRING; + case VALUES$1: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TYPE$3: + return (memberValue === EMPTY_STRING); + case VALUES$1: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.type || EMPTY_STRING) }), + new Set({ + name: (names.setName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.values || EMPTY_STRING), + value: new Any() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1s); + const asn1 = compareSchema(schema, schema, Attribute.schema({ + names: { + type: TYPE$3, + values: VALUES$1 + } + })); + AsnError.assertSchema(asn1, this.className); + this.type = asn1.result.type.valueBlock.toString(); + this.values = asn1.result.values; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.type }), + new Set({ + value: this.values + }) + ] + })); + } + toJSON() { + return { + type: this.type, + values: Array.from(this.values, o => o.toJSON()) + }; + } } +Attribute.CLASS_NAME = "Attribute"; -const DISTRIBUTION_POINT$1 = "distributionPoint"; -const DISTRIBUTION_POINT_NAMES$1 = "distributionPointNames"; -const REASONS = "reasons"; -const CRL_ISSUER = "cRLIssuer"; -const CRL_ISSUER_NAMES = "cRLIssuerNames"; -const CLEAR_PROPS$1l = [ - DISTRIBUTION_POINT$1, - DISTRIBUTION_POINT_NAMES$1, - REASONS, - CRL_ISSUER, - CRL_ISSUER_NAMES, -]; -class DistributionPoint extends PkiObject { - constructor(parameters = {}) { - super(); - if (DISTRIBUTION_POINT$1 in parameters) { - this.distributionPoint = getParametersValue(parameters, DISTRIBUTION_POINT$1, DistributionPoint.defaultValues(DISTRIBUTION_POINT$1)); - } - if (REASONS in parameters) { - this.reasons = getParametersValue(parameters, REASONS, DistributionPoint.defaultValues(REASONS)); - } - if (CRL_ISSUER in parameters) { - this.cRLIssuer = getParametersValue(parameters, CRL_ISSUER, DistributionPoint.defaultValues(CRL_ISSUER)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case DISTRIBUTION_POINT$1: - return []; - case REASONS: - return new BitString(); - case CRL_ISSUER: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Choice({ - value: [ - new Constructed({ - name: (names.distributionPoint || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Repeated({ - name: (names.distributionPointNames || EMPTY_STRING), - value: GeneralName.schema() - }) - ] - }), - new Constructed({ - name: (names.distributionPoint || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: RelativeDistinguishedNames.schema().valueBlock.value - }) - ] - }) - ] - }), - new Primitive({ - name: (names.reasons || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - } - }), - new Constructed({ - name: (names.cRLIssuer || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [ - new Repeated({ - name: (names.cRLIssuerNames || EMPTY_STRING), - value: GeneralName.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1l); - const asn1 = compareSchema(schema, schema, DistributionPoint.schema({ - names: { - distributionPoint: DISTRIBUTION_POINT$1, - distributionPointNames: DISTRIBUTION_POINT_NAMES$1, - reasons: REASONS, - cRLIssuer: CRL_ISSUER, - cRLIssuerNames: CRL_ISSUER_NAMES - } - })); - AsnError.assertSchema(asn1, this.className); - if (DISTRIBUTION_POINT$1 in asn1.result) { - if (asn1.result.distributionPoint.idBlock.tagNumber === 0) { - this.distributionPoint = Array.from(asn1.result.distributionPointNames, element => new GeneralName({ schema: element })); - } - if (asn1.result.distributionPoint.idBlock.tagNumber === 1) { - this.distributionPoint = new RelativeDistinguishedNames({ - schema: new Sequence({ - value: asn1.result.distributionPoint.valueBlock.value - }) - }); - } - } - if (REASONS in asn1.result) { - this.reasons = new BitString({ valueHex: asn1.result.reasons.valueBlock.valueHex }); - } - if (CRL_ISSUER in asn1.result) { - this.cRLIssuer = Array.from(asn1.result.cRLIssuerNames, element => new GeneralName({ schema: element })); - } - } - toSchema() { - const outputArray = []; - if (this.distributionPoint) { - let internalValue; - if (this.distributionPoint instanceof Array) { - internalValue = new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: Array.from(this.distributionPoint, o => o.toSchema()) - }); - } - else { - internalValue = new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [this.distributionPoint.toSchema()] - }); - } - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [internalValue] - })); - } - if (this.reasons) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - valueHex: this.reasons.valueBlock.valueHexView - })); - } - if (this.cRLIssuer) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: Array.from(this.cRLIssuer, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const object = {}; - if (this.distributionPoint) { - if (this.distributionPoint instanceof Array) { - object.distributionPoint = Array.from(this.distributionPoint, o => o.toJSON()); - } - else { - object.distributionPoint = this.distributionPoint.toJSON(); - } - } - if (this.reasons) { - object.reasons = this.reasons.toJSON(); - } - if (this.cRLIssuer) { - object.cRLIssuer = Array.from(this.cRLIssuer, o => o.toJSON()); - } - return object; - } -} -DistributionPoint.CLASS_NAME = "DistributionPoint"; +const NOT_BEFORE_TIME = "notBeforeTime"; +const NOT_AFTER_TIME = "notAfterTime"; +const CLEAR_PROPS$1r = [ + NOT_BEFORE_TIME, + NOT_AFTER_TIME, +]; +class AttCertValidityPeriod extends PkiObject { + constructor(parameters = {}) { + super(); + this.notBeforeTime = getParametersValue(parameters, NOT_BEFORE_TIME, AttCertValidityPeriod.defaultValues(NOT_BEFORE_TIME)); + this.notAfterTime = getParametersValue(parameters, NOT_AFTER_TIME, AttCertValidityPeriod.defaultValues(NOT_AFTER_TIME)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case NOT_BEFORE_TIME: + case NOT_AFTER_TIME: + return new Date(0, 0, 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new GeneralizedTime({ name: (names.notBeforeTime || EMPTY_STRING) }), + new GeneralizedTime({ name: (names.notAfterTime || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1r); + const asn1 = compareSchema(schema, schema, AttCertValidityPeriod.schema({ + names: { + notBeforeTime: NOT_BEFORE_TIME, + notAfterTime: NOT_AFTER_TIME + } + })); + AsnError.assertSchema(asn1, this.className); + this.notBeforeTime = asn1.result.notBeforeTime.toDate(); + this.notAfterTime = asn1.result.notAfterTime.toDate(); + } + toSchema() { + return (new Sequence({ + value: [ + new GeneralizedTime({ valueDate: this.notBeforeTime }), + new GeneralizedTime({ valueDate: this.notAfterTime }), + ] + })); + } + toJSON() { + return { + notBeforeTime: this.notBeforeTime, + notAfterTime: this.notAfterTime + }; + } +} +AttCertValidityPeriod.CLASS_NAME = "AttCertValidityPeriod"; -const DISTRIBUTION_POINTS = "distributionPoints"; -const CLEAR_PROPS$1k = [ - DISTRIBUTION_POINTS -]; -class CRLDistributionPoints extends PkiObject { - constructor(parameters = {}) { - super(); - this.distributionPoints = getParametersValue(parameters, DISTRIBUTION_POINTS, CRLDistributionPoints.defaultValues(DISTRIBUTION_POINTS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case DISTRIBUTION_POINTS: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.distributionPoints || EMPTY_STRING), - value: DistributionPoint.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1k); - const asn1 = compareSchema(schema, schema, CRLDistributionPoints.schema({ - names: { - distributionPoints: DISTRIBUTION_POINTS - } - })); - AsnError.assertSchema(asn1, this.className); - this.distributionPoints = Array.from(asn1.result.distributionPoints, element => new DistributionPoint({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.distributionPoints, o => o.toSchema()) - })); - } - toJSON() { - return { - distributionPoints: Array.from(this.distributionPoints, o => o.toJSON()) - }; - } -} -CRLDistributionPoints.CLASS_NAME = "CRLDistributionPoints"; +const NAMES = "names"; +const GENERAL_NAMES = "generalNames"; +class GeneralNames extends PkiObject { + constructor(parameters = {}) { + super(); + this.names = getParametersValue(parameters, NAMES, GeneralNames.defaultValues(NAMES)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case "names": + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}, optional = false) { + const names = getParametersValue(parameters, NAMES, {}); + return (new Sequence({ + optional, + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.generalNames || EMPTY_STRING), + value: GeneralName.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + NAMES, + GENERAL_NAMES + ]); + const asn1 = compareSchema(schema, schema, GeneralNames.schema({ + names: { + blockName: NAMES, + generalNames: GENERAL_NAMES + } + })); + AsnError.assertSchema(asn1, this.className); + this.names = Array.from(asn1.result.generalNames, element => new GeneralName({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.names, o => o.toSchema()) + })); + } + toJSON() { + return { + names: Array.from(this.names, o => o.toJSON()) + }; + } +} +GeneralNames.CLASS_NAME = "GeneralNames"; -const KEY_PURPOSES = "keyPurposes"; -const CLEAR_PROPS$1j = [ - KEY_PURPOSES, -]; -class ExtKeyUsage extends PkiObject { - constructor(parameters = {}) { - super(); - this.keyPurposes = getParametersValue(parameters, KEY_PURPOSES, ExtKeyUsage.defaultValues(KEY_PURPOSES)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case KEY_PURPOSES: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.keyPurposes || EMPTY_STRING), - value: new ObjectIdentifier() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1j); - const asn1 = compareSchema(schema, schema, ExtKeyUsage.schema({ - names: { - keyPurposes: KEY_PURPOSES - } - })); - AsnError.assertSchema(asn1, this.className); - this.keyPurposes = Array.from(asn1.result.keyPurposes, (element) => element.valueBlock.toString()); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.keyPurposes, element => new ObjectIdentifier({ value: element })) - })); - } - toJSON() { - return { - keyPurposes: Array.from(this.keyPurposes) - }; - } -} -ExtKeyUsage.CLASS_NAME = "ExtKeyUsage"; +const id_SubjectDirectoryAttributes = "2.5.29.9"; +const id_SubjectKeyIdentifier = "2.5.29.14"; +const id_KeyUsage = "2.5.29.15"; +const id_PrivateKeyUsagePeriod = "2.5.29.16"; +const id_SubjectAltName = "2.5.29.17"; +const id_IssuerAltName = "2.5.29.18"; +const id_BasicConstraints = "2.5.29.19"; +const id_CRLNumber = "2.5.29.20"; +const id_BaseCRLNumber = "2.5.29.27"; +const id_CRLReason = "2.5.29.21"; +const id_InvalidityDate = "2.5.29.24"; +const id_IssuingDistributionPoint = "2.5.29.28"; +const id_CertificateIssuer = "2.5.29.29"; +const id_NameConstraints = "2.5.29.30"; +const id_CRLDistributionPoints = "2.5.29.31"; +const id_FreshestCRL = "2.5.29.46"; +const id_CertificatePolicies = "2.5.29.32"; +const id_AnyPolicy = "2.5.29.32.0"; +const id_MicrosoftAppPolicies = "1.3.6.1.4.1.311.21.10"; +const id_PolicyMappings = "2.5.29.33"; +const id_AuthorityKeyIdentifier = "2.5.29.35"; +const id_PolicyConstraints = "2.5.29.36"; +const id_ExtKeyUsage = "2.5.29.37"; +const id_InhibitAnyPolicy = "2.5.29.54"; +const id_AuthorityInfoAccess = "1.3.6.1.5.5.7.1.1"; +const id_SubjectInfoAccess = "1.3.6.1.5.5.7.1.11"; +const id_SignedCertificateTimestampList = "1.3.6.1.4.1.11129.2.4.2"; +const id_MicrosoftCertTemplateV1 = "1.3.6.1.4.1.311.20.2"; +const id_MicrosoftPrevCaCertHash = "1.3.6.1.4.1.311.21.2"; +const id_MicrosoftCertTemplateV2 = "1.3.6.1.4.1.311.21.7"; +const id_MicrosoftCaVersion = "1.3.6.1.4.1.311.21.1"; +const id_QCStatements = "1.3.6.1.5.5.7.1.3"; +const id_ContentType_Data = "1.2.840.113549.1.7.1"; +const id_ContentType_SignedData = "1.2.840.113549.1.7.2"; +const id_ContentType_EnvelopedData = "1.2.840.113549.1.7.3"; +const id_ContentType_EncryptedData = "1.2.840.113549.1.7.6"; +const id_eContentType_TSTInfo = "1.2.840.113549.1.9.16.1.4"; +const id_CertBag_X509Certificate = "1.2.840.113549.1.9.22.1"; +const id_CertBag_SDSICertificate = "1.2.840.113549.1.9.22.2"; +const id_CertBag_AttributeCertificate = "1.2.840.113549.1.9.22.3"; +const id_CRLBag_X509CRL = "1.2.840.113549.1.9.23.1"; +const id_pkix = "1.3.6.1.5.5.7"; +const id_ad = `${id_pkix}.48`; +const id_PKIX_OCSP_Basic = `${id_ad}.1.1`; +const id_ad_caIssuers = `${id_ad}.2`; +const id_ad_ocsp = `${id_ad}.1`; +const id_sha1 = "1.3.14.3.2.26"; +const id_sha256 = "2.16.840.1.101.3.4.2.1"; +const id_sha384 = "2.16.840.1.101.3.4.2.2"; +const id_sha512 = "2.16.840.1.101.3.4.2.3"; -const ACCESS_DESCRIPTIONS = "accessDescriptions"; -class InfoAccess extends PkiObject { - constructor(parameters = {}) { - super(); - this.accessDescriptions = getParametersValue(parameters, ACCESS_DESCRIPTIONS, InfoAccess.defaultValues(ACCESS_DESCRIPTIONS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ACCESS_DESCRIPTIONS: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.accessDescriptions || EMPTY_STRING), - value: AccessDescription.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - ACCESS_DESCRIPTIONS - ]); - const asn1 = compareSchema(schema, schema, InfoAccess.schema({ - names: { - accessDescriptions: ACCESS_DESCRIPTIONS - } - })); - AsnError.assertSchema(asn1, this.className); - this.accessDescriptions = Array.from(asn1.result.accessDescriptions, element => new AccessDescription({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.accessDescriptions, o => o.toSchema()) - })); - } - toJSON() { - return { - accessDescriptions: Array.from(this.accessDescriptions, o => o.toJSON()) - }; - } -} -InfoAccess.CLASS_NAME = "InfoAccess"; +const KEY_IDENTIFIER$1 = "keyIdentifier"; +const AUTHORITY_CERT_ISSUER = "authorityCertIssuer"; +const AUTHORITY_CERT_SERIAL_NUMBER = "authorityCertSerialNumber"; +const CLEAR_PROPS$1q = [ + KEY_IDENTIFIER$1, + AUTHORITY_CERT_ISSUER, + AUTHORITY_CERT_SERIAL_NUMBER, +]; +class AuthorityKeyIdentifier extends PkiObject { + constructor(parameters = {}) { + super(); + if (KEY_IDENTIFIER$1 in parameters) { + this.keyIdentifier = getParametersValue(parameters, KEY_IDENTIFIER$1, AuthorityKeyIdentifier.defaultValues(KEY_IDENTIFIER$1)); + } + if (AUTHORITY_CERT_ISSUER in parameters) { + this.authorityCertIssuer = getParametersValue(parameters, AUTHORITY_CERT_ISSUER, AuthorityKeyIdentifier.defaultValues(AUTHORITY_CERT_ISSUER)); + } + if (AUTHORITY_CERT_SERIAL_NUMBER in parameters) { + this.authorityCertSerialNumber = getParametersValue(parameters, AUTHORITY_CERT_SERIAL_NUMBER, AuthorityKeyIdentifier.defaultValues(AUTHORITY_CERT_SERIAL_NUMBER)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case KEY_IDENTIFIER$1: + return new OctetString(); + case AUTHORITY_CERT_ISSUER: + return []; + case AUTHORITY_CERT_SERIAL_NUMBER: + return new Integer(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Primitive({ + name: (names.keyIdentifier || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + } + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new Repeated({ + name: (names.authorityCertIssuer || EMPTY_STRING), + value: GeneralName.schema() + }) + ] + }), + new Primitive({ + name: (names.authorityCertSerialNumber || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1q); + const asn1 = compareSchema(schema, schema, AuthorityKeyIdentifier.schema({ + names: { + keyIdentifier: KEY_IDENTIFIER$1, + authorityCertIssuer: AUTHORITY_CERT_ISSUER, + authorityCertSerialNumber: AUTHORITY_CERT_SERIAL_NUMBER + } + })); + AsnError.assertSchema(asn1, this.className); + if (KEY_IDENTIFIER$1 in asn1.result) + this.keyIdentifier = new OctetString({ valueHex: asn1.result.keyIdentifier.valueBlock.valueHex }); + if (AUTHORITY_CERT_ISSUER in asn1.result) + this.authorityCertIssuer = Array.from(asn1.result.authorityCertIssuer, o => new GeneralName({ schema: o })); + if (AUTHORITY_CERT_SERIAL_NUMBER in asn1.result) + this.authorityCertSerialNumber = new Integer({ valueHex: asn1.result.authorityCertSerialNumber.valueBlock.valueHex }); + } + toSchema() { + const outputArray = []; + if (this.keyIdentifier) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + valueHex: this.keyIdentifier.valueBlock.valueHexView + })); + } + if (this.authorityCertIssuer) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: Array.from(this.authorityCertIssuer, o => o.toSchema()) + })); + } + if (this.authorityCertSerialNumber) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + valueHex: this.authorityCertSerialNumber.valueBlock.valueHexView + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const object = {}; + if (this.keyIdentifier) { + object.keyIdentifier = this.keyIdentifier.toJSON(); + } + if (this.authorityCertIssuer) { + object.authorityCertIssuer = Array.from(this.authorityCertIssuer, o => o.toJSON()); + } + if (this.authorityCertSerialNumber) { + object.authorityCertSerialNumber = this.authorityCertSerialNumber.toJSON(); + } + return object; + } +} +AuthorityKeyIdentifier.CLASS_NAME = "AuthorityKeyIdentifier"; -const DISTRIBUTION_POINT = "distributionPoint"; -const DISTRIBUTION_POINT_NAMES = "distributionPointNames"; -const ONLY_CONTAINS_USER_CERTS = "onlyContainsUserCerts"; -const ONLY_CONTAINS_CA_CERTS = "onlyContainsCACerts"; -const ONLY_SOME_REASON = "onlySomeReasons"; -const INDIRECT_CRL = "indirectCRL"; -const ONLY_CONTAINS_ATTRIBUTE_CERTS = "onlyContainsAttributeCerts"; -const CLEAR_PROPS$1i = [ - DISTRIBUTION_POINT, - DISTRIBUTION_POINT_NAMES, - ONLY_CONTAINS_USER_CERTS, - ONLY_CONTAINS_CA_CERTS, - ONLY_SOME_REASON, - INDIRECT_CRL, - ONLY_CONTAINS_ATTRIBUTE_CERTS, -]; -class IssuingDistributionPoint extends PkiObject { - constructor(parameters = {}) { - super(); - if (DISTRIBUTION_POINT in parameters) { - this.distributionPoint = getParametersValue(parameters, DISTRIBUTION_POINT, IssuingDistributionPoint.defaultValues(DISTRIBUTION_POINT)); - } - this.onlyContainsUserCerts = getParametersValue(parameters, ONLY_CONTAINS_USER_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS)); - this.onlyContainsCACerts = getParametersValue(parameters, ONLY_CONTAINS_CA_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS)); - if (ONLY_SOME_REASON in parameters) { - this.onlySomeReasons = getParametersValue(parameters, ONLY_SOME_REASON, IssuingDistributionPoint.defaultValues(ONLY_SOME_REASON)); - } - this.indirectCRL = getParametersValue(parameters, INDIRECT_CRL, IssuingDistributionPoint.defaultValues(INDIRECT_CRL)); - this.onlyContainsAttributeCerts = getParametersValue(parameters, ONLY_CONTAINS_ATTRIBUTE_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case DISTRIBUTION_POINT: - return []; - case ONLY_CONTAINS_USER_CERTS: - return false; - case ONLY_CONTAINS_CA_CERTS: - return false; - case ONLY_SOME_REASON: - return 0; - case INDIRECT_CRL: - return false; - case ONLY_CONTAINS_ATTRIBUTE_CERTS: - return false; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Choice({ - value: [ - new Constructed({ - name: (names.distributionPoint || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Repeated({ - name: (names.distributionPointNames || EMPTY_STRING), - value: GeneralName.schema() - }) - ] - }), - new Constructed({ - name: (names.distributionPoint || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: RelativeDistinguishedNames.schema().valueBlock.value - }) - ] - }) - ] - }), - new Primitive({ - name: (names.onlyContainsUserCerts || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - } - }), - new Primitive({ - name: (names.onlyContainsCACerts || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - } - }), - new Primitive({ - name: (names.onlySomeReasons || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 3 - } - }), - new Primitive({ - name: (names.indirectCRL || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 4 - } - }), - new Primitive({ - name: (names.onlyContainsAttributeCerts || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 5 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1i); - const asn1 = compareSchema(schema, schema, IssuingDistributionPoint.schema({ - names: { - distributionPoint: DISTRIBUTION_POINT, - distributionPointNames: DISTRIBUTION_POINT_NAMES, - onlyContainsUserCerts: ONLY_CONTAINS_USER_CERTS, - onlyContainsCACerts: ONLY_CONTAINS_CA_CERTS, - onlySomeReasons: ONLY_SOME_REASON, - indirectCRL: INDIRECT_CRL, - onlyContainsAttributeCerts: ONLY_CONTAINS_ATTRIBUTE_CERTS - } - })); - AsnError.assertSchema(asn1, this.className); - if (DISTRIBUTION_POINT in asn1.result) { - switch (true) { - case (asn1.result.distributionPoint.idBlock.tagNumber === 0): - this.distributionPoint = Array.from(asn1.result.distributionPointNames, element => new GeneralName({ schema: element })); - break; - case (asn1.result.distributionPoint.idBlock.tagNumber === 1): - { - this.distributionPoint = new RelativeDistinguishedNames({ - schema: new Sequence({ - value: asn1.result.distributionPoint.valueBlock.value - }) - }); - } - break; - default: - throw new Error("Unknown tagNumber for distributionPoint: {$asn1.result.distributionPoint.idBlock.tagNumber}"); - } - } - if (ONLY_CONTAINS_USER_CERTS in asn1.result) { - const view = new Uint8Array(asn1.result.onlyContainsUserCerts.valueBlock.valueHex); - this.onlyContainsUserCerts = (view[0] !== 0x00); - } - if (ONLY_CONTAINS_CA_CERTS in asn1.result) { - const view = new Uint8Array(asn1.result.onlyContainsCACerts.valueBlock.valueHex); - this.onlyContainsCACerts = (view[0] !== 0x00); - } - if (ONLY_SOME_REASON in asn1.result) { - const view = new Uint8Array(asn1.result.onlySomeReasons.valueBlock.valueHex); - this.onlySomeReasons = view[0]; - } - if (INDIRECT_CRL in asn1.result) { - const view = new Uint8Array(asn1.result.indirectCRL.valueBlock.valueHex); - this.indirectCRL = (view[0] !== 0x00); - } - if (ONLY_CONTAINS_ATTRIBUTE_CERTS in asn1.result) { - const view = new Uint8Array(asn1.result.onlyContainsAttributeCerts.valueBlock.valueHex); - this.onlyContainsAttributeCerts = (view[0] !== 0x00); - } - } - toSchema() { - const outputArray = []; - if (this.distributionPoint) { - let value; - if (this.distributionPoint instanceof Array) { - value = new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: Array.from(this.distributionPoint, o => o.toSchema()) - }); - } - else { - value = this.distributionPoint.toSchema(); - value.idBlock.tagClass = 3; - value.idBlock.tagNumber = 1; - } - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [value] - })); - } - if (this.onlyContainsUserCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS)) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - valueHex: (new Uint8Array([0xFF])).buffer - })); - } - if (this.onlyContainsCACerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS)) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - valueHex: (new Uint8Array([0xFF])).buffer - })); - } - if (this.onlySomeReasons !== undefined) { - const buffer = new ArrayBuffer(1); - const view = new Uint8Array(buffer); - view[0] = this.onlySomeReasons; - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - valueHex: buffer - })); - } - if (this.indirectCRL !== IssuingDistributionPoint.defaultValues(INDIRECT_CRL)) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 4 - }, - valueHex: (new Uint8Array([0xFF])).buffer - })); - } - if (this.onlyContainsAttributeCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS)) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 5 - }, - valueHex: (new Uint8Array([0xFF])).buffer - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const obj = {}; - if (this.distributionPoint) { - if (this.distributionPoint instanceof Array) { - obj.distributionPoint = Array.from(this.distributionPoint, o => o.toJSON()); - } - else { - obj.distributionPoint = this.distributionPoint.toJSON(); - } - } - if (this.onlyContainsUserCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS)) { - obj.onlyContainsUserCerts = this.onlyContainsUserCerts; - } - if (this.onlyContainsCACerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS)) { - obj.onlyContainsCACerts = this.onlyContainsCACerts; - } - if (ONLY_SOME_REASON in this) { - obj.onlySomeReasons = this.onlySomeReasons; - } - if (this.indirectCRL !== IssuingDistributionPoint.defaultValues(INDIRECT_CRL)) { - obj.indirectCRL = this.indirectCRL; - } - if (this.onlyContainsAttributeCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS)) { - obj.onlyContainsAttributeCerts = this.onlyContainsAttributeCerts; - } - return obj; - } -} -IssuingDistributionPoint.CLASS_NAME = "IssuingDistributionPoint"; - -const BASE = "base"; -const MINIMUM = "minimum"; -const MAXIMUM = "maximum"; -const CLEAR_PROPS$1h = [ - BASE, - MINIMUM, - MAXIMUM -]; -class GeneralSubtree extends PkiObject { - constructor(parameters = {}) { - super(); - this.base = getParametersValue(parameters, BASE, GeneralSubtree.defaultValues(BASE)); - this.minimum = getParametersValue(parameters, MINIMUM, GeneralSubtree.defaultValues(MINIMUM)); - if (MAXIMUM in parameters) { - this.maximum = getParametersValue(parameters, MAXIMUM, GeneralSubtree.defaultValues(MAXIMUM)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case BASE: - return new GeneralName(); - case MINIMUM: - return 0; - case MAXIMUM: - return 0; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - GeneralName.schema(names.base || {}), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Integer({ name: (names.minimum || EMPTY_STRING) })] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [new Integer({ name: (names.maximum || EMPTY_STRING) })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1h); - const asn1 = compareSchema(schema, schema, GeneralSubtree.schema({ - names: { - base: { - names: { - blockName: BASE - } - }, - minimum: MINIMUM, - maximum: MAXIMUM - } - })); - AsnError.assertSchema(asn1, this.className); - this.base = new GeneralName({ schema: asn1.result.base }); - if (MINIMUM in asn1.result) { - if (asn1.result.minimum.valueBlock.isHexOnly) - this.minimum = asn1.result.minimum; - else - this.minimum = asn1.result.minimum.valueBlock.valueDec; - } - if (MAXIMUM in asn1.result) { - if (asn1.result.maximum.valueBlock.isHexOnly) - this.maximum = asn1.result.maximum; - else - this.maximum = asn1.result.maximum.valueBlock.valueDec; - } - } - toSchema() { - const outputArray = []; - outputArray.push(this.base.toSchema()); - if (this.minimum !== 0) { - let valueMinimum = 0; - if (this.minimum instanceof Integer) { - valueMinimum = this.minimum; - } - else { - valueMinimum = new Integer({ value: this.minimum }); - } - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [valueMinimum] - })); - } - if (MAXIMUM in this) { - let valueMaximum = 0; - if (this.maximum instanceof Integer) { - valueMaximum = this.maximum; - } - else { - valueMaximum = new Integer({ value: this.maximum }); - } - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [valueMaximum] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - base: this.base.toJSON() - }; - if (this.minimum !== 0) { - if (typeof this.minimum === "number") { - res.minimum = this.minimum; - } - else { - res.minimum = this.minimum.toJSON(); - } - } - if (this.maximum !== undefined) { - if (typeof this.maximum === "number") { - res.maximum = this.maximum; - } - else { - res.maximum = this.maximum.toJSON(); - } - } - return res; - } -} -GeneralSubtree.CLASS_NAME = "GeneralSubtree"; - -const PERMITTED_SUBTREES = "permittedSubtrees"; -const EXCLUDED_SUBTREES = "excludedSubtrees"; -const CLEAR_PROPS$1g = [ - PERMITTED_SUBTREES, - EXCLUDED_SUBTREES -]; -class NameConstraints extends PkiObject { - constructor(parameters = {}) { - super(); - if (PERMITTED_SUBTREES in parameters) { - this.permittedSubtrees = getParametersValue(parameters, PERMITTED_SUBTREES, NameConstraints.defaultValues(PERMITTED_SUBTREES)); - } - if (EXCLUDED_SUBTREES in parameters) { - this.excludedSubtrees = getParametersValue(parameters, EXCLUDED_SUBTREES, NameConstraints.defaultValues(EXCLUDED_SUBTREES)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case PERMITTED_SUBTREES: - case EXCLUDED_SUBTREES: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Repeated({ - name: (names.permittedSubtrees || EMPTY_STRING), - value: GeneralSubtree.schema() - }) - ] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new Repeated({ - name: (names.excludedSubtrees || EMPTY_STRING), - value: GeneralSubtree.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1g); - const asn1 = compareSchema(schema, schema, NameConstraints.schema({ - names: { - permittedSubtrees: PERMITTED_SUBTREES, - excludedSubtrees: EXCLUDED_SUBTREES - } - })); - AsnError.assertSchema(asn1, this.className); - if (PERMITTED_SUBTREES in asn1.result) - this.permittedSubtrees = Array.from(asn1.result.permittedSubtrees, element => new GeneralSubtree({ schema: element })); - if (EXCLUDED_SUBTREES in asn1.result) - this.excludedSubtrees = Array.from(asn1.result.excludedSubtrees, element => new GeneralSubtree({ schema: element })); - } - toSchema() { - const outputArray = []; - if (this.permittedSubtrees) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: Array.from(this.permittedSubtrees, o => o.toSchema()) - })); - } - if (this.excludedSubtrees) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: Array.from(this.excludedSubtrees, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const object = {}; - if (this.permittedSubtrees) { - object.permittedSubtrees = Array.from(this.permittedSubtrees, o => o.toJSON()); - } - if (this.excludedSubtrees) { - object.excludedSubtrees = Array.from(this.excludedSubtrees, o => o.toJSON()); - } - return object; - } -} -NameConstraints.CLASS_NAME = "NameConstraints"; - -const REQUIRE_EXPLICIT_POLICY = "requireExplicitPolicy"; -const INHIBIT_POLICY_MAPPING = "inhibitPolicyMapping"; -const CLEAR_PROPS$1f = [ - REQUIRE_EXPLICIT_POLICY, - INHIBIT_POLICY_MAPPING, -]; -class PolicyConstraints extends PkiObject { - constructor(parameters = {}) { - super(); - if (REQUIRE_EXPLICIT_POLICY in parameters) { - this.requireExplicitPolicy = getParametersValue(parameters, REQUIRE_EXPLICIT_POLICY, PolicyConstraints.defaultValues(REQUIRE_EXPLICIT_POLICY)); - } - if (INHIBIT_POLICY_MAPPING in parameters) { - this.inhibitPolicyMapping = getParametersValue(parameters, INHIBIT_POLICY_MAPPING, PolicyConstraints.defaultValues(INHIBIT_POLICY_MAPPING)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case REQUIRE_EXPLICIT_POLICY: - return 0; - case INHIBIT_POLICY_MAPPING: - return 0; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Primitive({ - name: (names.requireExplicitPolicy || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - } - }), - new Primitive({ - name: (names.inhibitPolicyMapping || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1f); - const asn1 = compareSchema(schema, schema, PolicyConstraints.schema({ - names: { - requireExplicitPolicy: REQUIRE_EXPLICIT_POLICY, - inhibitPolicyMapping: INHIBIT_POLICY_MAPPING - } - })); - AsnError.assertSchema(asn1, this.className); - if (REQUIRE_EXPLICIT_POLICY in asn1.result) { - const field1 = asn1.result.requireExplicitPolicy; - field1.idBlock.tagClass = 1; - field1.idBlock.tagNumber = 2; - const ber1 = field1.toBER(false); - const int1 = fromBER(ber1); - AsnError.assert(int1, "Integer"); - this.requireExplicitPolicy = int1.result.valueBlock.valueDec; - } - if (INHIBIT_POLICY_MAPPING in asn1.result) { - const field2 = asn1.result.inhibitPolicyMapping; - field2.idBlock.tagClass = 1; - field2.idBlock.tagNumber = 2; - const ber2 = field2.toBER(false); - const int2 = fromBER(ber2); - AsnError.assert(int2, "Integer"); - this.inhibitPolicyMapping = int2.result.valueBlock.valueDec; - } - } - toSchema() { - const outputArray = []; - if (REQUIRE_EXPLICIT_POLICY in this) { - const int1 = new Integer({ value: this.requireExplicitPolicy }); - int1.idBlock.tagClass = 3; - int1.idBlock.tagNumber = 0; - outputArray.push(int1); - } - if (INHIBIT_POLICY_MAPPING in this) { - const int2 = new Integer({ value: this.inhibitPolicyMapping }); - int2.idBlock.tagClass = 3; - int2.idBlock.tagNumber = 1; - outputArray.push(int2); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = {}; - if (REQUIRE_EXPLICIT_POLICY in this) { - res.requireExplicitPolicy = this.requireExplicitPolicy; - } - if (INHIBIT_POLICY_MAPPING in this) { - res.inhibitPolicyMapping = this.inhibitPolicyMapping; - } - return res; - } -} -PolicyConstraints.CLASS_NAME = "PolicyConstraints"; - -const ISSUER_DOMAIN_POLICY = "issuerDomainPolicy"; -const SUBJECT_DOMAIN_POLICY = "subjectDomainPolicy"; -const CLEAR_PROPS$1e = [ - ISSUER_DOMAIN_POLICY, - SUBJECT_DOMAIN_POLICY -]; -class PolicyMapping extends PkiObject { - constructor(parameters = {}) { - super(); - this.issuerDomainPolicy = getParametersValue(parameters, ISSUER_DOMAIN_POLICY, PolicyMapping.defaultValues(ISSUER_DOMAIN_POLICY)); - this.subjectDomainPolicy = getParametersValue(parameters, SUBJECT_DOMAIN_POLICY, PolicyMapping.defaultValues(SUBJECT_DOMAIN_POLICY)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ISSUER_DOMAIN_POLICY: - return EMPTY_STRING; - case SUBJECT_DOMAIN_POLICY: - return EMPTY_STRING; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.issuerDomainPolicy || EMPTY_STRING) }), - new ObjectIdentifier({ name: (names.subjectDomainPolicy || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1e); - const asn1 = compareSchema(schema, schema, PolicyMapping.schema({ - names: { - issuerDomainPolicy: ISSUER_DOMAIN_POLICY, - subjectDomainPolicy: SUBJECT_DOMAIN_POLICY - } - })); - AsnError.assertSchema(asn1, this.className); - this.issuerDomainPolicy = asn1.result.issuerDomainPolicy.valueBlock.toString(); - this.subjectDomainPolicy = asn1.result.subjectDomainPolicy.valueBlock.toString(); - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.issuerDomainPolicy }), - new ObjectIdentifier({ value: this.subjectDomainPolicy }) - ] - })); - } - toJSON() { - return { - issuerDomainPolicy: this.issuerDomainPolicy, - subjectDomainPolicy: this.subjectDomainPolicy - }; - } -} -PolicyMapping.CLASS_NAME = "PolicyMapping"; - -const MAPPINGS = "mappings"; -const CLEAR_PROPS$1d = [ - MAPPINGS, -]; -class PolicyMappings extends PkiObject { - constructor(parameters = {}) { - super(); - this.mappings = getParametersValue(parameters, MAPPINGS, PolicyMappings.defaultValues(MAPPINGS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case MAPPINGS: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.mappings || EMPTY_STRING), - value: PolicyMapping.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1d); - const asn1 = compareSchema(schema, schema, PolicyMappings.schema({ - names: { - mappings: MAPPINGS - } - })); - AsnError.assertSchema(asn1, this.className); - this.mappings = Array.from(asn1.result.mappings, element => new PolicyMapping({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.mappings, o => o.toSchema()) - })); - } - toJSON() { - return { - mappings: Array.from(this.mappings, o => o.toJSON()) - }; - } -} -PolicyMappings.CLASS_NAME = "PolicyMappings"; - -const NOT_BEFORE$1 = "notBefore"; -const NOT_AFTER$1 = "notAfter"; -const CLEAR_PROPS$1c = [ - NOT_BEFORE$1, - NOT_AFTER$1 -]; -class PrivateKeyUsagePeriod extends PkiObject { - constructor(parameters = {}) { - super(); - if (NOT_BEFORE$1 in parameters) { - this.notBefore = getParametersValue(parameters, NOT_BEFORE$1, PrivateKeyUsagePeriod.defaultValues(NOT_BEFORE$1)); - } - if (NOT_AFTER$1 in parameters) { - this.notAfter = getParametersValue(parameters, NOT_AFTER$1, PrivateKeyUsagePeriod.defaultValues(NOT_AFTER$1)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case NOT_BEFORE$1: - return new Date(); - case NOT_AFTER$1: - return new Date(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Primitive({ - name: (names.notBefore || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - } - }), - new Primitive({ - name: (names.notAfter || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1c); - const asn1 = compareSchema(schema, schema, PrivateKeyUsagePeriod.schema({ - names: { - notBefore: NOT_BEFORE$1, - notAfter: NOT_AFTER$1 - } - })); - AsnError.assertSchema(asn1, this.className); - if (NOT_BEFORE$1 in asn1.result) { - const localNotBefore = new GeneralizedTime(); - localNotBefore.fromBuffer(asn1.result.notBefore.valueBlock.valueHex); - this.notBefore = localNotBefore.toDate(); - } - if (NOT_AFTER$1 in asn1.result) { - const localNotAfter = new GeneralizedTime({ valueHex: asn1.result.notAfter.valueBlock.valueHex }); - localNotAfter.fromBuffer(asn1.result.notAfter.valueBlock.valueHex); - this.notAfter = localNotAfter.toDate(); - } - } - toSchema() { - const outputArray = []; - if (NOT_BEFORE$1 in this) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - valueHex: (new GeneralizedTime({ valueDate: this.notBefore })).valueBlock.valueHexView - })); - } - if (NOT_AFTER$1 in this) { - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - valueHex: (new GeneralizedTime({ valueDate: this.notAfter })).valueBlock.valueHexView - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = {}; - if (this.notBefore) { - res.notBefore = this.notBefore; - } - if (this.notAfter) { - res.notAfter = this.notAfter; - } - return res; - } -} -PrivateKeyUsagePeriod.CLASS_NAME = "PrivateKeyUsagePeriod"; - -const ID = "id"; -const TYPE$2 = "type"; -const VALUES = "values"; -const QC_STATEMENT_CLEAR_PROPS = [ - ID, - TYPE$2 -]; -const QC_STATEMENTS_CLEAR_PROPS = [ - VALUES -]; -class QCStatement extends PkiObject { - constructor(parameters = {}) { - super(); - this.id = getParametersValue(parameters, ID, QCStatement.defaultValues(ID)); - if (TYPE$2 in parameters) { - this.type = getParametersValue(parameters, TYPE$2, QCStatement.defaultValues(TYPE$2)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ID: - return EMPTY_STRING; - case TYPE$2: - return new Null(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case ID: - return (memberValue === EMPTY_STRING); - case TYPE$2: - return (memberValue instanceof Null); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.id || EMPTY_STRING) }), - new Any({ - name: (names.type || EMPTY_STRING), - optional: true - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, QC_STATEMENT_CLEAR_PROPS); - const asn1 = compareSchema(schema, schema, QCStatement.schema({ - names: { - id: ID, - type: TYPE$2 - } - })); - AsnError.assertSchema(asn1, this.className); - this.id = asn1.result.id.valueBlock.toString(); - if (TYPE$2 in asn1.result) - this.type = asn1.result.type; - } - toSchema() { - const value = [ - new ObjectIdentifier({ value: this.id }) - ]; - if (TYPE$2 in this) - value.push(this.type); - return (new Sequence({ - value, - })); - } - toJSON() { - const object = { - id: this.id - }; - if (this.type) { - object.type = this.type.toJSON(); - } - return object; - } -} -QCStatement.CLASS_NAME = "QCStatement"; -class QCStatements extends PkiObject { - constructor(parameters = {}) { - super(); - this.values = getParametersValue(parameters, VALUES, QCStatements.defaultValues(VALUES)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VALUES: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VALUES: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.values || EMPTY_STRING), - value: QCStatement.schema(names.value || {}) - }), - ] - })); - } - fromSchema(schema) { - clearProps(schema, QC_STATEMENTS_CLEAR_PROPS); - const asn1 = compareSchema(schema, schema, QCStatements.schema({ - names: { - values: VALUES - } - })); - AsnError.assertSchema(asn1, this.className); - this.values = Array.from(asn1.result.values, element => new QCStatement({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.values, o => o.toSchema()) - })); - } - toJSON() { - return { - values: Array.from(this.values, o => o.toJSON()) - }; - } -} -QCStatements.CLASS_NAME = "QCStatements"; - -class ByteStream { +const PATH_LENGTH_CONSTRAINT = "pathLenConstraint"; +const CA = "cA"; +class BasicConstraints extends PkiObject { constructor(parameters = {}) { - if ("view" in parameters) { - this.fromUint8Array(parameters.view); + super(); + this.cA = getParametersValue(parameters, CA, false); + if (PATH_LENGTH_CONSTRAINT in parameters) { + this.pathLenConstraint = getParametersValue(parameters, PATH_LENGTH_CONSTRAINT, 0); } - else if ("buffer" in parameters) { - this.fromArrayBuffer(parameters.buffer); + if (parameters.schema) { + this.fromSchema(parameters.schema); } - else if ("string" in parameters) { - this.fromString(parameters.string); + } + static defaultValues(memberName) { + switch (memberName) { + case CA: + return false; + default: + return super.defaultValues(memberName); } - else if ("hexstring" in parameters) { - this.fromHexString(parameters.hexstring); + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Boolean({ + optional: true, + name: (names.cA || EMPTY_STRING) + }), + new Integer({ + optional: true, + name: (names.pathLenConstraint || EMPTY_STRING) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + CA, + PATH_LENGTH_CONSTRAINT + ]); + const asn1 = compareSchema(schema, schema, BasicConstraints.schema({ + names: { + cA: CA, + pathLenConstraint: PATH_LENGTH_CONSTRAINT + } + })); + AsnError.assertSchema(asn1, this.className); + if (CA in asn1.result) { + this.cA = asn1.result.cA.valueBlock.value; } - else { - if ("length" in parameters && parameters.length > 0) { - this.length = parameters.length; - if (parameters.stub) { - for (let i = 0; i < this._view.length; i++) { - this._view[i] = parameters.stub; - } - } + if (PATH_LENGTH_CONSTRAINT in asn1.result) { + if (asn1.result.pathLenConstraint.valueBlock.isHexOnly) { + this.pathLenConstraint = asn1.result.pathLenConstraint; } else { - this.length = 0; + this.pathLenConstraint = asn1.result.pathLenConstraint.valueBlock.valueDec; } } } - set buffer(value) { - this._buffer = value; - this._view = new Uint8Array(this._buffer); + toSchema() { + const outputArray = []; + if (this.cA !== BasicConstraints.defaultValues(CA)) + outputArray.push(new Boolean({ value: this.cA })); + if (PATH_LENGTH_CONSTRAINT in this) { + if (this.pathLenConstraint instanceof Integer) { + outputArray.push(this.pathLenConstraint); + } + else { + outputArray.push(new Integer({ value: this.pathLenConstraint })); + } + } + return (new Sequence({ + value: outputArray + })); } - get buffer() { - return this._buffer; + toJSON() { + const object = {}; + if (this.cA !== BasicConstraints.defaultValues(CA)) { + object.cA = this.cA; + } + if (PATH_LENGTH_CONSTRAINT in this) { + if (this.pathLenConstraint instanceof Integer) { + object.pathLenConstraint = this.pathLenConstraint.toJSON(); + } + else { + object.pathLenConstraint = this.pathLenConstraint; + } + } + return object; } - set view(value) { - this._buffer = new ArrayBuffer(value.length); - this._view = new Uint8Array(this._buffer); - this._view.set(value); +} +BasicConstraints.CLASS_NAME = "BasicConstraints"; + +const CERTIFICATE_INDEX = "certificateIndex"; +const KEY_INDEX = "keyIndex"; +class CAVersion extends PkiObject { + constructor(parameters = {}) { + super(); + this.certificateIndex = getParametersValue(parameters, CERTIFICATE_INDEX, CAVersion.defaultValues(CERTIFICATE_INDEX)); + this.keyIndex = getParametersValue(parameters, KEY_INDEX, CAVersion.defaultValues(KEY_INDEX)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } } - get view() { - return this._view; + static defaultValues(memberName) { + switch (memberName) { + case CERTIFICATE_INDEX: + case KEY_INDEX: + return 0; + default: + return super.defaultValues(memberName); + } } - get length() { - return this.view.byteLength; + static schema() { + return (new Integer()); } - set length(value) { - this._buffer = new ArrayBuffer(value); - this._view = new Uint8Array(this._buffer); + fromSchema(schema) { + if (schema.constructor.blockName() !== Integer.blockName()) { + throw new Error("Object's schema was not verified against input data for CAVersion"); + } + let value = schema.valueBlock.valueHex.slice(0); + const valueView = new Uint8Array(value); + switch (true) { + case (value.byteLength < 4): + { + const tempValue = new ArrayBuffer(4); + const tempValueView = new Uint8Array(tempValue); + tempValueView.set(valueView, 4 - value.byteLength); + value = tempValue.slice(0); + } + break; + case (value.byteLength > 4): + { + const tempValue = new ArrayBuffer(4); + const tempValueView = new Uint8Array(tempValue); + tempValueView.set(valueView.slice(0, 4)); + value = tempValue.slice(0); + } + break; + } + const keyIndexBuffer = value.slice(0, 2); + const keyIndexView8 = new Uint8Array(keyIndexBuffer); + let temp = keyIndexView8[0]; + keyIndexView8[0] = keyIndexView8[1]; + keyIndexView8[1] = temp; + const keyIndexView16 = new Uint16Array(keyIndexBuffer); + this.keyIndex = keyIndexView16[0]; + const certificateIndexBuffer = value.slice(2); + const certificateIndexView8 = new Uint8Array(certificateIndexBuffer); + temp = certificateIndexView8[0]; + certificateIndexView8[0] = certificateIndexView8[1]; + certificateIndexView8[1] = temp; + const certificateIndexView16 = new Uint16Array(certificateIndexBuffer); + this.certificateIndex = certificateIndexView16[0]; } - clear() { - this._buffer = new ArrayBuffer(0); - this._view = new Uint8Array(this._buffer); + toSchema() { + const certificateIndexBuffer = new ArrayBuffer(2); + const certificateIndexView = new Uint16Array(certificateIndexBuffer); + certificateIndexView[0] = this.certificateIndex; + const certificateIndexView8 = new Uint8Array(certificateIndexBuffer); + let temp = certificateIndexView8[0]; + certificateIndexView8[0] = certificateIndexView8[1]; + certificateIndexView8[1] = temp; + const keyIndexBuffer = new ArrayBuffer(2); + const keyIndexView = new Uint16Array(keyIndexBuffer); + keyIndexView[0] = this.keyIndex; + const keyIndexView8 = new Uint8Array(keyIndexBuffer); + temp = keyIndexView8[0]; + keyIndexView8[0] = keyIndexView8[1]; + keyIndexView8[1] = temp; + return (new Integer({ + valueHex: utilConcatBuf(keyIndexBuffer, certificateIndexBuffer) + })); } - fromArrayBuffer(array) { - this._buffer = array; - this._view = new Uint8Array(this._buffer); + toJSON() { + return { + certificateIndex: this.certificateIndex, + keyIndex: this.keyIndex + }; } - fromUint8Array(array) { - this.fromArrayBuffer(new Uint8Array(array).buffer); +} +CAVersion.CLASS_NAME = "CAVersion"; + +const POLICY_QUALIFIER_ID = "policyQualifierId"; +const QUALIFIER = "qualifier"; +const CLEAR_PROPS$1p = [ + POLICY_QUALIFIER_ID, + QUALIFIER +]; +class PolicyQualifierInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.policyQualifierId = getParametersValue(parameters, POLICY_QUALIFIER_ID, PolicyQualifierInfo.defaultValues(POLICY_QUALIFIER_ID)); + this.qualifier = getParametersValue(parameters, QUALIFIER, PolicyQualifierInfo.defaultValues(QUALIFIER)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } } - fromString(string) { - const stringLength = string.length; - this.length = stringLength; - for (let i = 0; i < stringLength; i++) - this.view[i] = string.charCodeAt(i); + static defaultValues(memberName) { + switch (memberName) { + case POLICY_QUALIFIER_ID: + return EMPTY_STRING; + case QUALIFIER: + return new Any(); + default: + return super.defaultValues(memberName); + } } - toString(start = 0, length = (this.view.length - start)) { - let result = ""; - if ((start >= this.view.length) || (start < 0)) { - start = 0; + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.policyQualifierId || EMPTY_STRING) }), + new Any({ name: (names.qualifier || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1p); + const asn1 = compareSchema(schema, schema, PolicyQualifierInfo.schema({ + names: { + policyQualifierId: POLICY_QUALIFIER_ID, + qualifier: QUALIFIER + } + })); + AsnError.assertSchema(asn1, this.className); + this.policyQualifierId = asn1.result.policyQualifierId.valueBlock.toString(); + this.qualifier = asn1.result.qualifier; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.policyQualifierId }), + this.qualifier + ] + })); + } + toJSON() { + return { + policyQualifierId: this.policyQualifierId, + qualifier: this.qualifier.toJSON() + }; + } +} +PolicyQualifierInfo.CLASS_NAME = "PolicyQualifierInfo"; + +const POLICY_IDENTIFIER = "policyIdentifier"; +const POLICY_QUALIFIERS = "policyQualifiers"; +const CLEAR_PROPS$1o = [ + POLICY_IDENTIFIER, + POLICY_QUALIFIERS +]; +class PolicyInformation extends PkiObject { + constructor(parameters = {}) { + super(); + this.policyIdentifier = getParametersValue(parameters, POLICY_IDENTIFIER, PolicyInformation.defaultValues(POLICY_IDENTIFIER)); + if (POLICY_QUALIFIERS in parameters) { + this.policyQualifiers = getParametersValue(parameters, POLICY_QUALIFIERS, PolicyInformation.defaultValues(POLICY_QUALIFIERS)); } - if ((length >= this.view.length) || (length < 0)) { - length = this.view.length - start; + if (parameters.schema) { + this.fromSchema(parameters.schema); } - for (let i = start; i < (start + length); i++) - result += String.fromCharCode(this.view[i]); - return result; } - fromHexString(hexString) { - const stringLength = hexString.length; - this.buffer = new ArrayBuffer(stringLength >> 1); - this.view = new Uint8Array(this.buffer); - const hexMap = new Map(); - hexMap.set("0", 0x00); - hexMap.set("1", 0x01); - hexMap.set("2", 0x02); - hexMap.set("3", 0x03); - hexMap.set("4", 0x04); - hexMap.set("5", 0x05); - hexMap.set("6", 0x06); - hexMap.set("7", 0x07); - hexMap.set("8", 0x08); - hexMap.set("9", 0x09); - hexMap.set("A", 0x0A); - hexMap.set("a", 0x0A); - hexMap.set("B", 0x0B); - hexMap.set("b", 0x0B); - hexMap.set("C", 0x0C); - hexMap.set("c", 0x0C); - hexMap.set("D", 0x0D); - hexMap.set("d", 0x0D); - hexMap.set("E", 0x0E); - hexMap.set("e", 0x0E); - hexMap.set("F", 0x0F); - hexMap.set("f", 0x0F); - let j = 0; - let temp = 0x00; - for (let i = 0; i < stringLength; i++) { - if (!(i % 2)) { - temp = hexMap.get(hexString.charAt(i)) << 4; - } - else { - temp |= hexMap.get(hexString.charAt(i)); - this.view[j] = temp; - j++; + static defaultValues(memberName) { + switch (memberName) { + case POLICY_IDENTIFIER: + return EMPTY_STRING; + case POLICY_QUALIFIERS: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.policyIdentifier || EMPTY_STRING) }), + new Sequence({ + optional: true, + value: [ + new Repeated({ + name: (names.policyQualifiers || EMPTY_STRING), + value: PolicyQualifierInfo.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1o); + const asn1 = compareSchema(schema, schema, PolicyInformation.schema({ + names: { + policyIdentifier: POLICY_IDENTIFIER, + policyQualifiers: POLICY_QUALIFIERS } + })); + AsnError.assertSchema(asn1, this.className); + this.policyIdentifier = asn1.result.policyIdentifier.valueBlock.toString(); + if (POLICY_QUALIFIERS in asn1.result) { + this.policyQualifiers = Array.from(asn1.result.policyQualifiers, element => new PolicyQualifierInfo({ schema: element })); } } - toHexString(start = 0, length = (this.view.length - start)) { - let result = ""; - if ((start >= this.view.length) || (start < 0)) { - start = 0; + toSchema() { + const outputArray = []; + outputArray.push(new ObjectIdentifier({ value: this.policyIdentifier })); + if (this.policyQualifiers) { + outputArray.push(new Sequence({ + value: Array.from(this.policyQualifiers, o => o.toSchema()) + })); } - if ((length >= this.view.length) || (length < 0)) { - length = this.view.length - start; + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + policyIdentifier: this.policyIdentifier + }; + if (this.policyQualifiers) + res.policyQualifiers = Array.from(this.policyQualifiers, o => o.toJSON()); + return res; + } +} +PolicyInformation.CLASS_NAME = "PolicyInformation"; + +const CERTIFICATE_POLICIES = "certificatePolicies"; +const CLEAR_PROPS$1n = [ + CERTIFICATE_POLICIES, +]; +class CertificatePolicies extends PkiObject { + constructor(parameters = {}) { + super(); + this.certificatePolicies = getParametersValue(parameters, CERTIFICATE_POLICIES, CertificatePolicies.defaultValues(CERTIFICATE_POLICIES)); + if (parameters.schema) { + this.fromSchema(parameters.schema); } - for (let i = start; i < (start + length); i++) { - const str = this.view[i].toString(16).toUpperCase(); - result = result + ((str.length == 1) ? "0" : "") + str; + } + static defaultValues(memberName) { + switch (memberName) { + case CERTIFICATE_POLICIES: + return []; + default: + return super.defaultValues(memberName); } - return result; } - copy(start = 0, length = (this.length - start)) { - if (!start && !this.length) { - return new ByteStream(); + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.certificatePolicies || EMPTY_STRING), + value: PolicyInformation.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1n); + const asn1 = compareSchema(schema, schema, CertificatePolicies.schema({ + names: { + certificatePolicies: CERTIFICATE_POLICIES + } + })); + AsnError.assertSchema(asn1, this.className); + this.certificatePolicies = Array.from(asn1.result.certificatePolicies, element => new PolicyInformation({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.certificatePolicies, o => o.toSchema()) + })); + } + toJSON() { + return { + certificatePolicies: Array.from(this.certificatePolicies, o => o.toJSON()) + }; + } +} +CertificatePolicies.CLASS_NAME = "CertificatePolicies"; + +const TEMPLATE_ID = "templateID"; +const TEMPLATE_MAJOR_VERSION = "templateMajorVersion"; +const TEMPLATE_MINOR_VERSION = "templateMinorVersion"; +const CLEAR_PROPS$1m = [ + TEMPLATE_ID, + TEMPLATE_MAJOR_VERSION, + TEMPLATE_MINOR_VERSION +]; +class CertificateTemplate extends PkiObject { + constructor(parameters = {}) { + super(); + this.templateID = getParametersValue(parameters, TEMPLATE_ID, CertificateTemplate.defaultValues(TEMPLATE_ID)); + if (TEMPLATE_MAJOR_VERSION in parameters) { + this.templateMajorVersion = getParametersValue(parameters, TEMPLATE_MAJOR_VERSION, CertificateTemplate.defaultValues(TEMPLATE_MAJOR_VERSION)); } - if ((start < 0) || (start > (this.length - 1))) { - throw new Error(`Wrong start position: ${start}`); + if (TEMPLATE_MINOR_VERSION in parameters) { + this.templateMinorVersion = getParametersValue(parameters, TEMPLATE_MINOR_VERSION, CertificateTemplate.defaultValues(TEMPLATE_MINOR_VERSION)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); } - const stream = new ByteStream({ - buffer: this._buffer.slice(start, start + length) - }); - return stream; } - slice(start = 0, end = this.length) { - if (!start && !this.length) { - return new ByteStream(); + static defaultValues(memberName) { + switch (memberName) { + case TEMPLATE_ID: + return EMPTY_STRING; + case TEMPLATE_MAJOR_VERSION: + case TEMPLATE_MINOR_VERSION: + return 0; + default: + return super.defaultValues(memberName); } - if ((start < 0) || (start > (this.length - 1))) { - throw new Error(`Wrong start position: ${start}`); + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.templateID || EMPTY_STRING) }), + new Integer({ + name: (names.templateMajorVersion || EMPTY_STRING), + optional: true + }), + new Integer({ + name: (names.templateMinorVersion || EMPTY_STRING), + optional: true + }), + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1m); + const asn1 = compareSchema(schema, schema, CertificateTemplate.schema({ + names: { + templateID: TEMPLATE_ID, + templateMajorVersion: TEMPLATE_MAJOR_VERSION, + templateMinorVersion: TEMPLATE_MINOR_VERSION + } + })); + AsnError.assertSchema(asn1, this.className); + this.templateID = asn1.result.templateID.valueBlock.toString(); + if (TEMPLATE_MAJOR_VERSION in asn1.result) { + this.templateMajorVersion = asn1.result.templateMajorVersion.valueBlock.valueDec; + } + if (TEMPLATE_MINOR_VERSION in asn1.result) { + this.templateMinorVersion = asn1.result.templateMinorVersion.valueBlock.valueDec; } - const stream = new ByteStream({ - buffer: this._buffer.slice(start, end), - }); - return stream; } - realloc(size) { - const buffer = new ArrayBuffer(size); - const view = new Uint8Array(buffer); - if (size > this._view.length) - view.set(this._view); - else { - view.set(new Uint8Array(this._buffer, 0, size)); + toSchema() { + const outputArray = []; + outputArray.push(new ObjectIdentifier({ value: this.templateID })); + if (TEMPLATE_MAJOR_VERSION in this) { + outputArray.push(new Integer({ value: this.templateMajorVersion })); } - this._buffer = buffer; - this._view = new Uint8Array(this._buffer); + if (TEMPLATE_MINOR_VERSION in this) { + outputArray.push(new Integer({ value: this.templateMinorVersion })); + } + return (new Sequence({ + value: outputArray + })); } - append(stream) { - const initialSize = this.length; - const streamViewLength = stream.length; - const subarrayView = stream._view.subarray(); - this.realloc(initialSize + streamViewLength); - this._view.set(subarrayView, initialSize); + toJSON() { + const res = { + templateID: this.templateID + }; + if (TEMPLATE_MAJOR_VERSION in this) + res.templateMajorVersion = this.templateMajorVersion; + if (TEMPLATE_MINOR_VERSION in this) + res.templateMinorVersion = this.templateMinorVersion; + return res; } - insert(stream, start = 0, length = (this.length - start)) { - if (start > (this.length - 1)) - return false; - if (length > (this.length - start)) { - length = this.length - start; +} + +const DISTRIBUTION_POINT$1 = "distributionPoint"; +const DISTRIBUTION_POINT_NAMES$1 = "distributionPointNames"; +const REASONS = "reasons"; +const CRL_ISSUER = "cRLIssuer"; +const CRL_ISSUER_NAMES = "cRLIssuerNames"; +const CLEAR_PROPS$1l = [ + DISTRIBUTION_POINT$1, + DISTRIBUTION_POINT_NAMES$1, + REASONS, + CRL_ISSUER, + CRL_ISSUER_NAMES, +]; +class DistributionPoint extends PkiObject { + constructor(parameters = {}) { + super(); + if (DISTRIBUTION_POINT$1 in parameters) { + this.distributionPoint = getParametersValue(parameters, DISTRIBUTION_POINT$1, DistributionPoint.defaultValues(DISTRIBUTION_POINT$1)); } - if (length > stream.length) { - length = stream.length; + if (REASONS in parameters) { + this.reasons = getParametersValue(parameters, REASONS, DistributionPoint.defaultValues(REASONS)); } - if (length == stream.length) - this._view.set(stream._view, start); - else { - this._view.set(stream._view.subarray(0, length), start); + if (CRL_ISSUER in parameters) { + this.cRLIssuer = getParametersValue(parameters, CRL_ISSUER, DistributionPoint.defaultValues(CRL_ISSUER)); } - return true; - } - isEqual(stream) { - if (this.length != stream.length) - return false; - for (let i = 0; i < stream.length; i++) { - if (this.view[i] != stream.view[i]) - return false; + if (parameters.schema) { + this.fromSchema(parameters.schema); } - return true; } - isEqualView(view) { - if (view.length != this.view.length) - return false; - for (let i = 0; i < view.length; i++) { - if (this.view[i] != view[i]) - return false; + static defaultValues(memberName) { + switch (memberName) { + case DISTRIBUTION_POINT$1: + return []; + case REASONS: + return new BitString(); + case CRL_ISSUER: + return []; + default: + return super.defaultValues(memberName); } - return true; } - findPattern(pattern, start_, length_, backward_) { - const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); - const patternLength = pattern.length; - if (patternLength > length) { - return (-1); - } - const patternArray = []; - for (let i = 0; i < patternLength; i++) - patternArray.push(pattern.view[i]); - for (let i = 0; i <= (length - patternLength); i++) { - let equal = true; - const equalStart = (backward) ? (start - patternLength - i) : (start + i); - for (let j = 0; j < patternLength; j++) { - if (this.view[j + equalStart] != patternArray[j]) { - equal = false; - break; - } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Choice({ + value: [ + new Constructed({ + name: (names.distributionPoint || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Repeated({ + name: (names.distributionPointNames || EMPTY_STRING), + value: GeneralName.schema() + }) + ] + }), + new Constructed({ + name: (names.distributionPoint || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: RelativeDistinguishedNames.schema().valueBlock.value + }) + ] + }) + ] + }), + new Primitive({ + name: (names.reasons || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + } + }), + new Constructed({ + name: (names.cRLIssuer || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [ + new Repeated({ + name: (names.cRLIssuerNames || EMPTY_STRING), + value: GeneralName.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1l); + const asn1 = compareSchema(schema, schema, DistributionPoint.schema({ + names: { + distributionPoint: DISTRIBUTION_POINT$1, + distributionPointNames: DISTRIBUTION_POINT_NAMES$1, + reasons: REASONS, + cRLIssuer: CRL_ISSUER, + cRLIssuerNames: CRL_ISSUER_NAMES } - if (equal) { - return (backward) ? (start - patternLength - i) : (start + patternLength + i); + })); + AsnError.assertSchema(asn1, this.className); + if (DISTRIBUTION_POINT$1 in asn1.result) { + if (asn1.result.distributionPoint.idBlock.tagNumber === 0) { + this.distributionPoint = Array.from(asn1.result.distributionPointNames, element => new GeneralName({ schema: element })); + } + if (asn1.result.distributionPoint.idBlock.tagNumber === 1) { + this.distributionPoint = new RelativeDistinguishedNames({ + schema: new Sequence({ + value: asn1.result.distributionPoint.valueBlock.value + }) + }); } } - return (-1); + if (REASONS in asn1.result) { + this.reasons = new BitString({ valueHex: asn1.result.reasons.valueBlock.valueHex }); + } + if (CRL_ISSUER in asn1.result) { + this.cRLIssuer = Array.from(asn1.result.cRLIssuerNames, element => new GeneralName({ schema: element })); + } } - findFirstIn(patterns, start_, length_, backward_) { - const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); - const result = { - id: (-1), - position: (backward) ? 0 : (start + length), - length: 0 - }; - for (let i = 0; i < patterns.length; i++) { - const position = this.findPattern(patterns[i], start, length, backward); - if (position != (-1)) { - let valid = false; - const patternLength = patterns[i].length; - if (backward) { - if ((position - patternLength) >= (result.position - result.length)) - valid = true; - } - else { - if ((position - patternLength) <= (result.position - result.length)) - valid = true; - } - if (valid) { - result.position = position; - result.id = i; - result.length = patternLength; - } + toSchema() { + const outputArray = []; + if (this.distributionPoint) { + let internalValue; + if (this.distributionPoint instanceof Array) { + internalValue = new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: Array.from(this.distributionPoint, o => o.toSchema()) + }); + } + else { + internalValue = new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [this.distributionPoint.toSchema()] + }); } + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [internalValue] + })); } - return result; + if (this.reasons) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + valueHex: this.reasons.valueBlock.valueHexView + })); + } + if (this.cRLIssuer) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: Array.from(this.cRLIssuer, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); } - findAllIn(patterns, start_, length_) { - let { start, length } = this.prepareFindParameters(start_, length_); - const result = []; - let patternFound = { - id: (-1), - position: start - }; - do { - const position = patternFound.position; - patternFound = this.findFirstIn(patterns, patternFound.position, length); - if (patternFound.id == (-1)) { - break; + toJSON() { + const object = {}; + if (this.distributionPoint) { + if (this.distributionPoint instanceof Array) { + object.distributionPoint = Array.from(this.distributionPoint, o => o.toJSON()); + } + else { + object.distributionPoint = this.distributionPoint.toJSON(); } - length -= (patternFound.position - position); - result.push({ - id: patternFound.id, - position: patternFound.position - }); - } while (true); - return result; - } - findAllPatternIn(pattern, start_, length_) { - const { start, length } = this.prepareFindParameters(start_, length_); - const result = []; - const patternLength = pattern.length; - if (patternLength > length) { - return (-1); } - const patternArray = Array.from(pattern.view); - for (let i = 0; i <= (length - patternLength); i++) { - let equal = true; - const equalStart = start + i; - for (let j = 0; j < patternLength; j++) { - if (this.view[j + equalStart] != patternArray[j]) { - equal = false; - break; - } - } - if (equal) { - result.push(start + patternLength + i); - i += (patternLength - 1); - } + if (this.reasons) { + object.reasons = this.reasons.toJSON(); } - return result; + if (this.cRLIssuer) { + object.cRLIssuer = Array.from(this.cRLIssuer, o => o.toJSON()); + } + return object; } - findFirstNotIn(patterns, start_, length_, backward_) { - let { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); - const result = { - left: { - id: (-1), - position: start - }, - right: { - id: (-1), - position: 0 - }, - value: new ByteStream() - }; - let currentLength = length; - while (currentLength > 0) { - result.right = this.findFirstIn(patterns, (backward) ? (start - length + currentLength) : (start + length - currentLength), currentLength, backward); - if (result.right.id == (-1)) { - length = currentLength; - if (backward) { - start -= length; - } - else { - start = result.left.position; - } - result.value = new ByteStream({ - buffer: this._buffer.slice(start, start + length), - }); - break; - } - if (result.right.position != ((backward) ? (result.left.position - patterns[result.right.id].length) : (result.left.position + patterns[result.right.id].length))) { - if (backward) { - start = result.right.position + patterns[result.right.id].length; - length = result.left.position - result.right.position - patterns[result.right.id].length; - } - else { - start = result.left.position; - length = result.right.position - result.left.position - patterns[result.right.id].length; - } - result.value = new ByteStream({ - buffer: this._buffer.slice(start, start + length), - }); - break; - } - result.left = result.right; - currentLength -= patterns[result.right.id].length; +} +DistributionPoint.CLASS_NAME = "DistributionPoint"; + +const DISTRIBUTION_POINTS = "distributionPoints"; +const CLEAR_PROPS$1k = [ + DISTRIBUTION_POINTS +]; +class CRLDistributionPoints extends PkiObject { + constructor(parameters = {}) { + super(); + this.distributionPoints = getParametersValue(parameters, DISTRIBUTION_POINTS, CRLDistributionPoints.defaultValues(DISTRIBUTION_POINTS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); } - if (backward) { - const temp = result.right; - result.right = result.left; - result.left = temp; + } + static defaultValues(memberName) { + switch (memberName) { + case DISTRIBUTION_POINTS: + return []; + default: + return super.defaultValues(memberName); } - return result; } - findAllNotIn(patterns, start_, length_) { - let { start, length } = this.prepareFindParameters(start_, length_); - const result = []; - let patternFound = { - left: { - id: (-1), - position: start - }, - right: { - id: (-1), - position: start - }, - value: new ByteStream() + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.distributionPoints || EMPTY_STRING), + value: DistributionPoint.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1k); + const asn1 = compareSchema(schema, schema, CRLDistributionPoints.schema({ + names: { + distributionPoints: DISTRIBUTION_POINTS + } + })); + AsnError.assertSchema(asn1, this.className); + this.distributionPoints = Array.from(asn1.result.distributionPoints, element => new DistributionPoint({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.distributionPoints, o => o.toSchema()) + })); + } + toJSON() { + return { + distributionPoints: Array.from(this.distributionPoints, o => o.toJSON()) }; - do { - const position = patternFound.right.position; - patternFound = this.findFirstNotIn(patterns, patternFound.right.position, length); - length -= (patternFound.right.position - position); - result.push({ - left: { - id: patternFound.left.id, - position: patternFound.left.position - }, - right: { - id: patternFound.right.id, - position: patternFound.right.position - }, - value: patternFound.value - }); - } while (patternFound.right.id != (-1)); - return result; } - findFirstSequence(patterns, start_, length_, backward_) { - let { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); - const firstIn = this.skipNotPatterns(patterns, start, length, backward); - if (firstIn == (-1)) { - return { - position: (-1), - value: new ByteStream() - }; - } - const firstNotIn = this.skipPatterns(patterns, firstIn, length - ((backward) ? (start - firstIn) : (firstIn - start)), backward); - if (backward) { - start = firstNotIn; - length = (firstIn - firstNotIn); +} +CRLDistributionPoints.CLASS_NAME = "CRLDistributionPoints"; + +const KEY_PURPOSES = "keyPurposes"; +const CLEAR_PROPS$1j = [ + KEY_PURPOSES, +]; +class ExtKeyUsage extends PkiObject { + constructor(parameters = {}) { + super(); + this.keyPurposes = getParametersValue(parameters, KEY_PURPOSES, ExtKeyUsage.defaultValues(KEY_PURPOSES)); + if (parameters.schema) { + this.fromSchema(parameters.schema); } - else { - start = firstIn; - length = (firstNotIn - firstIn); + } + static defaultValues(memberName) { + switch (memberName) { + case KEY_PURPOSES: + return []; + default: + return super.defaultValues(memberName); } - const value = new ByteStream({ - buffer: this._buffer.slice(start, start + length), - }); + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.keyPurposes || EMPTY_STRING), + value: new ObjectIdentifier() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1j); + const asn1 = compareSchema(schema, schema, ExtKeyUsage.schema({ + names: { + keyPurposes: KEY_PURPOSES + } + })); + AsnError.assertSchema(asn1, this.className); + this.keyPurposes = Array.from(asn1.result.keyPurposes, (element) => element.valueBlock.toString()); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.keyPurposes, element => new ObjectIdentifier({ value: element })) + })); + } + toJSON() { return { - position: firstNotIn, - value + keyPurposes: Array.from(this.keyPurposes) }; } - findAllSequences(patterns, start_, length_) { - let { start, length } = this.prepareFindParameters(start_, length_); - const result = []; - let patternFound = { - position: start, - value: new ByteStream() - }; - do { - const position = patternFound.position; - patternFound = this.findFirstSequence(patterns, patternFound.position, length); - if (patternFound.position != (-1)) { - length -= (patternFound.position - position); - result.push({ - position: patternFound.position, - value: patternFound.value, - }); +} +ExtKeyUsage.CLASS_NAME = "ExtKeyUsage"; + +const ACCESS_DESCRIPTIONS = "accessDescriptions"; +class InfoAccess extends PkiObject { + constructor(parameters = {}) { + super(); + this.accessDescriptions = getParametersValue(parameters, ACCESS_DESCRIPTIONS, InfoAccess.defaultValues(ACCESS_DESCRIPTIONS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ACCESS_DESCRIPTIONS: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.accessDescriptions || EMPTY_STRING), + value: AccessDescription.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + ACCESS_DESCRIPTIONS + ]); + const asn1 = compareSchema(schema, schema, InfoAccess.schema({ + names: { + accessDescriptions: ACCESS_DESCRIPTIONS } - } while (patternFound.position != (-1)); - return result; + })); + AsnError.assertSchema(asn1, this.className); + this.accessDescriptions = Array.from(asn1.result.accessDescriptions, element => new AccessDescription({ schema: element })); } - findPairedPatterns(leftPattern, rightPattern, start_, length_) { - const result = []; - if (leftPattern.isEqual(rightPattern)) - return result; - const { start, length } = this.prepareFindParameters(start_, length_); - let currentPositionLeft = 0; - const leftPatterns = this.findAllPatternIn(leftPattern, start, length); - if (!Array.isArray(leftPatterns) || leftPatterns.length == 0) { - return result; + toSchema() { + return (new Sequence({ + value: Array.from(this.accessDescriptions, o => o.toSchema()) + })); + } + toJSON() { + return { + accessDescriptions: Array.from(this.accessDescriptions, o => o.toJSON()) + }; + } +} +InfoAccess.CLASS_NAME = "InfoAccess"; + +const DISTRIBUTION_POINT = "distributionPoint"; +const DISTRIBUTION_POINT_NAMES = "distributionPointNames"; +const ONLY_CONTAINS_USER_CERTS = "onlyContainsUserCerts"; +const ONLY_CONTAINS_CA_CERTS = "onlyContainsCACerts"; +const ONLY_SOME_REASON = "onlySomeReasons"; +const INDIRECT_CRL = "indirectCRL"; +const ONLY_CONTAINS_ATTRIBUTE_CERTS = "onlyContainsAttributeCerts"; +const CLEAR_PROPS$1i = [ + DISTRIBUTION_POINT, + DISTRIBUTION_POINT_NAMES, + ONLY_CONTAINS_USER_CERTS, + ONLY_CONTAINS_CA_CERTS, + ONLY_SOME_REASON, + INDIRECT_CRL, + ONLY_CONTAINS_ATTRIBUTE_CERTS, +]; +class IssuingDistributionPoint extends PkiObject { + constructor(parameters = {}) { + super(); + if (DISTRIBUTION_POINT in parameters) { + this.distributionPoint = getParametersValue(parameters, DISTRIBUTION_POINT, IssuingDistributionPoint.defaultValues(DISTRIBUTION_POINT)); } - const rightPatterns = this.findAllPatternIn(rightPattern, start, length); - if (!Array.isArray(rightPatterns) || rightPatterns.length == 0) { - return result; + this.onlyContainsUserCerts = getParametersValue(parameters, ONLY_CONTAINS_USER_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS)); + this.onlyContainsCACerts = getParametersValue(parameters, ONLY_CONTAINS_CA_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS)); + if (ONLY_SOME_REASON in parameters) { + this.onlySomeReasons = getParametersValue(parameters, ONLY_SOME_REASON, IssuingDistributionPoint.defaultValues(ONLY_SOME_REASON)); } - while (currentPositionLeft < leftPatterns.length) { - if (rightPatterns.length == 0) { - break; - } - if (leftPatterns[0] == rightPatterns[0]) { - result.push({ - left: leftPatterns[0], - right: rightPatterns[0] - }); - leftPatterns.splice(0, 1); - rightPatterns.splice(0, 1); - continue; - } - if (leftPatterns[currentPositionLeft] > rightPatterns[0]) { - break; + this.indirectCRL = getParametersValue(parameters, INDIRECT_CRL, IssuingDistributionPoint.defaultValues(INDIRECT_CRL)); + this.onlyContainsAttributeCerts = getParametersValue(parameters, ONLY_CONTAINS_ATTRIBUTE_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case DISTRIBUTION_POINT: + return []; + case ONLY_CONTAINS_USER_CERTS: + return false; + case ONLY_CONTAINS_CA_CERTS: + return false; + case ONLY_SOME_REASON: + return 0; + case INDIRECT_CRL: + return false; + case ONLY_CONTAINS_ATTRIBUTE_CERTS: + return false; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Choice({ + value: [ + new Constructed({ + name: (names.distributionPoint || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Repeated({ + name: (names.distributionPointNames || EMPTY_STRING), + value: GeneralName.schema() + }) + ] + }), + new Constructed({ + name: (names.distributionPoint || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: RelativeDistinguishedNames.schema().valueBlock.value + }) + ] + }) + ] + }), + new Primitive({ + name: (names.onlyContainsUserCerts || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + } + }), + new Primitive({ + name: (names.onlyContainsCACerts || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + } + }), + new Primitive({ + name: (names.onlySomeReasons || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 3 + } + }), + new Primitive({ + name: (names.indirectCRL || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 4 + } + }), + new Primitive({ + name: (names.onlyContainsAttributeCerts || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 5 + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1i); + const asn1 = compareSchema(schema, schema, IssuingDistributionPoint.schema({ + names: { + distributionPoint: DISTRIBUTION_POINT, + distributionPointNames: DISTRIBUTION_POINT_NAMES, + onlyContainsUserCerts: ONLY_CONTAINS_USER_CERTS, + onlyContainsCACerts: ONLY_CONTAINS_CA_CERTS, + onlySomeReasons: ONLY_SOME_REASON, + indirectCRL: INDIRECT_CRL, + onlyContainsAttributeCerts: ONLY_CONTAINS_ATTRIBUTE_CERTS } - while (leftPatterns[currentPositionLeft] < rightPatterns[0]) { - currentPositionLeft++; - if (currentPositionLeft >= leftPatterns.length) { + })); + AsnError.assertSchema(asn1, this.className); + if (DISTRIBUTION_POINT in asn1.result) { + switch (true) { + case (asn1.result.distributionPoint.idBlock.tagNumber === 0): + this.distributionPoint = Array.from(asn1.result.distributionPointNames, element => new GeneralName({ schema: element })); break; - } + case (asn1.result.distributionPoint.idBlock.tagNumber === 1): + { + this.distributionPoint = new RelativeDistinguishedNames({ + schema: new Sequence({ + value: asn1.result.distributionPoint.valueBlock.value + }) + }); + } + break; + default: + throw new Error("Unknown tagNumber for distributionPoint: {$asn1.result.distributionPoint.idBlock.tagNumber}"); } - result.push({ - left: leftPatterns[currentPositionLeft - 1], - right: rightPatterns[0] - }); - leftPatterns.splice(currentPositionLeft - 1, 1); - rightPatterns.splice(0, 1); - currentPositionLeft = 0; } - result.sort((a, b) => (a.left - b.left)); - return result; + if (ONLY_CONTAINS_USER_CERTS in asn1.result) { + const view = new Uint8Array(asn1.result.onlyContainsUserCerts.valueBlock.valueHex); + this.onlyContainsUserCerts = (view[0] !== 0x00); + } + if (ONLY_CONTAINS_CA_CERTS in asn1.result) { + const view = new Uint8Array(asn1.result.onlyContainsCACerts.valueBlock.valueHex); + this.onlyContainsCACerts = (view[0] !== 0x00); + } + if (ONLY_SOME_REASON in asn1.result) { + const view = new Uint8Array(asn1.result.onlySomeReasons.valueBlock.valueHex); + this.onlySomeReasons = view[0]; + } + if (INDIRECT_CRL in asn1.result) { + const view = new Uint8Array(asn1.result.indirectCRL.valueBlock.valueHex); + this.indirectCRL = (view[0] !== 0x00); + } + if (ONLY_CONTAINS_ATTRIBUTE_CERTS in asn1.result) { + const view = new Uint8Array(asn1.result.onlyContainsAttributeCerts.valueBlock.valueHex); + this.onlyContainsAttributeCerts = (view[0] !== 0x00); + } } - findPairedArrays(inputLeftPatterns, inputRightPatterns, start_, length_) { - const { start, length } = this.prepareFindParameters(start_, length_); - const result = []; - let currentPositionLeft = 0; - const leftPatterns = this.findAllIn(inputLeftPatterns, start, length); - if (leftPatterns.length == 0) - return result; - const rightPatterns = this.findAllIn(inputRightPatterns, start, length); - if (rightPatterns.length == 0) - return result; - while (currentPositionLeft < leftPatterns.length) { - if (rightPatterns.length == 0) { - break; - } - if (leftPatterns[0].position == rightPatterns[0].position) { - result.push({ - left: leftPatterns[0], - right: rightPatterns[0] + toSchema() { + const outputArray = []; + if (this.distributionPoint) { + let value; + if (this.distributionPoint instanceof Array) { + value = new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: Array.from(this.distributionPoint, o => o.toSchema()) }); - leftPatterns.splice(0, 1); - rightPatterns.splice(0, 1); - continue; } - if (leftPatterns[currentPositionLeft].position > rightPatterns[0].position) { - break; + else { + value = this.distributionPoint.toSchema(); + value.idBlock.tagClass = 3; + value.idBlock.tagNumber = 1; } - while (leftPatterns[currentPositionLeft].position < rightPatterns[0].position) { - currentPositionLeft++; - if (currentPositionLeft >= leftPatterns.length) { - break; - } - } - result.push({ - left: leftPatterns[currentPositionLeft - 1], - right: rightPatterns[0] - }); - leftPatterns.splice(currentPositionLeft - 1, 1); - rightPatterns.splice(0, 1); - currentPositionLeft = 0; + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [value] + })); } - result.sort((a, b) => (a.left.position - b.left.position)); - return result; - } - replacePattern(searchPattern, replacePattern, start_, length_, findAllResult = null) { - let result = []; - let i; - const output = { - status: (-1), - searchPatternPositions: [], - replacePatternPositions: [] - }; - const { start, length } = this.prepareFindParameters(start_, length_); - if (findAllResult == null) { - result = this.findAllIn([searchPattern], start, length); - if (result.length == 0) { - return output; - } + if (this.onlyContainsUserCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS)) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + valueHex: (new Uint8Array([0xFF])).buffer + })); } - else { - result = findAllResult; + if (this.onlyContainsCACerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS)) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + valueHex: (new Uint8Array([0xFF])).buffer + })); } - output.searchPatternPositions.push(...Array.from(result, element => element.position)); - const patternDifference = searchPattern.length - replacePattern.length; - const changedBuffer = new ArrayBuffer(this.view.length - (result.length * patternDifference)); - const changedView = new Uint8Array(changedBuffer); - changedView.set(new Uint8Array(this.buffer, 0, start)); - for (i = 0; i < result.length; i++) { - const currentPosition = (i == 0) ? start : result[i - 1].position; - changedView.set(new Uint8Array(this.buffer, currentPosition, result[i].position - searchPattern.length - currentPosition), currentPosition - i * patternDifference); - changedView.set(replacePattern.view, result[i].position - searchPattern.length - i * patternDifference); - output.replacePatternPositions.push(result[i].position - searchPattern.length - i * patternDifference); + if (this.onlySomeReasons !== undefined) { + const buffer = new ArrayBuffer(1); + const view = new Uint8Array(buffer); + view[0] = this.onlySomeReasons; + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + valueHex: buffer + })); } - i--; - changedView.set(new Uint8Array(this.buffer, result[i].position, this.length - result[i].position), result[i].position - searchPattern.length + replacePattern.length - i * patternDifference); - this.buffer = changedBuffer; - this.view = new Uint8Array(this.buffer); - output.status = 1; - return output; + if (this.indirectCRL !== IssuingDistributionPoint.defaultValues(INDIRECT_CRL)) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 4 + }, + valueHex: (new Uint8Array([0xFF])).buffer + })); + } + if (this.onlyContainsAttributeCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS)) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 5 + }, + valueHex: (new Uint8Array([0xFF])).buffer + })); + } + return (new Sequence({ + value: outputArray + })); } - skipPatterns(patterns, start_, length_, backward_) { - const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); - let result = start; - for (let k = 0; k < patterns.length; k++) { - const patternLength = patterns[k].length; - const equalStart = (backward) ? (result - patternLength) : (result); - let equal = true; - for (let j = 0; j < patternLength; j++) { - if (this.view[j + equalStart] != patterns[k].view[j]) { - equal = false; - break; - } + toJSON() { + const obj = {}; + if (this.distributionPoint) { + if (this.distributionPoint instanceof Array) { + obj.distributionPoint = Array.from(this.distributionPoint, o => o.toJSON()); } - if (equal) { - k = (-1); - if (backward) { - result -= patternLength; - if (result <= 0) - return result; - } - else { - result += patternLength; - if (result >= (start + length)) - return result; - } + else { + obj.distributionPoint = this.distributionPoint.toJSON(); } } - return result; + if (this.onlyContainsUserCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS)) { + obj.onlyContainsUserCerts = this.onlyContainsUserCerts; + } + if (this.onlyContainsCACerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS)) { + obj.onlyContainsCACerts = this.onlyContainsCACerts; + } + if (ONLY_SOME_REASON in this) { + obj.onlySomeReasons = this.onlySomeReasons; + } + if (this.indirectCRL !== IssuingDistributionPoint.defaultValues(INDIRECT_CRL)) { + obj.indirectCRL = this.indirectCRL; + } + if (this.onlyContainsAttributeCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS)) { + obj.onlyContainsAttributeCerts = this.onlyContainsAttributeCerts; + } + return obj; } - skipNotPatterns(patterns, start_, length_, backward_) { - const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); - let result = (-1); - for (let i = 0; i < length; i++) { - for (let k = 0; k < patterns.length; k++) { - const patternLength = patterns[k].length; - const equalStart = (backward) ? (start - i - patternLength) : (start + i); - let equal = true; - for (let j = 0; j < patternLength; j++) { - if (this.view[j + equalStart] != patterns[k].view[j]) { - equal = false; - break; +} +IssuingDistributionPoint.CLASS_NAME = "IssuingDistributionPoint"; + +const BASE = "base"; +const MINIMUM = "minimum"; +const MAXIMUM = "maximum"; +const CLEAR_PROPS$1h = [ + BASE, + MINIMUM, + MAXIMUM +]; +class GeneralSubtree extends PkiObject { + constructor(parameters = {}) { + super(); + this.base = getParametersValue(parameters, BASE, GeneralSubtree.defaultValues(BASE)); + this.minimum = getParametersValue(parameters, MINIMUM, GeneralSubtree.defaultValues(MINIMUM)); + if (MAXIMUM in parameters) { + this.maximum = getParametersValue(parameters, MAXIMUM, GeneralSubtree.defaultValues(MAXIMUM)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case BASE: + return new GeneralName(); + case MINIMUM: + return 0; + case MAXIMUM: + return 0; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + GeneralName.schema(names.base || {}), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Integer({ name: (names.minimum || EMPTY_STRING) })] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [new Integer({ name: (names.maximum || EMPTY_STRING) })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1h); + const asn1 = compareSchema(schema, schema, GeneralSubtree.schema({ + names: { + base: { + names: { + blockName: BASE } - } - if (equal) { - result = (backward) ? (start - i) : (start + i); - break; - } - } - if (result != (-1)) { - break; + }, + minimum: MINIMUM, + maximum: MAXIMUM } + })); + AsnError.assertSchema(asn1, this.className); + this.base = new GeneralName({ schema: asn1.result.base }); + if (MINIMUM in asn1.result) { + if (asn1.result.minimum.valueBlock.isHexOnly) + this.minimum = asn1.result.minimum; + else + this.minimum = asn1.result.minimum.valueBlock.valueDec; + } + if (MAXIMUM in asn1.result) { + if (asn1.result.maximum.valueBlock.isHexOnly) + this.maximum = asn1.result.maximum; + else + this.maximum = asn1.result.maximum.valueBlock.valueDec; } - return result; } - prepareFindParameters(start = null, length = null, backward = false) { - if (start === null) { - start = (backward) ? this.length : 0; + toSchema() { + const outputArray = []; + outputArray.push(this.base.toSchema()); + if (this.minimum !== 0) { + let valueMinimum = 0; + if (this.minimum instanceof Integer) { + valueMinimum = this.minimum; + } + else { + valueMinimum = new Integer({ value: this.minimum }); + } + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [valueMinimum] + })); } - if (start > this.length) { - start = this.length; + if (MAXIMUM in this) { + let valueMaximum = 0; + if (this.maximum instanceof Integer) { + valueMaximum = this.maximum; + } + else { + valueMaximum = new Integer({ value: this.maximum }); + } + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [valueMaximum] + })); } - if (backward) { - if (length === null) { - length = start; + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + base: this.base.toJSON() + }; + if (this.minimum !== 0) { + if (typeof this.minimum === "number") { + res.minimum = this.minimum; } - if (length > start) { - length = start; + else { + res.minimum = this.minimum.toJSON(); } } - else { - if (length === null) { - length = this.length - start; + if (this.maximum !== undefined) { + if (typeof this.maximum === "number") { + res.maximum = this.maximum; } - if (length > (this.length - start)) { - length = this.length - start; + else { + res.maximum = this.maximum.toJSON(); } } - return { start, length, backward }; + return res; } } +GeneralSubtree.CLASS_NAME = "GeneralSubtree"; -class SeqStream { +const PERMITTED_SUBTREES = "permittedSubtrees"; +const EXCLUDED_SUBTREES = "excludedSubtrees"; +const CLEAR_PROPS$1g = [ + PERMITTED_SUBTREES, + EXCLUDED_SUBTREES +]; +class NameConstraints extends PkiObject { constructor(parameters = {}) { - this._stream = new ByteStream(); - this._length = 0; - this._start = 0; - this.backward = false; - this.appendBlock = 0; - this.prevLength = 0; - this.prevStart = 0; - if ("view" in parameters) { - this.stream = new ByteStream({ view: parameters.view }); + super(); + if (PERMITTED_SUBTREES in parameters) { + this.permittedSubtrees = getParametersValue(parameters, PERMITTED_SUBTREES, NameConstraints.defaultValues(PERMITTED_SUBTREES)); } - else if ("buffer" in parameters) { - this.stream = new ByteStream({ buffer: parameters.buffer }); + if (EXCLUDED_SUBTREES in parameters) { + this.excludedSubtrees = getParametersValue(parameters, EXCLUDED_SUBTREES, NameConstraints.defaultValues(EXCLUDED_SUBTREES)); } - else if ("string" in parameters) { - this.stream = new ByteStream({ string: parameters.string }); + if (parameters.schema) { + this.fromSchema(parameters.schema); } - else if ("hexstring" in parameters) { - this.stream = new ByteStream({ hexstring: parameters.hexstring }); + } + static defaultValues(memberName) { + switch (memberName) { + case PERMITTED_SUBTREES: + case EXCLUDED_SUBTREES: + return []; + default: + return super.defaultValues(memberName); } - else if ("stream" in parameters) { - this.stream = parameters.stream.slice(); + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Repeated({ + name: (names.permittedSubtrees || EMPTY_STRING), + value: GeneralSubtree.schema() + }) + ] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new Repeated({ + name: (names.excludedSubtrees || EMPTY_STRING), + value: GeneralSubtree.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1g); + const asn1 = compareSchema(schema, schema, NameConstraints.schema({ + names: { + permittedSubtrees: PERMITTED_SUBTREES, + excludedSubtrees: EXCLUDED_SUBTREES + } + })); + AsnError.assertSchema(asn1, this.className); + if (PERMITTED_SUBTREES in asn1.result) + this.permittedSubtrees = Array.from(asn1.result.permittedSubtrees, element => new GeneralSubtree({ schema: element })); + if (EXCLUDED_SUBTREES in asn1.result) + this.excludedSubtrees = Array.from(asn1.result.excludedSubtrees, element => new GeneralSubtree({ schema: element })); + } + toSchema() { + const outputArray = []; + if (this.permittedSubtrees) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: Array.from(this.permittedSubtrees, o => o.toSchema()) + })); } - else { - this.stream = new ByteStream(); + if (this.excludedSubtrees) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: Array.from(this.excludedSubtrees, o => o.toSchema()) + })); } - if ("backward" in parameters && parameters.backward) { - this.backward = parameters.backward; - this._start = this.stream.length; + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const object = {}; + if (this.permittedSubtrees) { + object.permittedSubtrees = Array.from(this.permittedSubtrees, o => o.toJSON()); } - if ("length" in parameters && parameters.length > 0) { - this._length = parameters.length; + if (this.excludedSubtrees) { + object.excludedSubtrees = Array.from(this.excludedSubtrees, o => o.toJSON()); } - if ("start" in parameters && parameters.start && parameters.start > 0) { - this._start = parameters.start; + return object; + } +} +NameConstraints.CLASS_NAME = "NameConstraints"; + +const REQUIRE_EXPLICIT_POLICY = "requireExplicitPolicy"; +const INHIBIT_POLICY_MAPPING = "inhibitPolicyMapping"; +const CLEAR_PROPS$1f = [ + REQUIRE_EXPLICIT_POLICY, + INHIBIT_POLICY_MAPPING, +]; +class PolicyConstraints extends PkiObject { + constructor(parameters = {}) { + super(); + if (REQUIRE_EXPLICIT_POLICY in parameters) { + this.requireExplicitPolicy = getParametersValue(parameters, REQUIRE_EXPLICIT_POLICY, PolicyConstraints.defaultValues(REQUIRE_EXPLICIT_POLICY)); } - if ("appendBlock" in parameters && parameters.appendBlock && parameters.appendBlock > 0) { - this.appendBlock = parameters.appendBlock; + if (INHIBIT_POLICY_MAPPING in parameters) { + this.inhibitPolicyMapping = getParametersValue(parameters, INHIBIT_POLICY_MAPPING, PolicyConstraints.defaultValues(INHIBIT_POLICY_MAPPING)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); } } - set stream(value) { - this._stream = value; - this.prevLength = this._length; - this._length = value.length; - this.prevStart = this._start; - this._start = 0; + static defaultValues(memberName) { + switch (memberName) { + case REQUIRE_EXPLICIT_POLICY: + return 0; + case INHIBIT_POLICY_MAPPING: + return 0; + default: + return super.defaultValues(memberName); + } } - get stream() { - return this._stream; + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Primitive({ + name: (names.requireExplicitPolicy || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + } + }), + new Primitive({ + name: (names.inhibitPolicyMapping || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + } + }) + ] + })); } - set length(value) { - this.prevLength = this._length; - this._length = value; + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1f); + const asn1 = compareSchema(schema, schema, PolicyConstraints.schema({ + names: { + requireExplicitPolicy: REQUIRE_EXPLICIT_POLICY, + inhibitPolicyMapping: INHIBIT_POLICY_MAPPING + } + })); + AsnError.assertSchema(asn1, this.className); + if (REQUIRE_EXPLICIT_POLICY in asn1.result) { + const field1 = asn1.result.requireExplicitPolicy; + field1.idBlock.tagClass = 1; + field1.idBlock.tagNumber = 2; + const ber1 = field1.toBER(false); + const int1 = fromBER(ber1); + AsnError.assert(int1, "Integer"); + this.requireExplicitPolicy = int1.result.valueBlock.valueDec; + } + if (INHIBIT_POLICY_MAPPING in asn1.result) { + const field2 = asn1.result.inhibitPolicyMapping; + field2.idBlock.tagClass = 1; + field2.idBlock.tagNumber = 2; + const ber2 = field2.toBER(false); + const int2 = fromBER(ber2); + AsnError.assert(int2, "Integer"); + this.inhibitPolicyMapping = int2.result.valueBlock.valueDec; + } } - get length() { - if (this.appendBlock) { - return this.start; + toSchema() { + const outputArray = []; + if (REQUIRE_EXPLICIT_POLICY in this) { + const int1 = new Integer({ value: this.requireExplicitPolicy }); + int1.idBlock.tagClass = 3; + int1.idBlock.tagNumber = 0; + outputArray.push(int1); } - return this._length; + if (INHIBIT_POLICY_MAPPING in this) { + const int2 = new Integer({ value: this.inhibitPolicyMapping }); + int2.idBlock.tagClass = 3; + int2.idBlock.tagNumber = 1; + outputArray.push(int2); + } + return (new Sequence({ + value: outputArray + })); } - set start(value) { - if (value > this.stream.length) - return; - this.prevStart = this._start; - this.prevLength = this._length; - this._length -= (this.backward) ? (this._start - value) : (value - this._start); - this._start = value; + toJSON() { + const res = {}; + if (REQUIRE_EXPLICIT_POLICY in this) { + res.requireExplicitPolicy = this.requireExplicitPolicy; + } + if (INHIBIT_POLICY_MAPPING in this) { + res.inhibitPolicyMapping = this.inhibitPolicyMapping; + } + return res; } - get start() { - return this._start; +} +PolicyConstraints.CLASS_NAME = "PolicyConstraints"; + +const ISSUER_DOMAIN_POLICY = "issuerDomainPolicy"; +const SUBJECT_DOMAIN_POLICY = "subjectDomainPolicy"; +const CLEAR_PROPS$1e = [ + ISSUER_DOMAIN_POLICY, + SUBJECT_DOMAIN_POLICY +]; +class PolicyMapping extends PkiObject { + constructor(parameters = {}) { + super(); + this.issuerDomainPolicy = getParametersValue(parameters, ISSUER_DOMAIN_POLICY, PolicyMapping.defaultValues(ISSUER_DOMAIN_POLICY)); + this.subjectDomainPolicy = getParametersValue(parameters, SUBJECT_DOMAIN_POLICY, PolicyMapping.defaultValues(SUBJECT_DOMAIN_POLICY)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } } - get buffer() { - return this._stream.buffer.slice(0, this._length); + static defaultValues(memberName) { + switch (memberName) { + case ISSUER_DOMAIN_POLICY: + return EMPTY_STRING; + case SUBJECT_DOMAIN_POLICY: + return EMPTY_STRING; + default: + return super.defaultValues(memberName); + } } - resetPosition() { - this._start = this.prevStart; - this._length = this.prevLength; + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.issuerDomainPolicy || EMPTY_STRING) }), + new ObjectIdentifier({ name: (names.subjectDomainPolicy || EMPTY_STRING) }) + ] + })); } - findPattern(pattern, gap = null) { - if ((gap == null) || (gap > this.length)) { - gap = this.length; - } - const result = this.stream.findPattern(pattern, this.start, this.length, this.backward); - if (result == (-1)) - return result; - if (this.backward) { - if (result < (this.start - pattern.length - gap)) { - return (-1); - } - } - else { - if (result > (this.start + pattern.length + gap)) { - return (-1); + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1e); + const asn1 = compareSchema(schema, schema, PolicyMapping.schema({ + names: { + issuerDomainPolicy: ISSUER_DOMAIN_POLICY, + subjectDomainPolicy: SUBJECT_DOMAIN_POLICY } - } - this.start = result; - return result; + })); + AsnError.assertSchema(asn1, this.className); + this.issuerDomainPolicy = asn1.result.issuerDomainPolicy.valueBlock.toString(); + this.subjectDomainPolicy = asn1.result.subjectDomainPolicy.valueBlock.toString(); } - findFirstIn(patterns, gap = null) { - if ((gap == null) || (gap > this.length)) { - gap = this.length; - } - const result = this.stream.findFirstIn(patterns, this.start, this.length, this.backward); - if (result.id == (-1)) - return result; - if (this.backward) { - if (result.position < (this.start - patterns[result.id].length - gap)) { - return { - id: (-1), - position: (this.backward) ? 0 : (this.start + this.length) - }; - } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.issuerDomainPolicy }), + new ObjectIdentifier({ value: this.subjectDomainPolicy }) + ] + })); + } + toJSON() { + return { + issuerDomainPolicy: this.issuerDomainPolicy, + subjectDomainPolicy: this.subjectDomainPolicy + }; + } +} +PolicyMapping.CLASS_NAME = "PolicyMapping"; + +const MAPPINGS = "mappings"; +const CLEAR_PROPS$1d = [ + MAPPINGS, +]; +class PolicyMappings extends PkiObject { + constructor(parameters = {}) { + super(); + this.mappings = getParametersValue(parameters, MAPPINGS, PolicyMappings.defaultValues(MAPPINGS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); } - else { - if (result.position > (this.start + patterns[result.id].length + gap)) { - return { - id: (-1), - position: (this.backward) ? 0 : (this.start + this.length) - }; - } + } + static defaultValues(memberName) { + switch (memberName) { + case MAPPINGS: + return []; + default: + return super.defaultValues(memberName); } - this.start = result.position; - return result; } - findAllIn(patterns) { - const start = (this.backward) ? (this.start - this.length) : this.start; - return this.stream.findAllIn(patterns, start, this.length); + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.mappings || EMPTY_STRING), + value: PolicyMapping.schema() + }) + ] + })); } - findFirstNotIn(patterns, gap = null) { - if ((gap == null) || (gap > this._length)) { - gap = this._length; + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1d); + const asn1 = compareSchema(schema, schema, PolicyMappings.schema({ + names: { + mappings: MAPPINGS + } + })); + AsnError.assertSchema(asn1, this.className); + this.mappings = Array.from(asn1.result.mappings, element => new PolicyMapping({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.mappings, o => o.toSchema()) + })); + } + toJSON() { + return { + mappings: Array.from(this.mappings, o => o.toJSON()) + }; + } +} +PolicyMappings.CLASS_NAME = "PolicyMappings"; + +const NOT_BEFORE$1 = "notBefore"; +const NOT_AFTER$1 = "notAfter"; +const CLEAR_PROPS$1c = [ + NOT_BEFORE$1, + NOT_AFTER$1 +]; +class PrivateKeyUsagePeriod extends PkiObject { + constructor(parameters = {}) { + super(); + if (NOT_BEFORE$1 in parameters) { + this.notBefore = getParametersValue(parameters, NOT_BEFORE$1, PrivateKeyUsagePeriod.defaultValues(NOT_BEFORE$1)); } - const result = this._stream.findFirstNotIn(patterns, this._start, this._length, this.backward); - if ((result.left.id == (-1)) && (result.right.id == (-1))) { - return result; + if (NOT_AFTER$1 in parameters) { + this.notAfter = getParametersValue(parameters, NOT_AFTER$1, PrivateKeyUsagePeriod.defaultValues(NOT_AFTER$1)); } - if (this.backward) { - if (result.right.id != (-1)) { - if (result.right.position < (this._start - patterns[result.right.id].length - gap)) { - return { - left: { - id: (-1), - position: this._start - }, - right: { - id: (-1), - position: 0 - }, - value: new ByteStream() - }; - } - } + if (parameters.schema) { + this.fromSchema(parameters.schema); } - else { - if (result.left.id != (-1)) { - if (result.left.position > (this._start + patterns[result.left.id].length + gap)) { - return { - left: { - id: (-1), - position: this._start - }, - right: { - id: (-1), - position: 0 - }, - value: new ByteStream() - }; - } - } + } + static defaultValues(memberName) { + switch (memberName) { + case NOT_BEFORE$1: + return new Date(); + case NOT_AFTER$1: + return new Date(); + default: + return super.defaultValues(memberName); } - if (this.backward) { - if (result.left.id == (-1)) { - this.start = 0; - } - else { - this.start = result.left.position; + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Primitive({ + name: (names.notBefore || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + } + }), + new Primitive({ + name: (names.notAfter || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1c); + const asn1 = compareSchema(schema, schema, PrivateKeyUsagePeriod.schema({ + names: { + notBefore: NOT_BEFORE$1, + notAfter: NOT_AFTER$1 } + })); + AsnError.assertSchema(asn1, this.className); + if (NOT_BEFORE$1 in asn1.result) { + const localNotBefore = new GeneralizedTime(); + localNotBefore.fromBuffer(asn1.result.notBefore.valueBlock.valueHex); + this.notBefore = localNotBefore.toDate(); } - else { - if (result.right.id == (-1)) { - this.start = (this._start + this._length); - } - else { - this.start = result.right.position; - } + if (NOT_AFTER$1 in asn1.result) { + const localNotAfter = new GeneralizedTime({ valueHex: asn1.result.notAfter.valueBlock.valueHex }); + localNotAfter.fromBuffer(asn1.result.notAfter.valueBlock.valueHex); + this.notAfter = localNotAfter.toDate(); } - return result; } - findAllNotIn(patterns) { - const start = (this.backward) ? (this._start - this._length) : this._start; - return this._stream.findAllNotIn(patterns, start, this._length); + toSchema() { + const outputArray = []; + if (NOT_BEFORE$1 in this) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + valueHex: (new GeneralizedTime({ valueDate: this.notBefore })).valueBlock.valueHexView + })); + } + if (NOT_AFTER$1 in this) { + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + valueHex: (new GeneralizedTime({ valueDate: this.notAfter })).valueBlock.valueHexView + })); + } + return (new Sequence({ + value: outputArray + })); } - findFirstSequence(patterns, length = null, gap = null) { - if ((length == null) || (length > this._length)) { - length = this._length; + toJSON() { + const res = {}; + if (this.notBefore) { + res.notBefore = this.notBefore; } - if ((gap == null) || (gap > length)) { - gap = length; + if (this.notAfter) { + res.notAfter = this.notAfter; } - const result = this._stream.findFirstSequence(patterns, this._start, length, this.backward); - if (result.value.length == 0) { - return result; + return res; + } +} +PrivateKeyUsagePeriod.CLASS_NAME = "PrivateKeyUsagePeriod"; + +const ID = "id"; +const TYPE$2 = "type"; +const VALUES = "values"; +const QC_STATEMENT_CLEAR_PROPS = [ + ID, + TYPE$2 +]; +const QC_STATEMENTS_CLEAR_PROPS = [ + VALUES +]; +class QCStatement extends PkiObject { + constructor(parameters = {}) { + super(); + this.id = getParametersValue(parameters, ID, QCStatement.defaultValues(ID)); + if (TYPE$2 in parameters) { + this.type = getParametersValue(parameters, TYPE$2, QCStatement.defaultValues(TYPE$2)); } - if (this.backward) { - if (result.position < (this._start - result.value.length - gap)) { - return { - position: (-1), - value: new ByteStream() - }; - } + if (parameters.schema) { + this.fromSchema(parameters.schema); } - else { - if (result.position > (this._start + result.value.length + gap)) { - return { - position: (-1), - value: new ByteStream() - }; + } + static defaultValues(memberName) { + switch (memberName) { + case ID: + return EMPTY_STRING; + case TYPE$2: + return new Null(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case ID: + return (memberValue === EMPTY_STRING); + case TYPE$2: + return (memberValue instanceof Null); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.id || EMPTY_STRING) }), + new Any({ + name: (names.type || EMPTY_STRING), + optional: true + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, QC_STATEMENT_CLEAR_PROPS); + const asn1 = compareSchema(schema, schema, QCStatement.schema({ + names: { + id: ID, + type: TYPE$2 } + })); + AsnError.assertSchema(asn1, this.className); + this.id = asn1.result.id.valueBlock.toString(); + if (TYPE$2 in asn1.result) + this.type = asn1.result.type; + } + toSchema() { + const value = [ + new ObjectIdentifier({ value: this.id }) + ]; + if (TYPE$2 in this) + value.push(this.type); + return (new Sequence({ + value, + })); + } + toJSON() { + const object = { + id: this.id + }; + if (this.type) { + object.type = this.type.toJSON(); } - this.start = result.position; - return result; + return object; } - findAllSequences(patterns) { - const start = (this.backward) ? (this.start - this.length) : this.start; - return this.stream.findAllSequences(patterns, start, this.length); +} +QCStatement.CLASS_NAME = "QCStatement"; +class QCStatements extends PkiObject { + constructor(parameters = {}) { + super(); + this.values = getParametersValue(parameters, VALUES, QCStatements.defaultValues(VALUES)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } } - findPairedPatterns(leftPattern, rightPattern, gap = null) { - if ((gap == null) || (gap > this.length)) { - gap = this.length; + static defaultValues(memberName) { + switch (memberName) { + case VALUES: + return []; + default: + return super.defaultValues(memberName); } - const start = (this.backward) ? (this.start - this.length) : this.start; - const result = this.stream.findPairedPatterns(leftPattern, rightPattern, start, this.length); - if (result.length) { - if (this.backward) { - if (result[0].right < (this.start - rightPattern.length - gap)) { - return []; - } - } - else { - if (result[0].left > (this.start + leftPattern.length + gap)) { - return []; - } - } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VALUES: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); } - return result; } - findPairedArrays(leftPatterns, rightPatterns, gap = null) { - if ((gap == null) || (gap > this.length)) { - gap = this.length; + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.values || EMPTY_STRING), + value: QCStatement.schema(names.value || {}) + }), + ] + })); + } + fromSchema(schema) { + clearProps(schema, QC_STATEMENTS_CLEAR_PROPS); + const asn1 = compareSchema(schema, schema, QCStatements.schema({ + names: { + values: VALUES + } + })); + AsnError.assertSchema(asn1, this.className); + this.values = Array.from(asn1.result.values, element => new QCStatement({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.values, o => o.toSchema()) + })); + } + toJSON() { + return { + values: Array.from(this.values, o => o.toJSON()) + }; + } +} +QCStatements.CLASS_NAME = "QCStatements"; + +class ByteStream { + constructor(parameters = {}) { + if ("view" in parameters) { + this.fromUint8Array(parameters.view); } - const start = (this.backward) ? (this.start - this.length) : this.start; - const result = this.stream.findPairedArrays(leftPatterns, rightPatterns, start, this.length); - if (result.length) { - if (this.backward) { - if (result[0].right.position < (this.start - rightPatterns[result[0].right.id].length - gap)) { - return []; + else if ("buffer" in parameters) { + this.fromArrayBuffer(parameters.buffer); + } + else if ("string" in parameters) { + this.fromString(parameters.string); + } + else if ("hexstring" in parameters) { + this.fromHexString(parameters.hexstring); + } + else { + if ("length" in parameters && parameters.length > 0) { + this.length = parameters.length; + if (parameters.stub) { + for (let i = 0; i < this._view.length; i++) { + this._view[i] = parameters.stub; + } } } else { - if (result[0].left.position > (this.start + leftPatterns[result[0].left.id].length + gap)) { - return []; - } + this.length = 0; } } - return result; } - replacePattern(searchPattern, replacePattern) { - const start = (this.backward) ? (this.start - this.length) : this.start; - return this.stream.replacePattern(searchPattern, replacePattern, start, this.length); + set buffer(value) { + this._buffer = value; + this._view = new Uint8Array(this._buffer); } - skipPatterns(patterns) { - const result = this.stream.skipPatterns(patterns, this.start, this.length, this.backward); - this.start = result; - return result; + get buffer() { + return this._buffer; } - skipNotPatterns(patterns) { - const result = this.stream.skipNotPatterns(patterns, this.start, this.length, this.backward); - if (result == (-1)) - return (-1); - this.start = result; - return result; + set view(value) { + this._buffer = new ArrayBuffer(value.length); + this._view = new Uint8Array(this._buffer); + this._view.set(value); } - append(stream) { - this.beforeAppend(stream.length); - this._stream.view.set(stream.view, this._start); - this._length += (stream.length * 2); - this.start = (this._start + stream.length); - this.prevLength -= (stream.length * 2); + get view() { + return this._view; } - appendView(view) { - this.beforeAppend(view.length); - this._stream.view.set(view, this._start); - this._length += (view.length * 2); - this.start = (this._start + view.length); - this.prevLength -= (view.length * 2); + get length() { + return this.view.byteLength; } - appendChar(char) { - this.beforeAppend(1); - this._stream.view[this._start] = char; - this._length += 2; - this.start = (this._start + 1); - this.prevLength -= 2; + set length(value) { + this._buffer = new ArrayBuffer(value); + this._view = new Uint8Array(this._buffer); } - appendUint16(number) { - this.beforeAppend(2); - const value = new Uint16Array([number]); - const view = new Uint8Array(value.buffer); - this.stream.view[this._start] = view[1]; - this._stream.view[this._start + 1] = view[0]; - this._length += 4; - this.start = this._start + 2; - this.prevLength -= 4; - } - appendUint24(number) { - this.beforeAppend(3); - const value = new Uint32Array([number]); - const view = new Uint8Array(value.buffer); - this._stream.view[this._start] = view[2]; - this._stream.view[this._start + 1] = view[1]; - this._stream.view[this._start + 2] = view[0]; - this._length += 6; - this.start = (this._start + 3); - this.prevLength -= 6; + clear() { + this._buffer = new ArrayBuffer(0); + this._view = new Uint8Array(this._buffer); } - appendUint32(number) { - this.beforeAppend(4); - const value = new Uint32Array([number]); - const view = new Uint8Array(value.buffer); - this._stream.view[this._start] = view[3]; - this._stream.view[this._start + 1] = view[2]; - this._stream.view[this._start + 2] = view[1]; - this._stream.view[this._start + 3] = view[0]; - this._length += 8; - this.start = (this._start + 4); - this.prevLength -= 8; + fromArrayBuffer(array) { + this._buffer = array; + this._view = new Uint8Array(this._buffer); } - appendInt16(number) { - this.beforeAppend(2); - const value = new Int16Array([number]); - const view = new Uint8Array(value.buffer); - this._stream.view[this._start] = view[1]; - this._stream.view[this._start + 1] = view[0]; - this._length += 4; - this.start = (this._start + 2); - this.prevLength -= 4; + fromUint8Array(array) { + this.fromArrayBuffer(new Uint8Array(array).buffer); } - appendInt32(number) { - this.beforeAppend(4); - const value = new Int32Array([number]); - const view = new Uint8Array(value.buffer); - this._stream.view[this._start] = view[3]; - this._stream.view[this._start + 1] = view[2]; - this._stream.view[this._start + 2] = view[1]; - this._stream.view[this._start + 3] = view[0]; - this._length += 8; - this.start = (this._start + 4); - this.prevLength -= 8; + fromString(string) { + const stringLength = string.length; + this.length = stringLength; + for (let i = 0; i < stringLength; i++) + this.view[i] = string.charCodeAt(i); } - getBlock(size, changeLength = true) { - if (this._length <= 0) { - return new Uint8Array(0); + toString(start = 0, length = (this.view.length - start)) { + let result = ""; + if ((start >= this.view.length) || (start < 0)) { + start = 0; } - if (this._length < size) { - size = this._length; + if ((length >= this.view.length) || (length < 0)) { + length = this.view.length - start; } - let result; - if (this.backward) { - const view = this._stream.view.subarray(this._length - size, this._length); - result = new Uint8Array(size); - for (let i = 0; i < size; i++) { - result[size - 1 - i] = view[i]; + for (let i = start; i < (start + length); i++) + result += String.fromCharCode(this.view[i]); + return result; + } + fromHexString(hexString) { + const stringLength = hexString.length; + this.buffer = new ArrayBuffer(stringLength >> 1); + this.view = new Uint8Array(this.buffer); + const hexMap = new Map(); + hexMap.set("0", 0x00); + hexMap.set("1", 0x01); + hexMap.set("2", 0x02); + hexMap.set("3", 0x03); + hexMap.set("4", 0x04); + hexMap.set("5", 0x05); + hexMap.set("6", 0x06); + hexMap.set("7", 0x07); + hexMap.set("8", 0x08); + hexMap.set("9", 0x09); + hexMap.set("A", 0x0A); + hexMap.set("a", 0x0A); + hexMap.set("B", 0x0B); + hexMap.set("b", 0x0B); + hexMap.set("C", 0x0C); + hexMap.set("c", 0x0C); + hexMap.set("D", 0x0D); + hexMap.set("d", 0x0D); + hexMap.set("E", 0x0E); + hexMap.set("e", 0x0E); + hexMap.set("F", 0x0F); + hexMap.set("f", 0x0F); + let j = 0; + let temp = 0x00; + for (let i = 0; i < stringLength; i++) { + if (!(i % 2)) { + temp = hexMap.get(hexString.charAt(i)) << 4; + } + else { + temp |= hexMap.get(hexString.charAt(i)); + this.view[j] = temp; + j++; } } - else { - result = this._stream.view.subarray(this._start, this._start + size); + } + toHexString(start = 0, length = (this.view.length - start)) { + let result = ""; + if ((start >= this.view.length) || (start < 0)) { + start = 0; } - if (changeLength) { - this.start += ((this.backward) ? ((-1) * size) : size); + if ((length >= this.view.length) || (length < 0)) { + length = this.view.length - start; + } + for (let i = start; i < (start + length); i++) { + const str = this.view[i].toString(16).toUpperCase(); + result = result + ((str.length == 1) ? "0" : "") + str; } return result; } - getUint16(changeLength = true) { - const block = this.getBlock(2, changeLength); - if (block.length < 2) - return 0; - const value = new Uint16Array(1); - const view = new Uint8Array(value.buffer); - view[0] = block[1]; - view[1] = block[0]; - return value[0]; + copy(start = 0, length = (this.length - start)) { + if (!start && !this.length) { + return new ByteStream(); + } + if ((start < 0) || (start > (this.length - 1))) { + throw new Error(`Wrong start position: ${start}`); + } + const stream = new ByteStream({ + buffer: this._buffer.slice(start, start + length) + }); + return stream; } - getInt16(changeLength = true) { - const block = this.getBlock(2, changeLength); - if (block.length < 2) - return 0; - const value = new Int16Array(1); - const view = new Uint8Array(value.buffer); - view[0] = block[1]; - view[1] = block[0]; - return value[0]; + slice(start = 0, end = this.length) { + if (!start && !this.length) { + return new ByteStream(); + } + if ((start < 0) || (start > (this.length - 1))) { + throw new Error(`Wrong start position: ${start}`); + } + const stream = new ByteStream({ + buffer: this._buffer.slice(start, end), + }); + return stream; } - getUint24(changeLength = true) { - const block = this.getBlock(3, changeLength); - if (block.length < 3) - return 0; - const value = new Uint32Array(1); - const view = new Uint8Array(value.buffer); - for (let i = 3; i >= 1; i--) { - view[3 - i] = block[i - 1]; + realloc(size) { + const buffer = new ArrayBuffer(size); + const view = new Uint8Array(buffer); + if (size > this._view.length) + view.set(this._view); + else { + view.set(new Uint8Array(this._buffer, 0, size)); } - return value[0]; + this._buffer = buffer; + this._view = new Uint8Array(this._buffer); } - getUint32(changeLength = true) { - const block = this.getBlock(4, changeLength); - if (block.length < 4) { - return 0; + append(stream) { + const initialSize = this.length; + const streamViewLength = stream.length; + const subarrayView = stream._view.subarray(); + this.realloc(initialSize + streamViewLength); + this._view.set(subarrayView, initialSize); + } + insert(stream, start = 0, length = (this.length - start)) { + if (start > (this.length - 1)) + return false; + if (length > (this.length - start)) { + length = this.length - start; } - const value = new Uint32Array(1); - const view = new Uint8Array(value.buffer); - for (let i = 3; i >= 0; i--) { - view[3 - i] = block[i]; + if (length > stream.length) { + length = stream.length; } - return value[0]; + if (length == stream.length) + this._view.set(stream._view, start); + else { + this._view.set(stream._view.subarray(0, length), start); + } + return true; } - getInt32(changeLength = true) { - const block = this.getBlock(4, changeLength); - if (block.length < 4) - return 0; - const value = new Int32Array(1); - const view = new Uint8Array(value.buffer); - for (let i = 3; i >= 0; i--) { - view[3 - i] = block[i]; + isEqual(stream) { + if (this.length != stream.length) + return false; + for (let i = 0; i < stream.length; i++) { + if (this.view[i] != stream.view[i]) + return false; } - return value[0]; + return true; } - beforeAppend(size) { - if ((this._start + size) > this._stream.length) { - if (size > this.appendBlock) { - this.appendBlock = size + SeqStream.APPEND_BLOCK; + isEqualView(view) { + if (view.length != this.view.length) + return false; + for (let i = 0; i < view.length; i++) { + if (this.view[i] != view[i]) + return false; + } + return true; + } + findPattern(pattern, start_, length_, backward_) { + const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); + const patternLength = pattern.length; + if (patternLength > length) { + return (-1); + } + const patternArray = []; + for (let i = 0; i < patternLength; i++) + patternArray.push(pattern.view[i]); + for (let i = 0; i <= (length - patternLength); i++) { + let equal = true; + const equalStart = (backward) ? (start - patternLength - i) : (start + i); + for (let j = 0; j < patternLength; j++) { + if (this.view[j + equalStart] != patternArray[j]) { + equal = false; + break; + } + } + if (equal) { + return (backward) ? (start - patternLength - i) : (start + patternLength + i); } - this._stream.realloc(this._stream.length + this.appendBlock); } + return (-1); } + findFirstIn(patterns, start_, length_, backward_) { + const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); + const result = { + id: (-1), + position: (backward) ? 0 : (start + length), + length: 0 + }; + for (let i = 0; i < patterns.length; i++) { + const position = this.findPattern(patterns[i], start, length, backward); + if (position != (-1)) { + let valid = false; + const patternLength = patterns[i].length; + if (backward) { + if ((position - patternLength) >= (result.position - result.length)) + valid = true; + } + else { + if ((position - patternLength) <= (result.position - result.length)) + valid = true; + } + if (valid) { + result.position = position; + result.id = i; + result.length = patternLength; + } + } + } + return result; + } + findAllIn(patterns, start_, length_) { + let { start, length } = this.prepareFindParameters(start_, length_); + const result = []; + let patternFound = { + id: (-1), + position: start + }; + do { + const position = patternFound.position; + patternFound = this.findFirstIn(patterns, patternFound.position, length); + if (patternFound.id == (-1)) { + break; + } + length -= (patternFound.position - position); + result.push({ + id: patternFound.id, + position: patternFound.position + }); + } while (true); + return result; + } + findAllPatternIn(pattern, start_, length_) { + const { start, length } = this.prepareFindParameters(start_, length_); + const result = []; + const patternLength = pattern.length; + if (patternLength > length) { + return (-1); + } + const patternArray = Array.from(pattern.view); + for (let i = 0; i <= (length - patternLength); i++) { + let equal = true; + const equalStart = start + i; + for (let j = 0; j < patternLength; j++) { + if (this.view[j + equalStart] != patternArray[j]) { + equal = false; + break; + } + } + if (equal) { + result.push(start + patternLength + i); + i += (patternLength - 1); + } + } + return result; + } + findFirstNotIn(patterns, start_, length_, backward_) { + let { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); + const result = { + left: { + id: (-1), + position: start + }, + right: { + id: (-1), + position: 0 + }, + value: new ByteStream() + }; + let currentLength = length; + while (currentLength > 0) { + result.right = this.findFirstIn(patterns, (backward) ? (start - length + currentLength) : (start + length - currentLength), currentLength, backward); + if (result.right.id == (-1)) { + length = currentLength; + if (backward) { + start -= length; + } + else { + start = result.left.position; + } + result.value = new ByteStream({ + buffer: this._buffer.slice(start, start + length), + }); + break; + } + if (result.right.position != ((backward) ? (result.left.position - patterns[result.right.id].length) : (result.left.position + patterns[result.right.id].length))) { + if (backward) { + start = result.right.position + patterns[result.right.id].length; + length = result.left.position - result.right.position - patterns[result.right.id].length; + } + else { + start = result.left.position; + length = result.right.position - result.left.position - patterns[result.right.id].length; + } + result.value = new ByteStream({ + buffer: this._buffer.slice(start, start + length), + }); + break; + } + result.left = result.right; + currentLength -= patterns[result.right.id].length; + } + if (backward) { + const temp = result.right; + result.right = result.left; + result.left = temp; + } + return result; + } + findAllNotIn(patterns, start_, length_) { + let { start, length } = this.prepareFindParameters(start_, length_); + const result = []; + let patternFound = { + left: { + id: (-1), + position: start + }, + right: { + id: (-1), + position: start + }, + value: new ByteStream() + }; + do { + const position = patternFound.right.position; + patternFound = this.findFirstNotIn(patterns, patternFound.right.position, length); + length -= (patternFound.right.position - position); + result.push({ + left: { + id: patternFound.left.id, + position: patternFound.left.position + }, + right: { + id: patternFound.right.id, + position: patternFound.right.position + }, + value: patternFound.value + }); + } while (patternFound.right.id != (-1)); + return result; + } + findFirstSequence(patterns, start_, length_, backward_) { + let { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); + const firstIn = this.skipNotPatterns(patterns, start, length, backward); + if (firstIn == (-1)) { + return { + position: (-1), + value: new ByteStream() + }; + } + const firstNotIn = this.skipPatterns(patterns, firstIn, length - ((backward) ? (start - firstIn) : (firstIn - start)), backward); + if (backward) { + start = firstNotIn; + length = (firstIn - firstNotIn); + } + else { + start = firstIn; + length = (firstNotIn - firstIn); + } + const value = new ByteStream({ + buffer: this._buffer.slice(start, start + length), + }); + return { + position: firstNotIn, + value + }; + } + findAllSequences(patterns, start_, length_) { + let { start, length } = this.prepareFindParameters(start_, length_); + const result = []; + let patternFound = { + position: start, + value: new ByteStream() + }; + do { + const position = patternFound.position; + patternFound = this.findFirstSequence(patterns, patternFound.position, length); + if (patternFound.position != (-1)) { + length -= (patternFound.position - position); + result.push({ + position: patternFound.position, + value: patternFound.value, + }); + } + } while (patternFound.position != (-1)); + return result; + } + findPairedPatterns(leftPattern, rightPattern, start_, length_) { + const result = []; + if (leftPattern.isEqual(rightPattern)) + return result; + const { start, length } = this.prepareFindParameters(start_, length_); + let currentPositionLeft = 0; + const leftPatterns = this.findAllPatternIn(leftPattern, start, length); + if (!Array.isArray(leftPatterns) || leftPatterns.length == 0) { + return result; + } + const rightPatterns = this.findAllPatternIn(rightPattern, start, length); + if (!Array.isArray(rightPatterns) || rightPatterns.length == 0) { + return result; + } + while (currentPositionLeft < leftPatterns.length) { + if (rightPatterns.length == 0) { + break; + } + if (leftPatterns[0] == rightPatterns[0]) { + result.push({ + left: leftPatterns[0], + right: rightPatterns[0] + }); + leftPatterns.splice(0, 1); + rightPatterns.splice(0, 1); + continue; + } + if (leftPatterns[currentPositionLeft] > rightPatterns[0]) { + break; + } + while (leftPatterns[currentPositionLeft] < rightPatterns[0]) { + currentPositionLeft++; + if (currentPositionLeft >= leftPatterns.length) { + break; + } + } + result.push({ + left: leftPatterns[currentPositionLeft - 1], + right: rightPatterns[0] + }); + leftPatterns.splice(currentPositionLeft - 1, 1); + rightPatterns.splice(0, 1); + currentPositionLeft = 0; + } + result.sort((a, b) => (a.left - b.left)); + return result; + } + findPairedArrays(inputLeftPatterns, inputRightPatterns, start_, length_) { + const { start, length } = this.prepareFindParameters(start_, length_); + const result = []; + let currentPositionLeft = 0; + const leftPatterns = this.findAllIn(inputLeftPatterns, start, length); + if (leftPatterns.length == 0) + return result; + const rightPatterns = this.findAllIn(inputRightPatterns, start, length); + if (rightPatterns.length == 0) + return result; + while (currentPositionLeft < leftPatterns.length) { + if (rightPatterns.length == 0) { + break; + } + if (leftPatterns[0].position == rightPatterns[0].position) { + result.push({ + left: leftPatterns[0], + right: rightPatterns[0] + }); + leftPatterns.splice(0, 1); + rightPatterns.splice(0, 1); + continue; + } + if (leftPatterns[currentPositionLeft].position > rightPatterns[0].position) { + break; + } + while (leftPatterns[currentPositionLeft].position < rightPatterns[0].position) { + currentPositionLeft++; + if (currentPositionLeft >= leftPatterns.length) { + break; + } + } + result.push({ + left: leftPatterns[currentPositionLeft - 1], + right: rightPatterns[0] + }); + leftPatterns.splice(currentPositionLeft - 1, 1); + rightPatterns.splice(0, 1); + currentPositionLeft = 0; + } + result.sort((a, b) => (a.left.position - b.left.position)); + return result; + } + replacePattern(searchPattern, replacePattern, start_, length_, findAllResult = null) { + let result = []; + let i; + const output = { + status: (-1), + searchPatternPositions: [], + replacePatternPositions: [] + }; + const { start, length } = this.prepareFindParameters(start_, length_); + if (findAllResult == null) { + result = this.findAllIn([searchPattern], start, length); + if (result.length == 0) { + return output; + } + } + else { + result = findAllResult; + } + output.searchPatternPositions.push(...Array.from(result, element => element.position)); + const patternDifference = searchPattern.length - replacePattern.length; + const changedBuffer = new ArrayBuffer(this.view.length - (result.length * patternDifference)); + const changedView = new Uint8Array(changedBuffer); + changedView.set(new Uint8Array(this.buffer, 0, start)); + for (i = 0; i < result.length; i++) { + const currentPosition = (i == 0) ? start : result[i - 1].position; + changedView.set(new Uint8Array(this.buffer, currentPosition, result[i].position - searchPattern.length - currentPosition), currentPosition - i * patternDifference); + changedView.set(replacePattern.view, result[i].position - searchPattern.length - i * patternDifference); + output.replacePatternPositions.push(result[i].position - searchPattern.length - i * patternDifference); + } + i--; + changedView.set(new Uint8Array(this.buffer, result[i].position, this.length - result[i].position), result[i].position - searchPattern.length + replacePattern.length - i * patternDifference); + this.buffer = changedBuffer; + this.view = new Uint8Array(this.buffer); + output.status = 1; + return output; + } + skipPatterns(patterns, start_, length_, backward_) { + const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); + let result = start; + for (let k = 0; k < patterns.length; k++) { + const patternLength = patterns[k].length; + const equalStart = (backward) ? (result - patternLength) : (result); + let equal = true; + for (let j = 0; j < patternLength; j++) { + if (this.view[j + equalStart] != patterns[k].view[j]) { + equal = false; + break; + } + } + if (equal) { + k = (-1); + if (backward) { + result -= patternLength; + if (result <= 0) + return result; + } + else { + result += patternLength; + if (result >= (start + length)) + return result; + } + } + } + return result; + } + skipNotPatterns(patterns, start_, length_, backward_) { + const { start, length, backward } = this.prepareFindParameters(start_, length_, backward_); + let result = (-1); + for (let i = 0; i < length; i++) { + for (let k = 0; k < patterns.length; k++) { + const patternLength = patterns[k].length; + const equalStart = (backward) ? (start - i - patternLength) : (start + i); + let equal = true; + for (let j = 0; j < patternLength; j++) { + if (this.view[j + equalStart] != patterns[k].view[j]) { + equal = false; + break; + } + } + if (equal) { + result = (backward) ? (start - i) : (start + i); + break; + } + } + if (result != (-1)) { + break; + } + } + return result; + } + prepareFindParameters(start = null, length = null, backward = false) { + if (start === null) { + start = (backward) ? this.length : 0; + } + if (start > this.length) { + start = this.length; + } + if (backward) { + if (length === null) { + length = start; + } + if (length > start) { + length = start; + } + } + else { + if (length === null) { + length = this.length - start; + } + if (length > (this.length - start)) { + length = this.length - start; + } + } + return { start, length, backward }; + } +} + +const pow2_24 = 16777216; +class SeqStream { + constructor(parameters = {}) { + this._stream = new ByteStream(); + this._length = 0; + this._start = 0; + this.backward = false; + this.appendBlock = 0; + this.prevLength = 0; + this.prevStart = 0; + if ("view" in parameters) { + this.stream = new ByteStream({ view: parameters.view }); + } + else if ("buffer" in parameters) { + this.stream = new ByteStream({ buffer: parameters.buffer }); + } + else if ("string" in parameters) { + this.stream = new ByteStream({ string: parameters.string }); + } + else if ("hexstring" in parameters) { + this.stream = new ByteStream({ hexstring: parameters.hexstring }); + } + else if ("stream" in parameters) { + this.stream = parameters.stream.slice(); + } + else { + this.stream = new ByteStream(); + } + if ("backward" in parameters && parameters.backward) { + this.backward = parameters.backward; + this._start = this.stream.length; + } + if ("length" in parameters && parameters.length > 0) { + this._length = parameters.length; + } + if ("start" in parameters && parameters.start && parameters.start > 0) { + this._start = parameters.start; + } + if ("appendBlock" in parameters && parameters.appendBlock && parameters.appendBlock > 0) { + this.appendBlock = parameters.appendBlock; + } + } + set stream(value) { + this._stream = value; + this.prevLength = this._length; + this._length = value.length; + this.prevStart = this._start; + this._start = 0; + } + get stream() { + return this._stream; + } + set length(value) { + this.prevLength = this._length; + this._length = value; + } + get length() { + if (this.appendBlock) { + return this.start; + } + return this._length; + } + set start(value) { + if (value > this.stream.length) + return; + this.prevStart = this._start; + this.prevLength = this._length; + this._length -= (this.backward) ? (this._start - value) : (value - this._start); + this._start = value; + } + get start() { + return this._start; + } + get buffer() { + return this._stream.buffer.slice(0, this._length); + } + resetPosition() { + this._start = this.prevStart; + this._length = this.prevLength; + } + findPattern(pattern, gap = null) { + if ((gap == null) || (gap > this.length)) { + gap = this.length; + } + const result = this.stream.findPattern(pattern, this.start, this.length, this.backward); + if (result == (-1)) + return result; + if (this.backward) { + if (result < (this.start - pattern.length - gap)) { + return (-1); + } + } + else { + if (result > (this.start + pattern.length + gap)) { + return (-1); + } + } + this.start = result; + return result; + } + findFirstIn(patterns, gap = null) { + if ((gap == null) || (gap > this.length)) { + gap = this.length; + } + const result = this.stream.findFirstIn(patterns, this.start, this.length, this.backward); + if (result.id == (-1)) + return result; + if (this.backward) { + if (result.position < (this.start - patterns[result.id].length - gap)) { + return { + id: (-1), + position: (this.backward) ? 0 : (this.start + this.length) + }; + } + } + else { + if (result.position > (this.start + patterns[result.id].length + gap)) { + return { + id: (-1), + position: (this.backward) ? 0 : (this.start + this.length) + }; + } + } + this.start = result.position; + return result; + } + findAllIn(patterns) { + const start = (this.backward) ? (this.start - this.length) : this.start; + return this.stream.findAllIn(patterns, start, this.length); + } + findFirstNotIn(patterns, gap = null) { + if ((gap == null) || (gap > this._length)) { + gap = this._length; + } + const result = this._stream.findFirstNotIn(patterns, this._start, this._length, this.backward); + if ((result.left.id == (-1)) && (result.right.id == (-1))) { + return result; + } + if (this.backward) { + if (result.right.id != (-1)) { + if (result.right.position < (this._start - patterns[result.right.id].length - gap)) { + return { + left: { + id: (-1), + position: this._start + }, + right: { + id: (-1), + position: 0 + }, + value: new ByteStream() + }; + } + } + } + else { + if (result.left.id != (-1)) { + if (result.left.position > (this._start + patterns[result.left.id].length + gap)) { + return { + left: { + id: (-1), + position: this._start + }, + right: { + id: (-1), + position: 0 + }, + value: new ByteStream() + }; + } + } + } + if (this.backward) { + if (result.left.id == (-1)) { + this.start = 0; + } + else { + this.start = result.left.position; + } + } + else { + if (result.right.id == (-1)) { + this.start = (this._start + this._length); + } + else { + this.start = result.right.position; + } + } + return result; + } + findAllNotIn(patterns) { + const start = (this.backward) ? (this._start - this._length) : this._start; + return this._stream.findAllNotIn(patterns, start, this._length); + } + findFirstSequence(patterns, length = null, gap = null) { + if ((length == null) || (length > this._length)) { + length = this._length; + } + if ((gap == null) || (gap > length)) { + gap = length; + } + const result = this._stream.findFirstSequence(patterns, this._start, length, this.backward); + if (result.value.length == 0) { + return result; + } + if (this.backward) { + if (result.position < (this._start - result.value.length - gap)) { + return { + position: (-1), + value: new ByteStream() + }; + } + } + else { + if (result.position > (this._start + result.value.length + gap)) { + return { + position: (-1), + value: new ByteStream() + }; + } + } + this.start = result.position; + return result; + } + findAllSequences(patterns) { + const start = (this.backward) ? (this.start - this.length) : this.start; + return this.stream.findAllSequences(patterns, start, this.length); + } + findPairedPatterns(leftPattern, rightPattern, gap = null) { + if ((gap == null) || (gap > this.length)) { + gap = this.length; + } + const start = (this.backward) ? (this.start - this.length) : this.start; + const result = this.stream.findPairedPatterns(leftPattern, rightPattern, start, this.length); + if (result.length) { + if (this.backward) { + if (result[0].right < (this.start - rightPattern.length - gap)) { + return []; + } + } + else { + if (result[0].left > (this.start + leftPattern.length + gap)) { + return []; + } + } + } + return result; + } + findPairedArrays(leftPatterns, rightPatterns, gap = null) { + if ((gap == null) || (gap > this.length)) { + gap = this.length; + } + const start = (this.backward) ? (this.start - this.length) : this.start; + const result = this.stream.findPairedArrays(leftPatterns, rightPatterns, start, this.length); + if (result.length) { + if (this.backward) { + if (result[0].right.position < (this.start - rightPatterns[result[0].right.id].length - gap)) { + return []; + } + } + else { + if (result[0].left.position > (this.start + leftPatterns[result[0].left.id].length + gap)) { + return []; + } + } + } + return result; + } + replacePattern(searchPattern, replacePattern) { + const start = (this.backward) ? (this.start - this.length) : this.start; + return this.stream.replacePattern(searchPattern, replacePattern, start, this.length); + } + skipPatterns(patterns) { + const result = this.stream.skipPatterns(patterns, this.start, this.length, this.backward); + this.start = result; + return result; + } + skipNotPatterns(patterns) { + const result = this.stream.skipNotPatterns(patterns, this.start, this.length, this.backward); + if (result == (-1)) + return (-1); + this.start = result; + return result; + } + append(stream) { + this.beforeAppend(stream.length); + this._stream.view.set(stream.view, this._start); + this._length += (stream.length * 2); + this.start = (this._start + stream.length); + this.prevLength -= (stream.length * 2); + } + appendView(view) { + this.beforeAppend(view.length); + this._stream.view.set(view, this._start); + this._length += (view.length * 2); + this.start = (this._start + view.length); + this.prevLength -= (view.length * 2); + } + appendChar(char) { + this.beforeAppend(1); + this._stream.view[this._start] = char; + this._length += 2; + this.start = (this._start + 1); + this.prevLength -= 2; + } + appendUint16(number) { + this.beforeAppend(2); + const value = new Uint16Array([number]); + const view = new Uint8Array(value.buffer); + this.stream.view[this._start] = view[1]; + this._stream.view[this._start + 1] = view[0]; + this._length += 4; + this.start = this._start + 2; + this.prevLength -= 4; + } + appendUint24(number) { + this.beforeAppend(3); + const value = new Uint32Array([number]); + const view = new Uint8Array(value.buffer); + this._stream.view[this._start] = view[2]; + this._stream.view[this._start + 1] = view[1]; + this._stream.view[this._start + 2] = view[0]; + this._length += 6; + this.start = (this._start + 3); + this.prevLength -= 6; + } + appendUint32(number) { + this.beforeAppend(4); + const value = new Uint32Array([number]); + const view = new Uint8Array(value.buffer); + this._stream.view[this._start] = view[3]; + this._stream.view[this._start + 1] = view[2]; + this._stream.view[this._start + 2] = view[1]; + this._stream.view[this._start + 3] = view[0]; + this._length += 8; + this.start = (this._start + 4); + this.prevLength -= 8; + } + appendInt16(number) { + this.beforeAppend(2); + const value = new Int16Array([number]); + const view = new Uint8Array(value.buffer); + this._stream.view[this._start] = view[1]; + this._stream.view[this._start + 1] = view[0]; + this._length += 4; + this.start = (this._start + 2); + this.prevLength -= 4; + } + appendInt32(number) { + this.beforeAppend(4); + const value = new Int32Array([number]); + const view = new Uint8Array(value.buffer); + this._stream.view[this._start] = view[3]; + this._stream.view[this._start + 1] = view[2]; + this._stream.view[this._start + 2] = view[1]; + this._stream.view[this._start + 3] = view[0]; + this._length += 8; + this.start = (this._start + 4); + this.prevLength -= 8; + } + getBlock(size, changeLength = true) { + if (this._length <= 0) { + return new Uint8Array(0); + } + if (this._length < size) { + size = this._length; + } + let result; + if (this.backward) { + const view = this._stream.view.subarray(this._length - size, this._length); + result = new Uint8Array(size); + for (let i = 0; i < size; i++) { + result[size - 1 - i] = view[i]; + } + } + else { + result = this._stream.view.subarray(this._start, this._start + size); + } + if (changeLength) { + this.start += ((this.backward) ? ((-1) * size) : size); + } + return result; + } + getUint16(changeLength = true) { + const block = this.getBlock(2, changeLength); + if (block.length < 2) + return 0; + return (block[0] << 8) | block[1]; + } + getInt16(changeLength = true) { + const num = this.getUint16(changeLength); + const negative = 0x8000; + if (num & negative) { + return -(negative - (num ^ negative)); + } + return num; + } + getUint24(changeLength = true) { + const block = this.getBlock(4, changeLength); + if (block.length < 3) + return 0; + return (block[0] << 16) | + (block[1] << 8) | + block[2]; + } + getUint32(changeLength = true) { + const block = this.getBlock(4, changeLength); + if (block.length < 4) + return 0; + return (block[0] * pow2_24) + + (block[1] << 16) + + (block[2] << 8) + + block[3]; + } + getInt32(changeLength = true) { + const num = this.getUint32(changeLength); + const negative = 0x80000000; + if (num & negative) { + return -(negative - (num ^ negative)); + } + return num; + } + beforeAppend(size) { + if ((this._start + size) > this._stream.length) { + if (size > this.appendBlock) { + this.appendBlock = size + SeqStream.APPEND_BLOCK; + } + this._stream.realloc(this._stream.length + this.appendBlock); + } + } +} +SeqStream.APPEND_BLOCK = 1000; + +// copied from utils +function isBytes(a) { + return (a instanceof Uint8Array || + (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')); +} +function bytes(b, ...lengths) { + if (!isBytes(b)) + throw new Error('Uint8Array expected'); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} + +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. +// node.js versions earlier than v19 don't declare it in global scope. +// For node.js, package.json#exports field mapping rewrites import +// from `crypto` to `cryptoNode`, which imports native module. +// Makes the utils un-importable in browsers without a bundler. +// Once node.js 18 is deprecated (2025-04-30), we can just drop the import. +// Cast array to view +const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +// The rotate right (circular right shift) operation for uint32 +const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); +// The rotate left (circular left shift) operation for uint32 +const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0); +new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; +/** + * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) + */ +function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Normalizes (non-hex) string or Uint8Array to Uint8Array. + * Warning: when Uint8Array is passed, it would NOT get copied. + * Keep in mind for future mutable operations. + */ +function toBytes(data) { + if (typeof data === 'string') + data = utf8ToBytes(data); + bytes(data); + return data; +} +// For runtime check if class implements interface +class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +} +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} + +// Polyfill for Safari 14 +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === 'function') + return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(0xffffffff); + const wh = Number((value >> _32n) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +// Choice: a ? b : c +const Chi = (a, b, c) => (a & b) ^ (~a & c); +// Majority function, true if any two inpust is true +const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + */ +class HashMD extends Hash { + constructor(blockLen, outputLen, padOffset, isLE) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input, cast it to view and process + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + this.buffer.subarray(pos).fill(0); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that + // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. + // So we just write lowest 64 bits of that value. + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen should be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } +} + +// SHA1 (RFC 3174) was cryptographically broken. It's still used. Don't use it for a new protocol. +// Initial state +const SHA1_IV = /* @__PURE__ */ new Uint32Array([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +let SHA1$1 = class SHA1 extends HashMD { + constructor() { + super(64, 20, 8, false); + this.A = SHA1_IV[0] | 0; + this.B = SHA1_IV[1] | 0; + this.C = SHA1_IV[2] | 0; + this.D = SHA1_IV[3] | 0; + this.E = SHA1_IV[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +const sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1$1()); + +// SHA2-256 need to try 2^128 hashes to execute birthday attack. +// BTC network is doing 2^67 hashes/sec as per early 2023. +// Round constants: +// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) +// prettier-ignore +const SHA256_K = /* @__PURE__ */ new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +// Initial state: +// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19 +// prettier-ignore +const SHA256_IV = /* @__PURE__ */ new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]); +// Temporary buffer, not used to store anything between runs +// Named this way because it matches specification. +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +let SHA256$1 = class SHA256 extends HashMD { + constructor() { + super(64, 32, 8, false); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +/** + * SHA2-256 hash function + * @param message - data that would be hashed + */ +const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256$1()); + +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// We are not using BigUint64Array, because they are extremely slow as per 2022 +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// for Shift in [0, 32) +const shrSH = (h, _l, s) => h >>> s; +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in [1, 32) +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// Right rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// Right rotate for shift===32 (just swaps l&h) +const rotr32H = (_h, l) => l; +const rotr32L = (h, _l) => h; +// Left rotate for Shift in [1, 32) +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// Left rotate for Shift in (32, 64), NOTE: 32 is special case. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// JS uses 32-bit signed integers for bitwise operations which means we cannot +// simple take carry out of low bit sum by shift, we need to use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; } -SeqStream.APPEND_BLOCK = 1000; - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -function __awaiter(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()); - }); -} +// Addition with more than 2 elements +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; -var _a; -class ECNamedCurves { - static register(name, id, size) { - this.namedCurves[name.toLowerCase()] = this.namedCurves[id] = { name, id, size }; - } - static find(nameOrId) { - return this.namedCurves[nameOrId.toLowerCase()] || null; - } -} -_a = ECNamedCurves; -ECNamedCurves.namedCurves = {}; -(() => { - _a.register("P-256", "1.2.840.10045.3.1.7", 32); - _a.register("P-384", "1.3.132.0.34", 48); - _a.register("P-521", "1.3.132.0.35", 66); - _a.register("brainpoolP256r1", "1.3.36.3.3.2.8.1.1.7", 32); - _a.register("brainpoolP384r1", "1.3.36.3.3.2.8.1.1.11", 48); - _a.register("brainpoolP512r1", "1.3.36.3.3.2.8.1.1.13", 64); +// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): +// prettier-ignore +const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +// Temporary buffer, not used to store anything between runs +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +let SHA512$1 = class SHA512 extends HashMD { + constructor() { + super(128, 64, 16, false); + // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. + // Also looks cleaner and easier to verify with spec. + // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0x6a09e667 | 0; + this.Al = 0xf3bcc908 | 0; + this.Bh = 0xbb67ae85 | 0; + this.Bl = 0x84caa73b | 0; + this.Ch = 0x3c6ef372 | 0; + this.Cl = 0xfe94f82b | 0; + this.Dh = 0xa54ff53a | 0; + this.Dl = 0x5f1d36f1 | 0; + this.Eh = 0x510e527f | 0; + this.El = 0xade682d1 | 0; + this.Fh = 0x9b05688c | 0; + this.Fl = 0x2b3e6c1f | 0; + this.Gh = 0x1f83d9ab | 0; + this.Gl = 0xfb41bd6b | 0; + this.Hh = 0x5be0cd19 | 0; + this.Hl = 0x137e2179 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +}; +let SHA384$1 = class SHA384 extends SHA512$1 { + constructor() { + super(); + // h -- high 32 bits, l -- low 32 bits + this.Ah = 0xcbbb9d5d | 0; + this.Al = 0xc1059ed8 | 0; + this.Bh = 0x629a292a | 0; + this.Bl = 0x367cd507 | 0; + this.Ch = 0x9159015a | 0; + this.Cl = 0x3070dd17 | 0; + this.Dh = 0x152fecd8 | 0; + this.Dl = 0xf70e5939 | 0; + this.Eh = 0x67332667 | 0; + this.El = 0xffc00b31 | 0; + this.Fh = 0x8eb44a87 | 0; + this.Fl = 0x68581511 | 0; + this.Gh = 0xdb0c2e0d | 0; + this.Gl = 0x64f98fa7 | 0; + this.Hh = 0x47b5481d | 0; + this.Hl = 0xbefa4fa4 | 0; + this.outputLen = 48; + } +}; +const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512$1()); +const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384$1()); + +var _a; +class ECNamedCurves { + static register(name, id, size) { + this.namedCurves[name.toLowerCase()] = this.namedCurves[id] = { name, id, size }; + } + static find(nameOrId) { + return this.namedCurves[nameOrId.toLowerCase()] || null; + } +} +_a = ECNamedCurves; +ECNamedCurves.namedCurves = {}; +(() => { + _a.register("P-256", "1.2.840.10045.3.1.7", 32); + _a.register("P-384", "1.3.132.0.34", 48); + _a.register("P-521", "1.3.132.0.35", 66); + _a.register("brainpoolP256r1", "1.3.36.3.3.2.8.1.1.7", 32); + _a.register("brainpoolP384r1", "1.3.36.3.3.2.8.1.1.11", 48); + _a.register("brainpoolP512r1", "1.3.36.3.3.2.8.1.1.13", 64); })(); -const X = "x"; -const Y = "y"; -const NAMED_CURVE$1 = "namedCurve"; -class ECPublicKey extends PkiObject { - constructor(parameters = {}) { - super(); - this.x = getParametersValue(parameters, X, ECPublicKey.defaultValues(X)); - this.y = getParametersValue(parameters, Y, ECPublicKey.defaultValues(Y)); - this.namedCurve = getParametersValue(parameters, NAMED_CURVE$1, ECPublicKey.defaultValues(NAMED_CURVE$1)); - if (parameters.json) { - this.fromJSON(parameters.json); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case X: - case Y: - return EMPTY_BUFFER; - case NAMED_CURVE$1: - return EMPTY_STRING; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case X: - case Y: - return memberValue instanceof ArrayBuffer && - (isEqualBuffer(memberValue, ECPublicKey.defaultValues(memberName))); - case NAMED_CURVE$1: - return typeof memberValue === "string" && - memberValue === ECPublicKey.defaultValues(memberName); - default: - return super.defaultValues(memberName); - } - } - static schema() { - return new RawData(); - } - fromSchema(schema1) { - const view = BufferSourceConverter.toUint8Array(schema1); - if (view[0] !== 0x04) { - throw new Error("Object's schema was not verified against input data for ECPublicKey"); - } - const namedCurve = ECNamedCurves.find(this.namedCurve); - if (!namedCurve) { - throw new Error(`Incorrect curve OID: ${this.namedCurve}`); - } - const coordinateLength = namedCurve.size; - if (view.byteLength !== (coordinateLength * 2 + 1)) { - throw new Error("Object's schema was not verified against input data for ECPublicKey"); - } - this.namedCurve = namedCurve.name; - this.x = view.slice(1, coordinateLength + 1).buffer; - this.y = view.slice(1 + coordinateLength, coordinateLength * 2 + 1).buffer; - } - toSchema() { - return new RawData({ - data: utilConcatBuf((new Uint8Array([0x04])).buffer, this.x, this.y) - }); - } - toJSON() { - const namedCurve = ECNamedCurves.find(this.namedCurve); - return { - crv: namedCurve ? namedCurve.name : this.namedCurve, - x: toBase64(arrayBufferToString(this.x), true, true, false), - y: toBase64(arrayBufferToString(this.y), true, true, false) - }; - } - fromJSON(json) { - ParameterError.assert("json", json, "crv", "x", "y"); - let coordinateLength = 0; - const namedCurve = ECNamedCurves.find(json.crv); - if (namedCurve) { - this.namedCurve = namedCurve.id; - coordinateLength = namedCurve.size; - } - const xConvertBuffer = stringToArrayBuffer(fromBase64(json.x, true)); - if (xConvertBuffer.byteLength < coordinateLength) { - this.x = new ArrayBuffer(coordinateLength); - const view = new Uint8Array(this.x); - const convertBufferView = new Uint8Array(xConvertBuffer); - view.set(convertBufferView, 1); - } - else { - this.x = xConvertBuffer.slice(0, coordinateLength); - } - const yConvertBuffer = stringToArrayBuffer(fromBase64(json.y, true)); - if (yConvertBuffer.byteLength < coordinateLength) { - this.y = new ArrayBuffer(coordinateLength); - const view = new Uint8Array(this.y); - const convertBufferView = new Uint8Array(yConvertBuffer); - view.set(convertBufferView, 1); - } - else { - this.y = yConvertBuffer.slice(0, coordinateLength); - } - } -} +const X = "x"; +const Y = "y"; +const NAMED_CURVE$1 = "namedCurve"; +class ECPublicKey extends PkiObject { + constructor(parameters = {}) { + super(); + this.x = getParametersValue(parameters, X, ECPublicKey.defaultValues(X)); + this.y = getParametersValue(parameters, Y, ECPublicKey.defaultValues(Y)); + this.namedCurve = getParametersValue(parameters, NAMED_CURVE$1, ECPublicKey.defaultValues(NAMED_CURVE$1)); + if (parameters.json) { + this.fromJSON(parameters.json); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case X: + case Y: + return EMPTY_BUFFER; + case NAMED_CURVE$1: + return EMPTY_STRING; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case X: + case Y: + return memberValue instanceof ArrayBuffer && + (isEqualBuffer(memberValue, ECPublicKey.defaultValues(memberName))); + case NAMED_CURVE$1: + return typeof memberValue === "string" && + memberValue === ECPublicKey.defaultValues(memberName); + default: + return super.defaultValues(memberName); + } + } + static schema() { + return new RawData(); + } + fromSchema(schema1) { + const view = BufferSourceConverter.toUint8Array(schema1); + if (view[0] !== 0x04) { + throw new Error("Object's schema was not verified against input data for ECPublicKey"); + } + const namedCurve = ECNamedCurves.find(this.namedCurve); + if (!namedCurve) { + throw new Error(`Incorrect curve OID: ${this.namedCurve}`); + } + const coordinateLength = namedCurve.size; + if (view.byteLength !== (coordinateLength * 2 + 1)) { + throw new Error("Object's schema was not verified against input data for ECPublicKey"); + } + this.namedCurve = namedCurve.name; + this.x = view.slice(1, coordinateLength + 1).buffer; + this.y = view.slice(1 + coordinateLength, coordinateLength * 2 + 1).buffer; + } + toSchema() { + return new RawData({ + data: utilConcatBuf((new Uint8Array([0x04])).buffer, this.x, this.y) + }); + } + toJSON() { + const namedCurve = ECNamedCurves.find(this.namedCurve); + return { + crv: namedCurve ? namedCurve.name : this.namedCurve, + x: toBase64(arrayBufferToString(this.x), true, true, false), + y: toBase64(arrayBufferToString(this.y), true, true, false) + }; + } + fromJSON(json) { + ParameterError.assert("json", json, "crv", "x", "y"); + let coordinateLength = 0; + const namedCurve = ECNamedCurves.find(json.crv); + if (namedCurve) { + this.namedCurve = namedCurve.id; + coordinateLength = namedCurve.size; + } + const xConvertBuffer = stringToArrayBuffer(fromBase64(json.x, true)); + if (xConvertBuffer.byteLength < coordinateLength) { + this.x = new ArrayBuffer(coordinateLength); + const view = new Uint8Array(this.x); + const convertBufferView = new Uint8Array(xConvertBuffer); + view.set(convertBufferView, 1); + } + else { + this.x = xConvertBuffer.slice(0, coordinateLength); + } + const yConvertBuffer = stringToArrayBuffer(fromBase64(json.y, true)); + if (yConvertBuffer.byteLength < coordinateLength) { + this.y = new ArrayBuffer(coordinateLength); + const view = new Uint8Array(this.y); + const convertBufferView = new Uint8Array(yConvertBuffer); + view.set(convertBufferView, 1); + } + else { + this.y = yConvertBuffer.slice(0, coordinateLength); + } + } +} ECPublicKey.CLASS_NAME = "ECPublicKey"; -const MODULUS$1 = "modulus"; -const PUBLIC_EXPONENT$1 = "publicExponent"; -const CLEAR_PROPS$1b = [MODULUS$1, PUBLIC_EXPONENT$1]; -class RSAPublicKey extends PkiObject { - constructor(parameters = {}) { - super(); - this.modulus = getParametersValue(parameters, MODULUS$1, RSAPublicKey.defaultValues(MODULUS$1)); - this.publicExponent = getParametersValue(parameters, PUBLIC_EXPONENT$1, RSAPublicKey.defaultValues(PUBLIC_EXPONENT$1)); - if (parameters.json) { - this.fromJSON(parameters.json); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case MODULUS$1: - return new Integer(); - case PUBLIC_EXPONENT$1: - return new Integer(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.modulus || EMPTY_STRING) }), - new Integer({ name: (names.publicExponent || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1b); - const asn1 = compareSchema(schema, schema, RSAPublicKey.schema({ - names: { - modulus: MODULUS$1, - publicExponent: PUBLIC_EXPONENT$1 - } - })); - AsnError.assertSchema(asn1, this.className); - this.modulus = asn1.result.modulus.convertFromDER(256); - this.publicExponent = asn1.result.publicExponent; - } - toSchema() { - return (new Sequence({ - value: [ - this.modulus.convertToDER(), - this.publicExponent - ] - })); - } - toJSON() { - return { - n: Convert.ToBase64Url(this.modulus.valueBlock.valueHexView), - e: Convert.ToBase64Url(this.publicExponent.valueBlock.valueHexView), - }; - } - fromJSON(json) { - ParameterError.assert("json", json, "n", "e"); - const array = stringToArrayBuffer(fromBase64(json.n, true)); - this.modulus = new Integer({ valueHex: array.slice(0, Math.pow(2, nearestPowerOf2(array.byteLength))) }); - this.publicExponent = new Integer({ valueHex: stringToArrayBuffer(fromBase64(json.e, true)).slice(0, 3) }); - } -} +const MODULUS$1 = "modulus"; +const PUBLIC_EXPONENT$1 = "publicExponent"; +const CLEAR_PROPS$1b = [MODULUS$1, PUBLIC_EXPONENT$1]; +class RSAPublicKey extends PkiObject { + constructor(parameters = {}) { + super(); + this.modulus = getParametersValue(parameters, MODULUS$1, RSAPublicKey.defaultValues(MODULUS$1)); + this.publicExponent = getParametersValue(parameters, PUBLIC_EXPONENT$1, RSAPublicKey.defaultValues(PUBLIC_EXPONENT$1)); + if (parameters.json) { + this.fromJSON(parameters.json); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case MODULUS$1: + return new Integer(); + case PUBLIC_EXPONENT$1: + return new Integer(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.modulus || EMPTY_STRING) }), + new Integer({ name: (names.publicExponent || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1b); + const asn1 = compareSchema(schema, schema, RSAPublicKey.schema({ + names: { + modulus: MODULUS$1, + publicExponent: PUBLIC_EXPONENT$1 + } + })); + AsnError.assertSchema(asn1, this.className); + this.modulus = asn1.result.modulus.convertFromDER(256); + this.publicExponent = asn1.result.publicExponent; + } + toSchema() { + return (new Sequence({ + value: [ + this.modulus.convertToDER(), + this.publicExponent + ] + })); + } + toJSON() { + return { + n: Convert.ToBase64Url(this.modulus.valueBlock.valueHexView), + e: Convert.ToBase64Url(this.publicExponent.valueBlock.valueHexView), + }; + } + fromJSON(json) { + ParameterError.assert("json", json, "n", "e"); + const array = stringToArrayBuffer(fromBase64(json.n, true)); + this.modulus = new Integer({ valueHex: array.slice(0, Math.pow(2, nearestPowerOf2(array.byteLength))) }); + this.publicExponent = new Integer({ valueHex: stringToArrayBuffer(fromBase64(json.e, true)).slice(0, 3) }); + } +} RSAPublicKey.CLASS_NAME = "RSAPublicKey"; -const ALGORITHM$1 = "algorithm"; -const SUBJECT_PUBLIC_KEY = "subjectPublicKey"; -const CLEAR_PROPS$1a = [ALGORITHM$1, SUBJECT_PUBLIC_KEY]; -class PublicKeyInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.algorithm = getParametersValue(parameters, ALGORITHM$1, PublicKeyInfo.defaultValues(ALGORITHM$1)); - this.subjectPublicKey = getParametersValue(parameters, SUBJECT_PUBLIC_KEY, PublicKeyInfo.defaultValues(SUBJECT_PUBLIC_KEY)); - const parsedKey = getParametersValue(parameters, "parsedKey", null); - if (parsedKey) { - this.parsedKey = parsedKey; - } - if (parameters.json) { - this.fromJSON(parameters.json); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - get parsedKey() { - if (this._parsedKey === undefined) { - switch (this.algorithm.algorithmId) { - case "1.2.840.10045.2.1": - if ("algorithmParams" in this.algorithm) { - if (this.algorithm.algorithmParams.constructor.blockName() === ObjectIdentifier.blockName()) { - try { - this._parsedKey = new ECPublicKey({ - namedCurve: this.algorithm.algorithmParams.valueBlock.toString(), - schema: this.subjectPublicKey.valueBlock.valueHexView - }); - } - catch (ex) { - } - } - } - break; - case "1.2.840.113549.1.1.1": - { - const publicKeyASN1 = fromBER(this.subjectPublicKey.valueBlock.valueHexView); - if (publicKeyASN1.offset !== -1) { - try { - this._parsedKey = new RSAPublicKey({ schema: publicKeyASN1.result }); - } - catch (ex) { - } - } - } - break; - } - this._parsedKey || (this._parsedKey = null); - } - return this._parsedKey || undefined; - } - set parsedKey(value) { - this._parsedKey = value; - } - static defaultValues(memberName) { - switch (memberName) { - case ALGORITHM$1: - return new AlgorithmIdentifier(); - case SUBJECT_PUBLIC_KEY: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.algorithm || {}), - new BitString({ name: (names.subjectPublicKey || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1a); - const asn1 = compareSchema(schema, schema, PublicKeyInfo.schema({ - names: { - algorithm: { - names: { - blockName: ALGORITHM$1 - } - }, - subjectPublicKey: SUBJECT_PUBLIC_KEY - } - })); - AsnError.assertSchema(asn1, this.className); - this.algorithm = new AlgorithmIdentifier({ schema: asn1.result.algorithm }); - this.subjectPublicKey = asn1.result.subjectPublicKey; - } - toSchema() { - return (new Sequence({ - value: [ - this.algorithm.toSchema(), - this.subjectPublicKey - ] - })); - } - toJSON() { - if (!this.parsedKey) { - return { - algorithm: this.algorithm.toJSON(), - subjectPublicKey: this.subjectPublicKey.toJSON(), - }; - } - const jwk = {}; - switch (this.algorithm.algorithmId) { - case "1.2.840.10045.2.1": - jwk.kty = "EC"; - break; - case "1.2.840.113549.1.1.1": - jwk.kty = "RSA"; - break; - } - const publicKeyJWK = this.parsedKey.toJSON(); - Object.assign(jwk, publicKeyJWK); - return jwk; - } - fromJSON(json) { - if ("kty" in json) { - switch (json.kty.toUpperCase()) { - case "EC": - this.parsedKey = new ECPublicKey({ json }); - this.algorithm = new AlgorithmIdentifier({ - algorithmId: "1.2.840.10045.2.1", - algorithmParams: new ObjectIdentifier({ value: this.parsedKey.namedCurve }) - }); - break; - case "RSA": - this.parsedKey = new RSAPublicKey({ json }); - this.algorithm = new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.1.1", - algorithmParams: new Null() - }); - break; - default: - throw new Error(`Invalid value for "kty" parameter: ${json.kty}`); - } - this.subjectPublicKey = new BitString({ valueHex: this.parsedKey.toSchema().toBER(false) }); - } - } - importKey(publicKey, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - try { - if (!publicKey) { - throw new Error("Need to provide publicKey input parameter"); - } - const exportedKey = yield crypto.exportKey("spki", publicKey); - const asn1 = fromBER(exportedKey); - try { - this.fromSchema(asn1.result); - } - catch (exception) { - throw new Error("Error during initializing object from schema"); - } - } - catch (e) { - const message = e instanceof Error ? e.message : `${e}`; - throw new Error(`Error during exporting public key: ${message}`); - } - }); - } -} +const ALGORITHM$1 = "algorithm"; +const SUBJECT_PUBLIC_KEY = "subjectPublicKey"; +const CLEAR_PROPS$1a = [ALGORITHM$1, SUBJECT_PUBLIC_KEY]; +class PublicKeyInfo extends PkiObject { + get parsedKey() { + if (this._parsedKey === undefined) { + switch (this.algorithm.algorithmId) { + case "1.2.840.10045.2.1": + if ("algorithmParams" in this.algorithm) { + if (this.algorithm.algorithmParams.constructor.blockName() === ObjectIdentifier.blockName()) { + try { + this._parsedKey = new ECPublicKey({ + namedCurve: this.algorithm.algorithmParams.valueBlock.toString(), + schema: this.subjectPublicKey.valueBlock.valueHexView + }); + } + catch { + } + } + } + break; + case "1.2.840.113549.1.1.1": + { + const publicKeyASN1 = fromBER(this.subjectPublicKey.valueBlock.valueHexView); + if (publicKeyASN1.offset !== -1) { + try { + this._parsedKey = new RSAPublicKey({ schema: publicKeyASN1.result }); + } + catch { + } + } + } + break; + } + this._parsedKey || (this._parsedKey = null); + } + return this._parsedKey || undefined; + } + set parsedKey(value) { + this._parsedKey = value; + } + constructor(parameters = {}) { + super(); + this.algorithm = getParametersValue(parameters, ALGORITHM$1, PublicKeyInfo.defaultValues(ALGORITHM$1)); + this.subjectPublicKey = getParametersValue(parameters, SUBJECT_PUBLIC_KEY, PublicKeyInfo.defaultValues(SUBJECT_PUBLIC_KEY)); + const parsedKey = getParametersValue(parameters, "parsedKey", null); + if (parsedKey) { + this.parsedKey = parsedKey; + } + if (parameters.json) { + this.fromJSON(parameters.json); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ALGORITHM$1: + return new AlgorithmIdentifier(); + case SUBJECT_PUBLIC_KEY: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.algorithm || {}), + new BitString({ name: (names.subjectPublicKey || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1a); + const asn1 = compareSchema(schema, schema, PublicKeyInfo.schema({ + names: { + algorithm: { + names: { + blockName: ALGORITHM$1 + } + }, + subjectPublicKey: SUBJECT_PUBLIC_KEY + } + })); + AsnError.assertSchema(asn1, this.className); + this.algorithm = new AlgorithmIdentifier({ schema: asn1.result.algorithm }); + this.subjectPublicKey = asn1.result.subjectPublicKey; + } + toSchema() { + return (new Sequence({ + value: [ + this.algorithm.toSchema(), + this.subjectPublicKey + ] + })); + } + toJSON() { + if (!this.parsedKey) { + return { + algorithm: this.algorithm.toJSON(), + subjectPublicKey: this.subjectPublicKey.toJSON(), + }; + } + const jwk = {}; + switch (this.algorithm.algorithmId) { + case "1.2.840.10045.2.1": + jwk.kty = "EC"; + break; + case "1.2.840.113549.1.1.1": + jwk.kty = "RSA"; + break; + } + const publicKeyJWK = this.parsedKey.toJSON(); + Object.assign(jwk, publicKeyJWK); + return jwk; + } + fromJSON(json) { + if ("kty" in json) { + switch (json.kty.toUpperCase()) { + case "EC": + this.parsedKey = new ECPublicKey({ json }); + this.algorithm = new AlgorithmIdentifier({ + algorithmId: "1.2.840.10045.2.1", + algorithmParams: new ObjectIdentifier({ value: this.parsedKey.namedCurve }) + }); + break; + case "RSA": + this.parsedKey = new RSAPublicKey({ json }); + this.algorithm = new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.1.1", + algorithmParams: new Null() + }); + break; + default: + throw new Error(`Invalid value for "kty" parameter: ${json.kty}`); + } + this.subjectPublicKey = new BitString({ valueHex: this.parsedKey.toSchema().toBER(false) }); + } + } + async importKey(publicKey, crypto = getCrypto(true)) { + try { + if (!publicKey) { + throw new Error("Need to provide publicKey input parameter"); + } + const exportedKey = await crypto.exportKey("spki", publicKey); + const asn1 = fromBER(exportedKey); + try { + this.fromSchema(asn1.result); + } + catch { + throw new Error("Error during initializing object from schema"); + } + } + catch (e) { + const message = e instanceof Error ? e.message : `${e}`; + throw new Error(`Error during exporting public key: ${message}`); + } + } +} PublicKeyInfo.CLASS_NAME = "PublicKeyInfo"; -const VERSION$l = "version"; -const PRIVATE_KEY$1 = "privateKey"; -const NAMED_CURVE = "namedCurve"; -const PUBLIC_KEY$1 = "publicKey"; -const CLEAR_PROPS$19 = [ - VERSION$l, - PRIVATE_KEY$1, - NAMED_CURVE, - PUBLIC_KEY$1 -]; -class ECPrivateKey extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$l, ECPrivateKey.defaultValues(VERSION$l)); - this.privateKey = getParametersValue(parameters, PRIVATE_KEY$1, ECPrivateKey.defaultValues(PRIVATE_KEY$1)); - if (NAMED_CURVE in parameters) { - this.namedCurve = getParametersValue(parameters, NAMED_CURVE, ECPrivateKey.defaultValues(NAMED_CURVE)); - } - if (PUBLIC_KEY$1 in parameters) { - this.publicKey = getParametersValue(parameters, PUBLIC_KEY$1, ECPrivateKey.defaultValues(PUBLIC_KEY$1)); - } - if (parameters.json) { - this.fromJSON(parameters.json); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$l: - return 1; - case PRIVATE_KEY$1: - return new OctetString(); - case NAMED_CURVE: - return EMPTY_STRING; - case PUBLIC_KEY$1: - return new ECPublicKey(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$l: - return (memberValue === ECPrivateKey.defaultValues(memberName)); - case PRIVATE_KEY$1: - return (memberValue.isEqual(ECPrivateKey.defaultValues(memberName))); - case NAMED_CURVE: - return (memberValue === EMPTY_STRING); - case PUBLIC_KEY$1: - return ((ECPublicKey.compareWithDefault(NAMED_CURVE, memberValue.namedCurve)) && - (ECPublicKey.compareWithDefault("x", memberValue.x)) && - (ECPublicKey.compareWithDefault("y", memberValue.y))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - new OctetString({ name: (names.privateKey || EMPTY_STRING) }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new ObjectIdentifier({ name: (names.namedCurve || EMPTY_STRING) }) - ] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new BitString({ name: (names.publicKey || EMPTY_STRING) }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$19); - const asn1 = compareSchema(schema, schema, ECPrivateKey.schema({ - names: { - version: VERSION$l, - privateKey: PRIVATE_KEY$1, - namedCurve: NAMED_CURVE, - publicKey: PUBLIC_KEY$1 - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.privateKey = asn1.result.privateKey; - if (NAMED_CURVE in asn1.result) { - this.namedCurve = asn1.result.namedCurve.valueBlock.toString(); - } - if (PUBLIC_KEY$1 in asn1.result) { - const publicKeyData = { schema: asn1.result.publicKey.valueBlock.valueHex }; - if (NAMED_CURVE in this) { - publicKeyData.namedCurve = this.namedCurve; - } - this.publicKey = new ECPublicKey(publicKeyData); - } - } - toSchema() { - const outputArray = [ - new Integer({ value: this.version }), - this.privateKey - ]; - if (this.namedCurve) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new ObjectIdentifier({ value: this.namedCurve }) - ] - })); - } - if (this.publicKey) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new BitString({ valueHex: this.publicKey.toSchema().toBER(false) }) - ] - })); - } - return new Sequence({ - value: outputArray - }); - } - toJSON() { - if (!this.namedCurve || ECPrivateKey.compareWithDefault(NAMED_CURVE, this.namedCurve)) { - throw new Error("Not enough information for making JSON: absent \"namedCurve\" value"); - } - const curve = ECNamedCurves.find(this.namedCurve); - const privateKeyJSON = { - crv: curve ? curve.name : this.namedCurve, - d: Convert.ToBase64Url(this.privateKey.valueBlock.valueHexView), - }; - if (this.publicKey) { - const publicKeyJSON = this.publicKey.toJSON(); - privateKeyJSON.x = publicKeyJSON.x; - privateKeyJSON.y = publicKeyJSON.y; - } - return privateKeyJSON; - } - fromJSON(json) { - ParameterError.assert("json", json, "crv", "d"); - let coordinateLength = 0; - const curve = ECNamedCurves.find(json.crv); - if (curve) { - this.namedCurve = curve.id; - coordinateLength = curve.size; - } - const convertBuffer = Convert.FromBase64Url(json.d); - if (convertBuffer.byteLength < coordinateLength) { - const buffer = new ArrayBuffer(coordinateLength); - const view = new Uint8Array(buffer); - const convertBufferView = new Uint8Array(convertBuffer); - view.set(convertBufferView, 1); - this.privateKey = new OctetString({ valueHex: buffer }); - } - else { - this.privateKey = new OctetString({ valueHex: convertBuffer.slice(0, coordinateLength) }); - } - if (json.x && json.y) { - this.publicKey = new ECPublicKey({ json }); - } - } -} -ECPrivateKey.CLASS_NAME = "ECPrivateKey"; - -const PRIME = "prime"; -const EXPONENT = "exponent"; -const COEFFICIENT$1 = "coefficient"; -const CLEAR_PROPS$18 = [ - PRIME, - EXPONENT, - COEFFICIENT$1, -]; -class OtherPrimeInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.prime = getParametersValue(parameters, PRIME, OtherPrimeInfo.defaultValues(PRIME)); - this.exponent = getParametersValue(parameters, EXPONENT, OtherPrimeInfo.defaultValues(EXPONENT)); - this.coefficient = getParametersValue(parameters, COEFFICIENT$1, OtherPrimeInfo.defaultValues(COEFFICIENT$1)); - if (parameters.json) { - this.fromJSON(parameters.json); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case PRIME: - return new Integer(); - case EXPONENT: - return new Integer(); - case COEFFICIENT$1: - return new Integer(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.prime || EMPTY_STRING) }), - new Integer({ name: (names.exponent || EMPTY_STRING) }), - new Integer({ name: (names.coefficient || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$18); - const asn1 = compareSchema(schema, schema, OtherPrimeInfo.schema({ - names: { - prime: PRIME, - exponent: EXPONENT, - coefficient: COEFFICIENT$1 - } - })); - AsnError.assertSchema(asn1, this.className); - this.prime = asn1.result.prime.convertFromDER(); - this.exponent = asn1.result.exponent.convertFromDER(); - this.coefficient = asn1.result.coefficient.convertFromDER(); - } - toSchema() { - return (new Sequence({ - value: [ - this.prime.convertToDER(), - this.exponent.convertToDER(), - this.coefficient.convertToDER() - ] - })); - } - toJSON() { - return { - r: Convert.ToBase64Url(this.prime.valueBlock.valueHexView), - d: Convert.ToBase64Url(this.exponent.valueBlock.valueHexView), - t: Convert.ToBase64Url(this.coefficient.valueBlock.valueHexView), - }; - } - fromJSON(json) { - ParameterError.assert("json", json, "r", "d", "r"); - this.prime = new Integer({ valueHex: Convert.FromBase64Url(json.r) }); - this.exponent = new Integer({ valueHex: Convert.FromBase64Url(json.d) }); - this.coefficient = new Integer({ valueHex: Convert.FromBase64Url(json.t) }); - } -} +const VERSION$l = "version"; +const PRIVATE_KEY$1 = "privateKey"; +const NAMED_CURVE = "namedCurve"; +const PUBLIC_KEY$1 = "publicKey"; +const CLEAR_PROPS$19 = [ + VERSION$l, + PRIVATE_KEY$1, + NAMED_CURVE, + PUBLIC_KEY$1 +]; +class ECPrivateKey extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$l, ECPrivateKey.defaultValues(VERSION$l)); + this.privateKey = getParametersValue(parameters, PRIVATE_KEY$1, ECPrivateKey.defaultValues(PRIVATE_KEY$1)); + if (NAMED_CURVE in parameters) { + this.namedCurve = getParametersValue(parameters, NAMED_CURVE, ECPrivateKey.defaultValues(NAMED_CURVE)); + } + if (PUBLIC_KEY$1 in parameters) { + this.publicKey = getParametersValue(parameters, PUBLIC_KEY$1, ECPrivateKey.defaultValues(PUBLIC_KEY$1)); + } + if (parameters.json) { + this.fromJSON(parameters.json); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$l: + return 1; + case PRIVATE_KEY$1: + return new OctetString(); + case NAMED_CURVE: + return EMPTY_STRING; + case PUBLIC_KEY$1: + return new ECPublicKey(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$l: + return (memberValue === ECPrivateKey.defaultValues(memberName)); + case PRIVATE_KEY$1: + return (memberValue.isEqual(ECPrivateKey.defaultValues(memberName))); + case NAMED_CURVE: + return (memberValue === EMPTY_STRING); + case PUBLIC_KEY$1: + return ((ECPublicKey.compareWithDefault(NAMED_CURVE, memberValue.namedCurve)) && + (ECPublicKey.compareWithDefault("x", memberValue.x)) && + (ECPublicKey.compareWithDefault("y", memberValue.y))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + new OctetString({ name: (names.privateKey || EMPTY_STRING) }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new ObjectIdentifier({ name: (names.namedCurve || EMPTY_STRING) }) + ] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new BitString({ name: (names.publicKey || EMPTY_STRING) }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$19); + const asn1 = compareSchema(schema, schema, ECPrivateKey.schema({ + names: { + version: VERSION$l, + privateKey: PRIVATE_KEY$1, + namedCurve: NAMED_CURVE, + publicKey: PUBLIC_KEY$1 + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.privateKey = asn1.result.privateKey; + if (NAMED_CURVE in asn1.result) { + this.namedCurve = asn1.result.namedCurve.valueBlock.toString(); + } + if (PUBLIC_KEY$1 in asn1.result) { + const publicKeyData = { schema: asn1.result.publicKey.valueBlock.valueHex }; + if (NAMED_CURVE in this) { + publicKeyData.namedCurve = this.namedCurve; + } + this.publicKey = new ECPublicKey(publicKeyData); + } + } + toSchema() { + const outputArray = [ + new Integer({ value: this.version }), + this.privateKey + ]; + if (this.namedCurve) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new ObjectIdentifier({ value: this.namedCurve }) + ] + })); + } + if (this.publicKey) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new BitString({ valueHex: this.publicKey.toSchema().toBER(false) }) + ] + })); + } + return new Sequence({ + value: outputArray + }); + } + toJSON() { + if (!this.namedCurve || ECPrivateKey.compareWithDefault(NAMED_CURVE, this.namedCurve)) { + throw new Error("Not enough information for making JSON: absent \"namedCurve\" value"); + } + const curve = ECNamedCurves.find(this.namedCurve); + const privateKeyJSON = { + crv: curve ? curve.name : this.namedCurve, + d: Convert.ToBase64Url(this.privateKey.valueBlock.valueHexView), + }; + if (this.publicKey) { + const publicKeyJSON = this.publicKey.toJSON(); + privateKeyJSON.x = publicKeyJSON.x; + privateKeyJSON.y = publicKeyJSON.y; + } + return privateKeyJSON; + } + fromJSON(json) { + ParameterError.assert("json", json, "crv", "d"); + let coordinateLength = 0; + const curve = ECNamedCurves.find(json.crv); + if (curve) { + this.namedCurve = curve.id; + coordinateLength = curve.size; + } + const convertBuffer = Convert.FromBase64Url(json.d); + if (convertBuffer.byteLength < coordinateLength) { + const buffer = new ArrayBuffer(coordinateLength); + const view = new Uint8Array(buffer); + const convertBufferView = new Uint8Array(convertBuffer); + view.set(convertBufferView, 1); + this.privateKey = new OctetString({ valueHex: buffer }); + } + else { + this.privateKey = new OctetString({ valueHex: convertBuffer.slice(0, coordinateLength) }); + } + if (json.x && json.y) { + this.publicKey = new ECPublicKey({ json }); + } + } +} +ECPrivateKey.CLASS_NAME = "ECPrivateKey"; + +const PRIME = "prime"; +const EXPONENT = "exponent"; +const COEFFICIENT$1 = "coefficient"; +const CLEAR_PROPS$18 = [ + PRIME, + EXPONENT, + COEFFICIENT$1, +]; +class OtherPrimeInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.prime = getParametersValue(parameters, PRIME, OtherPrimeInfo.defaultValues(PRIME)); + this.exponent = getParametersValue(parameters, EXPONENT, OtherPrimeInfo.defaultValues(EXPONENT)); + this.coefficient = getParametersValue(parameters, COEFFICIENT$1, OtherPrimeInfo.defaultValues(COEFFICIENT$1)); + if (parameters.json) { + this.fromJSON(parameters.json); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case PRIME: + return new Integer(); + case EXPONENT: + return new Integer(); + case COEFFICIENT$1: + return new Integer(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.prime || EMPTY_STRING) }), + new Integer({ name: (names.exponent || EMPTY_STRING) }), + new Integer({ name: (names.coefficient || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$18); + const asn1 = compareSchema(schema, schema, OtherPrimeInfo.schema({ + names: { + prime: PRIME, + exponent: EXPONENT, + coefficient: COEFFICIENT$1 + } + })); + AsnError.assertSchema(asn1, this.className); + this.prime = asn1.result.prime.convertFromDER(); + this.exponent = asn1.result.exponent.convertFromDER(); + this.coefficient = asn1.result.coefficient.convertFromDER(); + } + toSchema() { + return (new Sequence({ + value: [ + this.prime.convertToDER(), + this.exponent.convertToDER(), + this.coefficient.convertToDER() + ] + })); + } + toJSON() { + return { + r: Convert.ToBase64Url(this.prime.valueBlock.valueHexView), + d: Convert.ToBase64Url(this.exponent.valueBlock.valueHexView), + t: Convert.ToBase64Url(this.coefficient.valueBlock.valueHexView), + }; + } + fromJSON(json) { + ParameterError.assert("json", json, "r", "d", "r"); + this.prime = new Integer({ valueHex: Convert.FromBase64Url(json.r) }); + this.exponent = new Integer({ valueHex: Convert.FromBase64Url(json.d) }); + this.coefficient = new Integer({ valueHex: Convert.FromBase64Url(json.t) }); + } +} OtherPrimeInfo.CLASS_NAME = "OtherPrimeInfo"; -const VERSION$k = "version"; -const MODULUS = "modulus"; -const PUBLIC_EXPONENT = "publicExponent"; -const PRIVATE_EXPONENT = "privateExponent"; -const PRIME1 = "prime1"; -const PRIME2 = "prime2"; -const EXPONENT1 = "exponent1"; -const EXPONENT2 = "exponent2"; -const COEFFICIENT = "coefficient"; -const OTHER_PRIME_INFOS = "otherPrimeInfos"; -const CLEAR_PROPS$17 = [ - VERSION$k, - MODULUS, - PUBLIC_EXPONENT, - PRIVATE_EXPONENT, - PRIME1, - PRIME2, - EXPONENT1, - EXPONENT2, - COEFFICIENT, - OTHER_PRIME_INFOS -]; -class RSAPrivateKey extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$k, RSAPrivateKey.defaultValues(VERSION$k)); - this.modulus = getParametersValue(parameters, MODULUS, RSAPrivateKey.defaultValues(MODULUS)); - this.publicExponent = getParametersValue(parameters, PUBLIC_EXPONENT, RSAPrivateKey.defaultValues(PUBLIC_EXPONENT)); - this.privateExponent = getParametersValue(parameters, PRIVATE_EXPONENT, RSAPrivateKey.defaultValues(PRIVATE_EXPONENT)); - this.prime1 = getParametersValue(parameters, PRIME1, RSAPrivateKey.defaultValues(PRIME1)); - this.prime2 = getParametersValue(parameters, PRIME2, RSAPrivateKey.defaultValues(PRIME2)); - this.exponent1 = getParametersValue(parameters, EXPONENT1, RSAPrivateKey.defaultValues(EXPONENT1)); - this.exponent2 = getParametersValue(parameters, EXPONENT2, RSAPrivateKey.defaultValues(EXPONENT2)); - this.coefficient = getParametersValue(parameters, COEFFICIENT, RSAPrivateKey.defaultValues(COEFFICIENT)); - if (OTHER_PRIME_INFOS in parameters) { - this.otherPrimeInfos = getParametersValue(parameters, OTHER_PRIME_INFOS, RSAPrivateKey.defaultValues(OTHER_PRIME_INFOS)); - } - if (parameters.json) { - this.fromJSON(parameters.json); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$k: - return 0; - case MODULUS: - return new Integer(); - case PUBLIC_EXPONENT: - return new Integer(); - case PRIVATE_EXPONENT: - return new Integer(); - case PRIME1: - return new Integer(); - case PRIME2: - return new Integer(); - case EXPONENT1: - return new Integer(); - case EXPONENT2: - return new Integer(); - case COEFFICIENT: - return new Integer(); - case OTHER_PRIME_INFOS: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - new Integer({ name: (names.modulus || EMPTY_STRING) }), - new Integer({ name: (names.publicExponent || EMPTY_STRING) }), - new Integer({ name: (names.privateExponent || EMPTY_STRING) }), - new Integer({ name: (names.prime1 || EMPTY_STRING) }), - new Integer({ name: (names.prime2 || EMPTY_STRING) }), - new Integer({ name: (names.exponent1 || EMPTY_STRING) }), - new Integer({ name: (names.exponent2 || EMPTY_STRING) }), - new Integer({ name: (names.coefficient || EMPTY_STRING) }), - new Sequence({ - optional: true, - value: [ - new Repeated({ - name: (names.otherPrimeInfosName || EMPTY_STRING), - value: OtherPrimeInfo.schema(names.otherPrimeInfo || {}) - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$17); - const asn1 = compareSchema(schema, schema, RSAPrivateKey.schema({ - names: { - version: VERSION$k, - modulus: MODULUS, - publicExponent: PUBLIC_EXPONENT, - privateExponent: PRIVATE_EXPONENT, - prime1: PRIME1, - prime2: PRIME2, - exponent1: EXPONENT1, - exponent2: EXPONENT2, - coefficient: COEFFICIENT, - otherPrimeInfo: { - names: { - blockName: OTHER_PRIME_INFOS - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.modulus = asn1.result.modulus.convertFromDER(256); - this.publicExponent = asn1.result.publicExponent; - this.privateExponent = asn1.result.privateExponent.convertFromDER(256); - this.prime1 = asn1.result.prime1.convertFromDER(128); - this.prime2 = asn1.result.prime2.convertFromDER(128); - this.exponent1 = asn1.result.exponent1.convertFromDER(128); - this.exponent2 = asn1.result.exponent2.convertFromDER(128); - this.coefficient = asn1.result.coefficient.convertFromDER(128); - if (OTHER_PRIME_INFOS in asn1.result) - this.otherPrimeInfos = Array.from(asn1.result.otherPrimeInfos, element => new OtherPrimeInfo({ schema: element })); - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - outputArray.push(this.modulus.convertToDER()); - outputArray.push(this.publicExponent); - outputArray.push(this.privateExponent.convertToDER()); - outputArray.push(this.prime1.convertToDER()); - outputArray.push(this.prime2.convertToDER()); - outputArray.push(this.exponent1.convertToDER()); - outputArray.push(this.exponent2.convertToDER()); - outputArray.push(this.coefficient.convertToDER()); - if (this.otherPrimeInfos) { - outputArray.push(new Sequence({ - value: Array.from(this.otherPrimeInfos, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const jwk = { - n: Convert.ToBase64Url(this.modulus.valueBlock.valueHexView), - e: Convert.ToBase64Url(this.publicExponent.valueBlock.valueHexView), - d: Convert.ToBase64Url(this.privateExponent.valueBlock.valueHexView), - p: Convert.ToBase64Url(this.prime1.valueBlock.valueHexView), - q: Convert.ToBase64Url(this.prime2.valueBlock.valueHexView), - dp: Convert.ToBase64Url(this.exponent1.valueBlock.valueHexView), - dq: Convert.ToBase64Url(this.exponent2.valueBlock.valueHexView), - qi: Convert.ToBase64Url(this.coefficient.valueBlock.valueHexView), - }; - if (this.otherPrimeInfos) { - jwk.oth = Array.from(this.otherPrimeInfos, o => o.toJSON()); - } - return jwk; - } - fromJSON(json) { - ParameterError.assert("json", json, "n", "e", "d", "p", "q", "dp", "dq", "qi"); - this.modulus = new Integer({ valueHex: Convert.FromBase64Url(json.n) }); - this.publicExponent = new Integer({ valueHex: Convert.FromBase64Url(json.e) }); - this.privateExponent = new Integer({ valueHex: Convert.FromBase64Url(json.d) }); - this.prime1 = new Integer({ valueHex: Convert.FromBase64Url(json.p) }); - this.prime2 = new Integer({ valueHex: Convert.FromBase64Url(json.q) }); - this.exponent1 = new Integer({ valueHex: Convert.FromBase64Url(json.dp) }); - this.exponent2 = new Integer({ valueHex: Convert.FromBase64Url(json.dq) }); - this.coefficient = new Integer({ valueHex: Convert.FromBase64Url(json.qi) }); - if (json.oth) { - this.otherPrimeInfos = Array.from(json.oth, (element) => new OtherPrimeInfo({ json: element })); - } - } -} +const VERSION$k = "version"; +const MODULUS = "modulus"; +const PUBLIC_EXPONENT = "publicExponent"; +const PRIVATE_EXPONENT = "privateExponent"; +const PRIME1 = "prime1"; +const PRIME2 = "prime2"; +const EXPONENT1 = "exponent1"; +const EXPONENT2 = "exponent2"; +const COEFFICIENT = "coefficient"; +const OTHER_PRIME_INFOS = "otherPrimeInfos"; +const CLEAR_PROPS$17 = [ + VERSION$k, + MODULUS, + PUBLIC_EXPONENT, + PRIVATE_EXPONENT, + PRIME1, + PRIME2, + EXPONENT1, + EXPONENT2, + COEFFICIENT, + OTHER_PRIME_INFOS +]; +class RSAPrivateKey extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$k, RSAPrivateKey.defaultValues(VERSION$k)); + this.modulus = getParametersValue(parameters, MODULUS, RSAPrivateKey.defaultValues(MODULUS)); + this.publicExponent = getParametersValue(parameters, PUBLIC_EXPONENT, RSAPrivateKey.defaultValues(PUBLIC_EXPONENT)); + this.privateExponent = getParametersValue(parameters, PRIVATE_EXPONENT, RSAPrivateKey.defaultValues(PRIVATE_EXPONENT)); + this.prime1 = getParametersValue(parameters, PRIME1, RSAPrivateKey.defaultValues(PRIME1)); + this.prime2 = getParametersValue(parameters, PRIME2, RSAPrivateKey.defaultValues(PRIME2)); + this.exponent1 = getParametersValue(parameters, EXPONENT1, RSAPrivateKey.defaultValues(EXPONENT1)); + this.exponent2 = getParametersValue(parameters, EXPONENT2, RSAPrivateKey.defaultValues(EXPONENT2)); + this.coefficient = getParametersValue(parameters, COEFFICIENT, RSAPrivateKey.defaultValues(COEFFICIENT)); + if (OTHER_PRIME_INFOS in parameters) { + this.otherPrimeInfos = getParametersValue(parameters, OTHER_PRIME_INFOS, RSAPrivateKey.defaultValues(OTHER_PRIME_INFOS)); + } + if (parameters.json) { + this.fromJSON(parameters.json); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$k: + return 0; + case MODULUS: + return new Integer(); + case PUBLIC_EXPONENT: + return new Integer(); + case PRIVATE_EXPONENT: + return new Integer(); + case PRIME1: + return new Integer(); + case PRIME2: + return new Integer(); + case EXPONENT1: + return new Integer(); + case EXPONENT2: + return new Integer(); + case COEFFICIENT: + return new Integer(); + case OTHER_PRIME_INFOS: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + new Integer({ name: (names.modulus || EMPTY_STRING) }), + new Integer({ name: (names.publicExponent || EMPTY_STRING) }), + new Integer({ name: (names.privateExponent || EMPTY_STRING) }), + new Integer({ name: (names.prime1 || EMPTY_STRING) }), + new Integer({ name: (names.prime2 || EMPTY_STRING) }), + new Integer({ name: (names.exponent1 || EMPTY_STRING) }), + new Integer({ name: (names.exponent2 || EMPTY_STRING) }), + new Integer({ name: (names.coefficient || EMPTY_STRING) }), + new Sequence({ + optional: true, + value: [ + new Repeated({ + name: (names.otherPrimeInfosName || EMPTY_STRING), + value: OtherPrimeInfo.schema(names.otherPrimeInfo || {}) + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$17); + const asn1 = compareSchema(schema, schema, RSAPrivateKey.schema({ + names: { + version: VERSION$k, + modulus: MODULUS, + publicExponent: PUBLIC_EXPONENT, + privateExponent: PRIVATE_EXPONENT, + prime1: PRIME1, + prime2: PRIME2, + exponent1: EXPONENT1, + exponent2: EXPONENT2, + coefficient: COEFFICIENT, + otherPrimeInfo: { + names: { + blockName: OTHER_PRIME_INFOS + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.modulus = asn1.result.modulus.convertFromDER(256); + this.publicExponent = asn1.result.publicExponent; + this.privateExponent = asn1.result.privateExponent.convertFromDER(256); + this.prime1 = asn1.result.prime1.convertFromDER(128); + this.prime2 = asn1.result.prime2.convertFromDER(128); + this.exponent1 = asn1.result.exponent1.convertFromDER(128); + this.exponent2 = asn1.result.exponent2.convertFromDER(128); + this.coefficient = asn1.result.coefficient.convertFromDER(128); + if (OTHER_PRIME_INFOS in asn1.result) + this.otherPrimeInfos = Array.from(asn1.result.otherPrimeInfos, element => new OtherPrimeInfo({ schema: element })); + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + outputArray.push(this.modulus.convertToDER()); + outputArray.push(this.publicExponent); + outputArray.push(this.privateExponent.convertToDER()); + outputArray.push(this.prime1.convertToDER()); + outputArray.push(this.prime2.convertToDER()); + outputArray.push(this.exponent1.convertToDER()); + outputArray.push(this.exponent2.convertToDER()); + outputArray.push(this.coefficient.convertToDER()); + if (this.otherPrimeInfos) { + outputArray.push(new Sequence({ + value: Array.from(this.otherPrimeInfos, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const jwk = { + n: Convert.ToBase64Url(this.modulus.valueBlock.valueHexView), + e: Convert.ToBase64Url(this.publicExponent.valueBlock.valueHexView), + d: Convert.ToBase64Url(this.privateExponent.valueBlock.valueHexView), + p: Convert.ToBase64Url(this.prime1.valueBlock.valueHexView), + q: Convert.ToBase64Url(this.prime2.valueBlock.valueHexView), + dp: Convert.ToBase64Url(this.exponent1.valueBlock.valueHexView), + dq: Convert.ToBase64Url(this.exponent2.valueBlock.valueHexView), + qi: Convert.ToBase64Url(this.coefficient.valueBlock.valueHexView), + }; + if (this.otherPrimeInfos) { + jwk.oth = Array.from(this.otherPrimeInfos, o => o.toJSON()); + } + return jwk; + } + fromJSON(json) { + ParameterError.assert("json", json, "n", "e", "d", "p", "q", "dp", "dq", "qi"); + this.modulus = new Integer({ valueHex: Convert.FromBase64Url(json.n) }); + this.publicExponent = new Integer({ valueHex: Convert.FromBase64Url(json.e) }); + this.privateExponent = new Integer({ valueHex: Convert.FromBase64Url(json.d) }); + this.prime1 = new Integer({ valueHex: Convert.FromBase64Url(json.p) }); + this.prime2 = new Integer({ valueHex: Convert.FromBase64Url(json.q) }); + this.exponent1 = new Integer({ valueHex: Convert.FromBase64Url(json.dp) }); + this.exponent2 = new Integer({ valueHex: Convert.FromBase64Url(json.dq) }); + this.coefficient = new Integer({ valueHex: Convert.FromBase64Url(json.qi) }); + if (json.oth) { + this.otherPrimeInfos = Array.from(json.oth, (element) => new OtherPrimeInfo({ json: element })); + } + } +} RSAPrivateKey.CLASS_NAME = "RSAPrivateKey"; -const VERSION$j = "version"; -const PRIVATE_KEY_ALGORITHM = "privateKeyAlgorithm"; -const PRIVATE_KEY = "privateKey"; -const ATTRIBUTES$5 = "attributes"; -const PARSED_KEY = "parsedKey"; -const CLEAR_PROPS$16 = [ - VERSION$j, - PRIVATE_KEY_ALGORITHM, - PRIVATE_KEY, - ATTRIBUTES$5 -]; -class PrivateKeyInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$j, PrivateKeyInfo.defaultValues(VERSION$j)); - this.privateKeyAlgorithm = getParametersValue(parameters, PRIVATE_KEY_ALGORITHM, PrivateKeyInfo.defaultValues(PRIVATE_KEY_ALGORITHM)); - this.privateKey = getParametersValue(parameters, PRIVATE_KEY, PrivateKeyInfo.defaultValues(PRIVATE_KEY)); - if (ATTRIBUTES$5 in parameters) { - this.attributes = getParametersValue(parameters, ATTRIBUTES$5, PrivateKeyInfo.defaultValues(ATTRIBUTES$5)); - } - if (PARSED_KEY in parameters) { - this.parsedKey = getParametersValue(parameters, PARSED_KEY, PrivateKeyInfo.defaultValues(PARSED_KEY)); - } - if (parameters.json) { - this.fromJSON(parameters.json); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$j: - return 0; - case PRIVATE_KEY_ALGORITHM: - return new AlgorithmIdentifier(); - case PRIVATE_KEY: - return new OctetString(); - case ATTRIBUTES$5: - return []; - case PARSED_KEY: - return {}; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - AlgorithmIdentifier.schema(names.privateKeyAlgorithm || {}), - new OctetString({ name: (names.privateKey || EMPTY_STRING) }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Repeated({ - name: (names.attributes || EMPTY_STRING), - value: Attribute.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$16); - const asn1 = compareSchema(schema, schema, PrivateKeyInfo.schema({ - names: { - version: VERSION$j, - privateKeyAlgorithm: { - names: { - blockName: PRIVATE_KEY_ALGORITHM - } - }, - privateKey: PRIVATE_KEY, - attributes: ATTRIBUTES$5 - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.privateKeyAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.privateKeyAlgorithm }); - this.privateKey = asn1.result.privateKey; - if (ATTRIBUTES$5 in asn1.result) - this.attributes = Array.from(asn1.result.attributes, element => new Attribute({ schema: element })); - switch (this.privateKeyAlgorithm.algorithmId) { - case "1.2.840.113549.1.1.1": - { - const privateKeyASN1 = fromBER(this.privateKey.valueBlock.valueHexView); - if (privateKeyASN1.offset !== -1) - this.parsedKey = new RSAPrivateKey({ schema: privateKeyASN1.result }); - } - break; - case "1.2.840.10045.2.1": - if ("algorithmParams" in this.privateKeyAlgorithm) { - if (this.privateKeyAlgorithm.algorithmParams instanceof ObjectIdentifier) { - const privateKeyASN1 = fromBER(this.privateKey.valueBlock.valueHexView); - if (privateKeyASN1.offset !== -1) { - this.parsedKey = new ECPrivateKey({ - namedCurve: this.privateKeyAlgorithm.algorithmParams.valueBlock.toString(), - schema: privateKeyASN1.result - }); - } - } - } - break; - } - } - toSchema() { - const outputArray = [ - new Integer({ value: this.version }), - this.privateKeyAlgorithm.toSchema(), - this.privateKey - ]; - if (this.attributes) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: Array.from(this.attributes, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - if (!this.parsedKey) { - const object = { - version: this.version, - privateKeyAlgorithm: this.privateKeyAlgorithm.toJSON(), - privateKey: this.privateKey.toJSON(), - }; - if (this.attributes) { - object.attributes = Array.from(this.attributes, o => o.toJSON()); - } - return object; - } - const jwk = {}; - switch (this.privateKeyAlgorithm.algorithmId) { - case "1.2.840.10045.2.1": - jwk.kty = "EC"; - break; - case "1.2.840.113549.1.1.1": - jwk.kty = "RSA"; - break; - } - const publicKeyJWK = this.parsedKey.toJSON(); - Object.assign(jwk, publicKeyJWK); - return jwk; - } - fromJSON(json) { - if ("kty" in json) { - switch (json.kty.toUpperCase()) { - case "EC": - this.parsedKey = new ECPrivateKey({ json }); - this.privateKeyAlgorithm = new AlgorithmIdentifier({ - algorithmId: "1.2.840.10045.2.1", - algorithmParams: new ObjectIdentifier({ value: this.parsedKey.namedCurve }) - }); - break; - case "RSA": - this.parsedKey = new RSAPrivateKey({ json }); - this.privateKeyAlgorithm = new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.1.1", - algorithmParams: new Null() - }); - break; - default: - throw new Error(`Invalid value for "kty" parameter: ${json.kty}`); - } - this.privateKey = new OctetString({ valueHex: this.parsedKey.toSchema().toBER(false) }); - } - } -} +const VERSION$j = "version"; +const PRIVATE_KEY_ALGORITHM = "privateKeyAlgorithm"; +const PRIVATE_KEY = "privateKey"; +const ATTRIBUTES$5 = "attributes"; +const PARSED_KEY = "parsedKey"; +const CLEAR_PROPS$16 = [ + VERSION$j, + PRIVATE_KEY_ALGORITHM, + PRIVATE_KEY, + ATTRIBUTES$5 +]; +class PrivateKeyInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$j, PrivateKeyInfo.defaultValues(VERSION$j)); + this.privateKeyAlgorithm = getParametersValue(parameters, PRIVATE_KEY_ALGORITHM, PrivateKeyInfo.defaultValues(PRIVATE_KEY_ALGORITHM)); + this.privateKey = getParametersValue(parameters, PRIVATE_KEY, PrivateKeyInfo.defaultValues(PRIVATE_KEY)); + if (ATTRIBUTES$5 in parameters) { + this.attributes = getParametersValue(parameters, ATTRIBUTES$5, PrivateKeyInfo.defaultValues(ATTRIBUTES$5)); + } + if (PARSED_KEY in parameters) { + this.parsedKey = getParametersValue(parameters, PARSED_KEY, PrivateKeyInfo.defaultValues(PARSED_KEY)); + } + if (parameters.json) { + this.fromJSON(parameters.json); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$j: + return 0; + case PRIVATE_KEY_ALGORITHM: + return new AlgorithmIdentifier(); + case PRIVATE_KEY: + return new OctetString(); + case ATTRIBUTES$5: + return []; + case PARSED_KEY: + return {}; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + AlgorithmIdentifier.schema(names.privateKeyAlgorithm || {}), + new OctetString({ name: (names.privateKey || EMPTY_STRING) }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Repeated({ + name: (names.attributes || EMPTY_STRING), + value: Attribute.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$16); + const asn1 = compareSchema(schema, schema, PrivateKeyInfo.schema({ + names: { + version: VERSION$j, + privateKeyAlgorithm: { + names: { + blockName: PRIVATE_KEY_ALGORITHM + } + }, + privateKey: PRIVATE_KEY, + attributes: ATTRIBUTES$5 + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.privateKeyAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.privateKeyAlgorithm }); + this.privateKey = asn1.result.privateKey; + if (ATTRIBUTES$5 in asn1.result) + this.attributes = Array.from(asn1.result.attributes, element => new Attribute({ schema: element })); + switch (this.privateKeyAlgorithm.algorithmId) { + case "1.2.840.113549.1.1.1": + { + const privateKeyASN1 = fromBER(this.privateKey.valueBlock.valueHexView); + if (privateKeyASN1.offset !== -1) + this.parsedKey = new RSAPrivateKey({ schema: privateKeyASN1.result }); + } + break; + case "1.2.840.10045.2.1": + if ("algorithmParams" in this.privateKeyAlgorithm) { + if (this.privateKeyAlgorithm.algorithmParams instanceof ObjectIdentifier) { + const privateKeyASN1 = fromBER(this.privateKey.valueBlock.valueHexView); + if (privateKeyASN1.offset !== -1) { + this.parsedKey = new ECPrivateKey({ + namedCurve: this.privateKeyAlgorithm.algorithmParams.valueBlock.toString(), + schema: privateKeyASN1.result + }); + } + } + } + break; + } + } + toSchema() { + const outputArray = [ + new Integer({ value: this.version }), + this.privateKeyAlgorithm.toSchema(), + this.privateKey + ]; + if (this.attributes) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: Array.from(this.attributes, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + if (!this.parsedKey) { + const object = { + version: this.version, + privateKeyAlgorithm: this.privateKeyAlgorithm.toJSON(), + privateKey: this.privateKey.toJSON(), + }; + if (this.attributes) { + object.attributes = Array.from(this.attributes, o => o.toJSON()); + } + return object; + } + const jwk = {}; + switch (this.privateKeyAlgorithm.algorithmId) { + case "1.2.840.10045.2.1": + jwk.kty = "EC"; + break; + case "1.2.840.113549.1.1.1": + jwk.kty = "RSA"; + break; + } + const publicKeyJWK = this.parsedKey.toJSON(); + Object.assign(jwk, publicKeyJWK); + return jwk; + } + fromJSON(json) { + if ("kty" in json) { + switch (json.kty.toUpperCase()) { + case "EC": + this.parsedKey = new ECPrivateKey({ json }); + this.privateKeyAlgorithm = new AlgorithmIdentifier({ + algorithmId: "1.2.840.10045.2.1", + algorithmParams: new ObjectIdentifier({ value: this.parsedKey.namedCurve }) + }); + break; + case "RSA": + this.parsedKey = new RSAPrivateKey({ json }); + this.privateKeyAlgorithm = new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.1.1", + algorithmParams: new Null() + }); + break; + default: + throw new Error(`Invalid value for "kty" parameter: ${json.kty}`); + } + this.privateKey = new OctetString({ valueHex: this.parsedKey.toSchema().toBER(false) }); + } + } +} PrivateKeyInfo.CLASS_NAME = "PrivateKeyInfo"; -const CONTENT_TYPE$1 = "contentType"; -const CONTENT_ENCRYPTION_ALGORITHM = "contentEncryptionAlgorithm"; -const ENCRYPTED_CONTENT = "encryptedContent"; -const CLEAR_PROPS$15 = [ - CONTENT_TYPE$1, - CONTENT_ENCRYPTION_ALGORITHM, - ENCRYPTED_CONTENT, -]; -class EncryptedContentInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.contentType = getParametersValue(parameters, CONTENT_TYPE$1, EncryptedContentInfo.defaultValues(CONTENT_TYPE$1)); - this.contentEncryptionAlgorithm = getParametersValue(parameters, CONTENT_ENCRYPTION_ALGORITHM, EncryptedContentInfo.defaultValues(CONTENT_ENCRYPTION_ALGORITHM)); - if (ENCRYPTED_CONTENT in parameters && parameters.encryptedContent) { - this.encryptedContent = parameters.encryptedContent; - if ((this.encryptedContent.idBlock.tagClass === 1) && - (this.encryptedContent.idBlock.tagNumber === 4)) { - if (this.encryptedContent.idBlock.isConstructed === false) { - const constrString = new OctetString({ - idBlock: { isConstructed: true }, - isConstructed: true - }); - let offset = 0; - const valueHex = this.encryptedContent.valueBlock.valueHexView.slice().buffer; - let length = valueHex.byteLength; - const pieceSize = 1024; - while (length > 0) { - const pieceView = new Uint8Array(valueHex, offset, ((offset + pieceSize) > valueHex.byteLength) ? (valueHex.byteLength - offset) : pieceSize); - const _array = new ArrayBuffer(pieceView.length); - const _view = new Uint8Array(_array); - for (let i = 0; i < _view.length; i++) - _view[i] = pieceView[i]; - constrString.valueBlock.value.push(new OctetString({ valueHex: _array })); - length -= pieceView.length; - offset += pieceView.length; - } - this.encryptedContent = constrString; - } - } - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CONTENT_TYPE$1: - return EMPTY_STRING; - case CONTENT_ENCRYPTION_ALGORITHM: - return new AlgorithmIdentifier(); - case ENCRYPTED_CONTENT: - return new OctetString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case CONTENT_TYPE$1: - return (memberValue === EMPTY_STRING); - case CONTENT_ENCRYPTION_ALGORITHM: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case ENCRYPTED_CONTENT: - return (memberValue.isEqual(EncryptedContentInfo.defaultValues(ENCRYPTED_CONTENT))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.contentType || EMPTY_STRING) }), - AlgorithmIdentifier.schema(names.contentEncryptionAlgorithm || {}), - new Choice({ - value: [ - new Constructed({ - name: (names.encryptedContent || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Repeated({ - value: new OctetString() - }) - ] - }), - new Primitive({ - name: (names.encryptedContent || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - } - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$15); - const asn1 = compareSchema(schema, schema, EncryptedContentInfo.schema({ - names: { - contentType: CONTENT_TYPE$1, - contentEncryptionAlgorithm: { - names: { - blockName: CONTENT_ENCRYPTION_ALGORITHM - } - }, - encryptedContent: ENCRYPTED_CONTENT - } - })); - AsnError.assertSchema(asn1, this.className); - this.contentType = asn1.result.contentType.valueBlock.toString(); - this.contentEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.contentEncryptionAlgorithm }); - if (ENCRYPTED_CONTENT in asn1.result) { - this.encryptedContent = asn1.result.encryptedContent; - this.encryptedContent.idBlock.tagClass = 1; - this.encryptedContent.idBlock.tagNumber = 4; - } - } - toSchema() { - const sequenceLengthBlock = { - isIndefiniteForm: false - }; - const outputArray = []; - outputArray.push(new ObjectIdentifier({ value: this.contentType })); - outputArray.push(this.contentEncryptionAlgorithm.toSchema()); - if (this.encryptedContent) { - sequenceLengthBlock.isIndefiniteForm = this.encryptedContent.idBlock.isConstructed; - const encryptedValue = this.encryptedContent; - encryptedValue.idBlock.tagClass = 3; - encryptedValue.idBlock.tagNumber = 0; - encryptedValue.lenBlock.isIndefiniteForm = this.encryptedContent.idBlock.isConstructed; - outputArray.push(encryptedValue); - } - return (new Sequence({ - lenBlock: sequenceLengthBlock, - value: outputArray - })); - } - toJSON() { - const res = { - contentType: this.contentType, - contentEncryptionAlgorithm: this.contentEncryptionAlgorithm.toJSON() - }; - if (this.encryptedContent) { - res.encryptedContent = this.encryptedContent.toJSON(); - } - return res; - } - getEncryptedContent() { - if (!this.encryptedContent) { - throw new Error("Parameter 'encryptedContent' is undefined"); - } - return OctetString.prototype.getValue.call(this.encryptedContent); - } -} +const CONTENT_TYPE$1 = "contentType"; +const CONTENT_ENCRYPTION_ALGORITHM = "contentEncryptionAlgorithm"; +const ENCRYPTED_CONTENT = "encryptedContent"; +const CLEAR_PROPS$15 = [ + CONTENT_TYPE$1, + CONTENT_ENCRYPTION_ALGORITHM, + ENCRYPTED_CONTENT, +]; +const PIECE_SIZE = 1024; +class EncryptedContentInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.contentType = getParametersValue(parameters, CONTENT_TYPE$1, EncryptedContentInfo.defaultValues(CONTENT_TYPE$1)); + this.contentEncryptionAlgorithm = getParametersValue(parameters, CONTENT_ENCRYPTION_ALGORITHM, EncryptedContentInfo.defaultValues(CONTENT_ENCRYPTION_ALGORITHM)); + if (ENCRYPTED_CONTENT in parameters && parameters.encryptedContent) { + this.encryptedContent = parameters.encryptedContent; + if ((this.encryptedContent.idBlock.tagClass === 1) && + (this.encryptedContent.idBlock.tagNumber === 4)) { + if (this.encryptedContent.idBlock.isConstructed === false && !parameters.disableSplit) { + const constrString = new OctetString({ + idBlock: { isConstructed: true }, + isConstructed: true + }); + let offset = 0; + const valueHex = this.encryptedContent.valueBlock.valueHexView.slice().buffer; + let length = valueHex.byteLength; + while (length > 0) { + const pieceView = new Uint8Array(valueHex, offset, ((offset + PIECE_SIZE) > valueHex.byteLength) ? (valueHex.byteLength - offset) : PIECE_SIZE); + const _array = new ArrayBuffer(pieceView.length); + const _view = new Uint8Array(_array); + for (let i = 0; i < _view.length; i++) + _view[i] = pieceView[i]; + constrString.valueBlock.value.push(new OctetString({ valueHex: _array })); + length -= pieceView.length; + offset += pieceView.length; + } + this.encryptedContent = constrString; + } + } + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CONTENT_TYPE$1: + return EMPTY_STRING; + case CONTENT_ENCRYPTION_ALGORITHM: + return new AlgorithmIdentifier(); + case ENCRYPTED_CONTENT: + return new OctetString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case CONTENT_TYPE$1: + return (memberValue === EMPTY_STRING); + case CONTENT_ENCRYPTION_ALGORITHM: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case ENCRYPTED_CONTENT: + return (memberValue.isEqual(EncryptedContentInfo.defaultValues(ENCRYPTED_CONTENT))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.contentType || EMPTY_STRING) }), + AlgorithmIdentifier.schema(names.contentEncryptionAlgorithm || {}), + new Choice({ + value: [ + new Constructed({ + name: (names.encryptedContent || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Repeated({ + value: new OctetString() + }) + ] + }), + new Primitive({ + name: (names.encryptedContent || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + } + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$15); + const asn1 = compareSchema(schema, schema, EncryptedContentInfo.schema({ + names: { + contentType: CONTENT_TYPE$1, + contentEncryptionAlgorithm: { + names: { + blockName: CONTENT_ENCRYPTION_ALGORITHM + } + }, + encryptedContent: ENCRYPTED_CONTENT + } + })); + AsnError.assertSchema(asn1, this.className); + this.contentType = asn1.result.contentType.valueBlock.toString(); + this.contentEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.contentEncryptionAlgorithm }); + if (ENCRYPTED_CONTENT in asn1.result) { + this.encryptedContent = asn1.result.encryptedContent; + this.encryptedContent.idBlock.tagClass = 1; + this.encryptedContent.idBlock.tagNumber = 4; + } + } + toSchema() { + const sequenceLengthBlock = { + isIndefiniteForm: false + }; + const outputArray = []; + outputArray.push(new ObjectIdentifier({ value: this.contentType })); + outputArray.push(this.contentEncryptionAlgorithm.toSchema()); + if (this.encryptedContent) { + sequenceLengthBlock.isIndefiniteForm = this.encryptedContent.idBlock.isConstructed; + const encryptedValue = this.encryptedContent; + encryptedValue.idBlock.tagClass = 3; + encryptedValue.idBlock.tagNumber = 0; + encryptedValue.lenBlock.isIndefiniteForm = this.encryptedContent.idBlock.isConstructed; + outputArray.push(encryptedValue); + } + return (new Sequence({ + lenBlock: sequenceLengthBlock, + value: outputArray + })); + } + toJSON() { + const res = { + contentType: this.contentType, + contentEncryptionAlgorithm: this.contentEncryptionAlgorithm.toJSON() + }; + if (this.encryptedContent) { + res.encryptedContent = this.encryptedContent.toJSON(); + } + return res; + } + getEncryptedContent() { + if (!this.encryptedContent) { + throw new Error("Parameter 'encryptedContent' is undefined"); + } + return OctetString.prototype.getValue.call(this.encryptedContent); + } +} EncryptedContentInfo.CLASS_NAME = "EncryptedContentInfo"; -const HASH_ALGORITHM$4 = "hashAlgorithm"; -const MASK_GEN_ALGORITHM$1 = "maskGenAlgorithm"; -const SALT_LENGTH = "saltLength"; -const TRAILER_FIELD = "trailerField"; -const CLEAR_PROPS$14 = [ - HASH_ALGORITHM$4, - MASK_GEN_ALGORITHM$1, - SALT_LENGTH, - TRAILER_FIELD -]; -class RSASSAPSSParams extends PkiObject { - constructor(parameters = {}) { - super(); - this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$4, RSASSAPSSParams.defaultValues(HASH_ALGORITHM$4)); - this.maskGenAlgorithm = getParametersValue(parameters, MASK_GEN_ALGORITHM$1, RSASSAPSSParams.defaultValues(MASK_GEN_ALGORITHM$1)); - this.saltLength = getParametersValue(parameters, SALT_LENGTH, RSASSAPSSParams.defaultValues(SALT_LENGTH)); - this.trailerField = getParametersValue(parameters, TRAILER_FIELD, RSASSAPSSParams.defaultValues(TRAILER_FIELD)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case HASH_ALGORITHM$4: - return new AlgorithmIdentifier({ - algorithmId: "1.3.14.3.2.26", - algorithmParams: new Null() - }); - case MASK_GEN_ALGORITHM$1: - return new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.1.8", - algorithmParams: (new AlgorithmIdentifier({ - algorithmId: "1.3.14.3.2.26", - algorithmParams: new Null() - })).toSchema() - }); - case SALT_LENGTH: - return 20; - case TRAILER_FIELD: - return 1; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - optional: true, - value: [AlgorithmIdentifier.schema(names.hashAlgorithm || {})] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - optional: true, - value: [AlgorithmIdentifier.schema(names.maskGenAlgorithm || {})] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - optional: true, - value: [new Integer({ name: (names.saltLength || EMPTY_STRING) })] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - optional: true, - value: [new Integer({ name: (names.trailerField || EMPTY_STRING) })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$14); - const asn1 = compareSchema(schema, schema, RSASSAPSSParams.schema({ - names: { - hashAlgorithm: { - names: { - blockName: HASH_ALGORITHM$4 - } - }, - maskGenAlgorithm: { - names: { - blockName: MASK_GEN_ALGORITHM$1 - } - }, - saltLength: SALT_LENGTH, - trailerField: TRAILER_FIELD - } - })); - AsnError.assertSchema(asn1, this.className); - if (HASH_ALGORITHM$4 in asn1.result) - this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); - if (MASK_GEN_ALGORITHM$1 in asn1.result) - this.maskGenAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.maskGenAlgorithm }); - if (SALT_LENGTH in asn1.result) - this.saltLength = asn1.result.saltLength.valueBlock.valueDec; - if (TRAILER_FIELD in asn1.result) - this.trailerField = asn1.result.trailerField.valueBlock.valueDec; - } - toSchema() { - const outputArray = []; - if (!this.hashAlgorithm.isEqual(RSASSAPSSParams.defaultValues(HASH_ALGORITHM$4))) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.hashAlgorithm.toSchema()] - })); - } - if (!this.maskGenAlgorithm.isEqual(RSASSAPSSParams.defaultValues(MASK_GEN_ALGORITHM$1))) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [this.maskGenAlgorithm.toSchema()] - })); - } - if (this.saltLength !== RSASSAPSSParams.defaultValues(SALT_LENGTH)) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [new Integer({ value: this.saltLength })] - })); - } - if (this.trailerField !== RSASSAPSSParams.defaultValues(TRAILER_FIELD)) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - value: [new Integer({ value: this.trailerField })] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = {}; - if (!this.hashAlgorithm.isEqual(RSASSAPSSParams.defaultValues(HASH_ALGORITHM$4))) { - res.hashAlgorithm = this.hashAlgorithm.toJSON(); - } - if (!this.maskGenAlgorithm.isEqual(RSASSAPSSParams.defaultValues(MASK_GEN_ALGORITHM$1))) { - res.maskGenAlgorithm = this.maskGenAlgorithm.toJSON(); - } - if (this.saltLength !== RSASSAPSSParams.defaultValues(SALT_LENGTH)) { - res.saltLength = this.saltLength; - } - if (this.trailerField !== RSASSAPSSParams.defaultValues(TRAILER_FIELD)) { - res.trailerField = this.trailerField; - } - return res; - } -} +const HASH_ALGORITHM$4 = "hashAlgorithm"; +const MASK_GEN_ALGORITHM$1 = "maskGenAlgorithm"; +const SALT_LENGTH = "saltLength"; +const TRAILER_FIELD = "trailerField"; +const CLEAR_PROPS$14 = [ + HASH_ALGORITHM$4, + MASK_GEN_ALGORITHM$1, + SALT_LENGTH, + TRAILER_FIELD +]; +class RSASSAPSSParams extends PkiObject { + constructor(parameters = {}) { + super(); + this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$4, RSASSAPSSParams.defaultValues(HASH_ALGORITHM$4)); + this.maskGenAlgorithm = getParametersValue(parameters, MASK_GEN_ALGORITHM$1, RSASSAPSSParams.defaultValues(MASK_GEN_ALGORITHM$1)); + this.saltLength = getParametersValue(parameters, SALT_LENGTH, RSASSAPSSParams.defaultValues(SALT_LENGTH)); + this.trailerField = getParametersValue(parameters, TRAILER_FIELD, RSASSAPSSParams.defaultValues(TRAILER_FIELD)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case HASH_ALGORITHM$4: + return new AlgorithmIdentifier({ + algorithmId: "1.3.14.3.2.26", + algorithmParams: new Null() + }); + case MASK_GEN_ALGORITHM$1: + return new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.1.8", + algorithmParams: (new AlgorithmIdentifier({ + algorithmId: "1.3.14.3.2.26", + algorithmParams: new Null() + })).toSchema() + }); + case SALT_LENGTH: + return 20; + case TRAILER_FIELD: + return 1; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + optional: true, + value: [AlgorithmIdentifier.schema(names.hashAlgorithm || {})] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + optional: true, + value: [AlgorithmIdentifier.schema(names.maskGenAlgorithm || {})] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + optional: true, + value: [new Integer({ name: (names.saltLength || EMPTY_STRING) })] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + optional: true, + value: [new Integer({ name: (names.trailerField || EMPTY_STRING) })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$14); + const asn1 = compareSchema(schema, schema, RSASSAPSSParams.schema({ + names: { + hashAlgorithm: { + names: { + blockName: HASH_ALGORITHM$4 + } + }, + maskGenAlgorithm: { + names: { + blockName: MASK_GEN_ALGORITHM$1 + } + }, + saltLength: SALT_LENGTH, + trailerField: TRAILER_FIELD + } + })); + AsnError.assertSchema(asn1, this.className); + if (HASH_ALGORITHM$4 in asn1.result) + this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); + if (MASK_GEN_ALGORITHM$1 in asn1.result) + this.maskGenAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.maskGenAlgorithm }); + if (SALT_LENGTH in asn1.result) + this.saltLength = asn1.result.saltLength.valueBlock.valueDec; + if (TRAILER_FIELD in asn1.result) + this.trailerField = asn1.result.trailerField.valueBlock.valueDec; + } + toSchema() { + const outputArray = []; + if (!this.hashAlgorithm.isEqual(RSASSAPSSParams.defaultValues(HASH_ALGORITHM$4))) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.hashAlgorithm.toSchema()] + })); + } + if (!this.maskGenAlgorithm.isEqual(RSASSAPSSParams.defaultValues(MASK_GEN_ALGORITHM$1))) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [this.maskGenAlgorithm.toSchema()] + })); + } + if (this.saltLength !== RSASSAPSSParams.defaultValues(SALT_LENGTH)) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [new Integer({ value: this.saltLength })] + })); + } + if (this.trailerField !== RSASSAPSSParams.defaultValues(TRAILER_FIELD)) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + value: [new Integer({ value: this.trailerField })] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = {}; + if (!this.hashAlgorithm.isEqual(RSASSAPSSParams.defaultValues(HASH_ALGORITHM$4))) { + res.hashAlgorithm = this.hashAlgorithm.toJSON(); + } + if (!this.maskGenAlgorithm.isEqual(RSASSAPSSParams.defaultValues(MASK_GEN_ALGORITHM$1))) { + res.maskGenAlgorithm = this.maskGenAlgorithm.toJSON(); + } + if (this.saltLength !== RSASSAPSSParams.defaultValues(SALT_LENGTH)) { + res.saltLength = this.saltLength; + } + if (this.trailerField !== RSASSAPSSParams.defaultValues(TRAILER_FIELD)) { + res.trailerField = this.trailerField; + } + return res; + } +} RSASSAPSSParams.CLASS_NAME = "RSASSAPSSParams"; -const SALT = "salt"; -const ITERATION_COUNT = "iterationCount"; -const KEY_LENGTH = "keyLength"; -const PRF = "prf"; -const CLEAR_PROPS$13 = [ - SALT, - ITERATION_COUNT, - KEY_LENGTH, - PRF -]; -class PBKDF2Params extends PkiObject { - constructor(parameters = {}) { - super(); - this.salt = getParametersValue(parameters, SALT, PBKDF2Params.defaultValues(SALT)); - this.iterationCount = getParametersValue(parameters, ITERATION_COUNT, PBKDF2Params.defaultValues(ITERATION_COUNT)); - if (KEY_LENGTH in parameters) { - this.keyLength = getParametersValue(parameters, KEY_LENGTH, PBKDF2Params.defaultValues(KEY_LENGTH)); - } - if (PRF in parameters) { - this.prf = getParametersValue(parameters, PRF, PBKDF2Params.defaultValues(PRF)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case SALT: - return {}; - case ITERATION_COUNT: - return (-1); - case KEY_LENGTH: - return 0; - case PRF: - return new AlgorithmIdentifier({ - algorithmId: "1.3.14.3.2.26", - algorithmParams: new Null() - }); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Choice({ - value: [ - new OctetString({ name: (names.saltPrimitive || EMPTY_STRING) }), - AlgorithmIdentifier.schema(names.saltConstructed || {}) - ] - }), - new Integer({ name: (names.iterationCount || EMPTY_STRING) }), - new Integer({ - name: (names.keyLength || EMPTY_STRING), - optional: true - }), - AlgorithmIdentifier.schema(names.prf || { - names: { - optional: true - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$13); - const asn1 = compareSchema(schema, schema, PBKDF2Params.schema({ - names: { - saltPrimitive: SALT, - saltConstructed: { - names: { - blockName: SALT - } - }, - iterationCount: ITERATION_COUNT, - keyLength: KEY_LENGTH, - prf: { - names: { - blockName: PRF, - optional: true - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.salt = asn1.result.salt; - this.iterationCount = asn1.result.iterationCount.valueBlock.valueDec; - if (KEY_LENGTH in asn1.result) - this.keyLength = asn1.result.keyLength.valueBlock.valueDec; - if (PRF in asn1.result) - this.prf = new AlgorithmIdentifier({ schema: asn1.result.prf }); - } - toSchema() { - const outputArray = []; - outputArray.push(this.salt); - outputArray.push(new Integer({ value: this.iterationCount })); - if (KEY_LENGTH in this) { - if (PBKDF2Params.defaultValues(KEY_LENGTH) !== this.keyLength) - outputArray.push(new Integer({ value: this.keyLength })); - } - if (this.prf) { - if (PBKDF2Params.defaultValues(PRF).isEqual(this.prf) === false) - outputArray.push(this.prf.toSchema()); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - salt: this.salt.toJSON(), - iterationCount: this.iterationCount - }; - if (KEY_LENGTH in this) { - if (PBKDF2Params.defaultValues(KEY_LENGTH) !== this.keyLength) - res.keyLength = this.keyLength; - } - if (this.prf) { - if (PBKDF2Params.defaultValues(PRF).isEqual(this.prf) === false) - res.prf = this.prf.toJSON(); - } - return res; - } -} +const SALT = "salt"; +const ITERATION_COUNT = "iterationCount"; +const KEY_LENGTH = "keyLength"; +const PRF = "prf"; +const CLEAR_PROPS$13 = [ + SALT, + ITERATION_COUNT, + KEY_LENGTH, + PRF +]; +class PBKDF2Params extends PkiObject { + constructor(parameters = {}) { + super(); + this.salt = getParametersValue(parameters, SALT, PBKDF2Params.defaultValues(SALT)); + this.iterationCount = getParametersValue(parameters, ITERATION_COUNT, PBKDF2Params.defaultValues(ITERATION_COUNT)); + if (KEY_LENGTH in parameters) { + this.keyLength = getParametersValue(parameters, KEY_LENGTH, PBKDF2Params.defaultValues(KEY_LENGTH)); + } + if (PRF in parameters) { + this.prf = getParametersValue(parameters, PRF, PBKDF2Params.defaultValues(PRF)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case SALT: + return {}; + case ITERATION_COUNT: + return (-1); + case KEY_LENGTH: + return 0; + case PRF: + return new AlgorithmIdentifier({ + algorithmId: "1.3.14.3.2.26", + algorithmParams: new Null() + }); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Choice({ + value: [ + new OctetString({ name: (names.saltPrimitive || EMPTY_STRING) }), + AlgorithmIdentifier.schema(names.saltConstructed || {}) + ] + }), + new Integer({ name: (names.iterationCount || EMPTY_STRING) }), + new Integer({ + name: (names.keyLength || EMPTY_STRING), + optional: true + }), + AlgorithmIdentifier.schema(names.prf || { + names: { + optional: true + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$13); + const asn1 = compareSchema(schema, schema, PBKDF2Params.schema({ + names: { + saltPrimitive: SALT, + saltConstructed: { + names: { + blockName: SALT + } + }, + iterationCount: ITERATION_COUNT, + keyLength: KEY_LENGTH, + prf: { + names: { + blockName: PRF, + optional: true + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.salt = asn1.result.salt; + this.iterationCount = asn1.result.iterationCount.valueBlock.valueDec; + if (KEY_LENGTH in asn1.result) + this.keyLength = asn1.result.keyLength.valueBlock.valueDec; + if (PRF in asn1.result) + this.prf = new AlgorithmIdentifier({ schema: asn1.result.prf }); + } + toSchema() { + const outputArray = []; + outputArray.push(this.salt); + outputArray.push(new Integer({ value: this.iterationCount })); + if (KEY_LENGTH in this) { + if (PBKDF2Params.defaultValues(KEY_LENGTH) !== this.keyLength) + outputArray.push(new Integer({ value: this.keyLength })); + } + if (this.prf) { + if (PBKDF2Params.defaultValues(PRF).isEqual(this.prf) === false) + outputArray.push(this.prf.toSchema()); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + salt: this.salt.toJSON(), + iterationCount: this.iterationCount + }; + if (KEY_LENGTH in this) { + if (PBKDF2Params.defaultValues(KEY_LENGTH) !== this.keyLength) + res.keyLength = this.keyLength; + } + if (this.prf) { + if (PBKDF2Params.defaultValues(PRF).isEqual(this.prf) === false) + res.prf = this.prf.toJSON(); + } + return res; + } +} PBKDF2Params.CLASS_NAME = "PBKDF2Params"; -const KEY_DERIVATION_FUNC = "keyDerivationFunc"; -const ENCRYPTION_SCHEME = "encryptionScheme"; -const CLEAR_PROPS$12 = [ - KEY_DERIVATION_FUNC, - ENCRYPTION_SCHEME -]; -class PBES2Params extends PkiObject { - constructor(parameters = {}) { - super(); - this.keyDerivationFunc = getParametersValue(parameters, KEY_DERIVATION_FUNC, PBES2Params.defaultValues(KEY_DERIVATION_FUNC)); - this.encryptionScheme = getParametersValue(parameters, ENCRYPTION_SCHEME, PBES2Params.defaultValues(ENCRYPTION_SCHEME)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case KEY_DERIVATION_FUNC: - return new AlgorithmIdentifier(); - case ENCRYPTION_SCHEME: - return new AlgorithmIdentifier(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.keyDerivationFunc || {}), - AlgorithmIdentifier.schema(names.encryptionScheme || {}) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$12); - const asn1 = compareSchema(schema, schema, PBES2Params.schema({ - names: { - keyDerivationFunc: { - names: { - blockName: KEY_DERIVATION_FUNC - } - }, - encryptionScheme: { - names: { - blockName: ENCRYPTION_SCHEME - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.keyDerivationFunc = new AlgorithmIdentifier({ schema: asn1.result.keyDerivationFunc }); - this.encryptionScheme = new AlgorithmIdentifier({ schema: asn1.result.encryptionScheme }); - } - toSchema() { - return (new Sequence({ - value: [ - this.keyDerivationFunc.toSchema(), - this.encryptionScheme.toSchema() - ] - })); - } - toJSON() { - return { - keyDerivationFunc: this.keyDerivationFunc.toJSON(), - encryptionScheme: this.encryptionScheme.toJSON() - }; - } -} +const KEY_DERIVATION_FUNC = "keyDerivationFunc"; +const ENCRYPTION_SCHEME = "encryptionScheme"; +const CLEAR_PROPS$12 = [ + KEY_DERIVATION_FUNC, + ENCRYPTION_SCHEME +]; +class PBES2Params extends PkiObject { + constructor(parameters = {}) { + super(); + this.keyDerivationFunc = getParametersValue(parameters, KEY_DERIVATION_FUNC, PBES2Params.defaultValues(KEY_DERIVATION_FUNC)); + this.encryptionScheme = getParametersValue(parameters, ENCRYPTION_SCHEME, PBES2Params.defaultValues(ENCRYPTION_SCHEME)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case KEY_DERIVATION_FUNC: + return new AlgorithmIdentifier(); + case ENCRYPTION_SCHEME: + return new AlgorithmIdentifier(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.keyDerivationFunc || {}), + AlgorithmIdentifier.schema(names.encryptionScheme || {}) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$12); + const asn1 = compareSchema(schema, schema, PBES2Params.schema({ + names: { + keyDerivationFunc: { + names: { + blockName: KEY_DERIVATION_FUNC + } + }, + encryptionScheme: { + names: { + blockName: ENCRYPTION_SCHEME + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.keyDerivationFunc = new AlgorithmIdentifier({ schema: asn1.result.keyDerivationFunc }); + this.encryptionScheme = new AlgorithmIdentifier({ schema: asn1.result.encryptionScheme }); + } + toSchema() { + return (new Sequence({ + value: [ + this.keyDerivationFunc.toSchema(), + this.encryptionScheme.toSchema() + ] + })); + } + toJSON() { + return { + keyDerivationFunc: this.keyDerivationFunc.toJSON(), + encryptionScheme: this.encryptionScheme.toJSON() + }; + } +} PBES2Params.CLASS_NAME = "PBES2Params"; -class AbstractCryptoEngine { - constructor(parameters) { - this.crypto = parameters.crypto; - this.subtle = "webkitSubtle" in parameters.crypto - ? parameters.crypto.webkitSubtle - : parameters.crypto.subtle; - this.name = getParametersValue(parameters, "name", EMPTY_STRING); - } - encrypt(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.encrypt(...args); - }); - } - decrypt(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.decrypt(...args); - }); - } - sign(...args) { - return this.subtle.sign(...args); - } - verify(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.verify(...args); - }); - } - digest(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.digest(...args); - }); - } - generateKey(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.generateKey(...args); - }); - } - deriveKey(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.deriveKey(...args); - }); - } - deriveBits(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.deriveBits(...args); - }); - } - wrapKey(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.wrapKey(...args); - }); - } - unwrapKey(...args) { - return __awaiter(this, void 0, void 0, function* () { - return this.subtle.unwrapKey(...args); - }); - } - exportKey(...args) { - return this.subtle.exportKey(...args); - } - importKey(...args) { - return this.subtle.importKey(...args); - } - getRandomValues(array) { - return this.crypto.getRandomValues(array); - } +class AbstractCryptoEngine { + constructor(parameters) { + this.crypto = parameters.crypto; + this.subtle = "webkitSubtle" in parameters.crypto + ? parameters.crypto.webkitSubtle + : parameters.crypto.subtle; + this.name = getParametersValue(parameters, "name", EMPTY_STRING); + } + async encrypt(...args) { + return this.subtle.encrypt(...args); + } + async decrypt(...args) { + return this.subtle.decrypt(...args); + } + sign(...args) { + return this.subtle.sign(...args); + } + async verify(...args) { + return this.subtle.verify(...args); + } + async digest(...args) { + return this.subtle.digest(...args); + } + async generateKey(...args) { + return this.subtle.generateKey(...args); + } + async deriveKey(...args) { + return this.subtle.deriveKey(...args); + } + async deriveBits(...args) { + return this.subtle.deriveBits(...args); + } + async wrapKey(...args) { + return this.subtle.wrapKey(...args); + } + async unwrapKey(...args) { + return this.subtle.unwrapKey(...args); + } + exportKey(...args) { + return this.subtle.exportKey(...args); + } + importKey(...args) { + return this.subtle.importKey(...args); + } + getRandomValues(array) { + if (array === null) { + throw new Error("Argument \"array\" must not be null"); + } + return this.crypto.getRandomValues(array); + } } -function makePKCS12B2Key(cryptoEngine, hashAlgorithm, keyLength, password, salt, iterationCount) { - return __awaiter(this, void 0, void 0, function* () { - let u; - let v; - const result = []; - switch (hashAlgorithm.toUpperCase()) { - case "SHA-1": - u = 20; - v = 64; - break; - case "SHA-256": - u = 32; - v = 64; - break; - case "SHA-384": - u = 48; - v = 128; - break; - case "SHA-512": - u = 64; - v = 128; - break; - default: - throw new Error("Unsupported hashing algorithm"); - } - const passwordViewInitial = new Uint8Array(password); - const passwordTransformed = new ArrayBuffer((password.byteLength * 2) + 2); - const passwordTransformedView = new Uint8Array(passwordTransformed); - for (let i = 0; i < passwordViewInitial.length; i++) { - passwordTransformedView[i * 2] = 0x00; - passwordTransformedView[i * 2 + 1] = passwordViewInitial[i]; - } - passwordTransformedView[passwordTransformedView.length - 2] = 0x00; - passwordTransformedView[passwordTransformedView.length - 1] = 0x00; - password = passwordTransformed.slice(0); - const D = new ArrayBuffer(v); - const dView = new Uint8Array(D); - for (let i = 0; i < D.byteLength; i++) - dView[i] = 3; - const saltLength = salt.byteLength; - const sLen = v * Math.ceil(saltLength / v); - const S = new ArrayBuffer(sLen); - const sView = new Uint8Array(S); - const saltView = new Uint8Array(salt); - for (let i = 0; i < sLen; i++) - sView[i] = saltView[i % saltLength]; - const passwordLength = password.byteLength; - const pLen = v * Math.ceil(passwordLength / v); - const P = new ArrayBuffer(pLen); - const pView = new Uint8Array(P); - const passwordView = new Uint8Array(password); - for (let i = 0; i < pLen; i++) - pView[i] = passwordView[i % passwordLength]; - const sPlusPLength = S.byteLength + P.byteLength; - let I = new ArrayBuffer(sPlusPLength); - let iView = new Uint8Array(I); - iView.set(sView); - iView.set(pView, sView.length); - const c = Math.ceil((keyLength >> 3) / u); - let internalSequence = Promise.resolve(I); - for (let i = 0; i <= c; i++) { - internalSequence = internalSequence.then(_I => { - const dAndI = new ArrayBuffer(D.byteLength + _I.byteLength); - const dAndIView = new Uint8Array(dAndI); - dAndIView.set(dView); - dAndIView.set(iView, dView.length); - return dAndI; - }); - for (let j = 0; j < iterationCount; j++) - internalSequence = internalSequence.then(roundBuffer => cryptoEngine.digest({ name: hashAlgorithm }, new Uint8Array(roundBuffer))); - internalSequence = internalSequence.then(roundBuffer => { - const B = new ArrayBuffer(v); - const bView = new Uint8Array(B); - for (let j = 0; j < B.byteLength; j++) - bView[j] = roundBuffer[j % roundBuffer.byteLength]; - const k = Math.ceil(saltLength / v) + Math.ceil(passwordLength / v); - const iRound = []; - let sliceStart = 0; - let sliceLength = v; - for (let j = 0; j < k; j++) { - const chunk = Array.from(new Uint8Array(I.slice(sliceStart, sliceStart + sliceLength))); - sliceStart += v; - if ((sliceStart + v) > I.byteLength) - sliceLength = I.byteLength - sliceStart; - let x = 0x1ff; - for (let l = (B.byteLength - 1); l >= 0; l--) { - x >>= 8; - x += bView[l] + chunk[l]; - chunk[l] = (x & 0xff); - } - iRound.push(...chunk); - } - I = new ArrayBuffer(iRound.length); - iView = new Uint8Array(I); - iView.set(iRound); - result.push(...(new Uint8Array(roundBuffer))); - return I; - }); - } - internalSequence = internalSequence.then(() => { - const resultBuffer = new ArrayBuffer(keyLength >> 3); - const resultView = new Uint8Array(resultBuffer); - resultView.set((new Uint8Array(result)).slice(0, keyLength >> 3)); - return resultBuffer; - }); - return internalSequence; - }); -} -function prepareAlgorithm(data) { - const res = typeof data === "string" - ? { name: data } - : data; - if ("hash" in res) { - return Object.assign(Object.assign({}, res), { hash: prepareAlgorithm(res.hash) }); - } - return res; -} -class CryptoEngine extends AbstractCryptoEngine { - importKey(format, keyData, algorithm, extractable, keyUsages) { - var _a, _b, _c, _d, _e, _f; - return __awaiter(this, void 0, void 0, function* () { - let jwk = {}; - const alg = prepareAlgorithm(algorithm); - switch (format.toLowerCase()) { - case "raw": - return this.subtle.importKey("raw", keyData, algorithm, extractable, keyUsages); - case "spki": - { - const asn1 = fromBER(BufferSourceConverter.toArrayBuffer(keyData)); - AsnError.assert(asn1, "keyData"); - const publicKeyInfo = new PublicKeyInfo(); - try { - publicKeyInfo.fromSchema(asn1.result); - } - catch (_g) { - throw new ArgumentError("Incorrect keyData"); - } - switch (alg.name.toUpperCase()) { - case "RSA-PSS": - { - if (!alg.hash) { - throw new ParameterError("hash", "algorithm.hash", "Incorrect hash algorithm: Hash algorithm is missed"); - } - switch (alg.hash.name.toUpperCase()) { - case "SHA-1": - jwk.alg = "PS1"; - break; - case "SHA-256": - jwk.alg = "PS256"; - break; - case "SHA-384": - jwk.alg = "PS384"; - break; - case "SHA-512": - jwk.alg = "PS512"; - break; - default: - throw new Error(`Incorrect hash algorithm: ${alg.hash.name.toUpperCase()}`); - } - } - case "RSASSA-PKCS1-V1_5": - { - keyUsages = ["verify"]; - jwk.kty = "RSA"; - jwk.ext = extractable; - jwk.key_ops = keyUsages; - if (publicKeyInfo.algorithm.algorithmId !== "1.2.840.113549.1.1.1") - throw new Error(`Incorrect public key algorithm: ${publicKeyInfo.algorithm.algorithmId}`); - if (!jwk.alg) { - if (!alg.hash) { - throw new ParameterError("hash", "algorithm.hash", "Incorrect hash algorithm: Hash algorithm is missed"); - } - switch (alg.hash.name.toUpperCase()) { - case "SHA-1": - jwk.alg = "RS1"; - break; - case "SHA-256": - jwk.alg = "RS256"; - break; - case "SHA-384": - jwk.alg = "RS384"; - break; - case "SHA-512": - jwk.alg = "RS512"; - break; - default: - throw new Error(`Incorrect hash algorithm: ${alg.hash.name.toUpperCase()}`); - } - } - const publicKeyJSON = publicKeyInfo.toJSON(); - Object.assign(jwk, publicKeyJSON); - } - break; - case "ECDSA": - keyUsages = ["verify"]; - case "ECDH": - { - jwk = { - kty: "EC", - ext: extractable, - key_ops: keyUsages - }; - if (publicKeyInfo.algorithm.algorithmId !== "1.2.840.10045.2.1") { - throw new Error(`Incorrect public key algorithm: ${publicKeyInfo.algorithm.algorithmId}`); - } - const publicKeyJSON = publicKeyInfo.toJSON(); - Object.assign(jwk, publicKeyJSON); - } - break; - case "RSA-OAEP": - { - jwk.kty = "RSA"; - jwk.ext = extractable; - jwk.key_ops = keyUsages; - if (this.name.toLowerCase() === "safari") - jwk.alg = "RSA-OAEP"; - else { - if (!alg.hash) { - throw new ParameterError("hash", "algorithm.hash", "Incorrect hash algorithm: Hash algorithm is missed"); - } - switch (alg.hash.name.toUpperCase()) { - case "SHA-1": - jwk.alg = "RSA-OAEP"; - break; - case "SHA-256": - jwk.alg = "RSA-OAEP-256"; - break; - case "SHA-384": - jwk.alg = "RSA-OAEP-384"; - break; - case "SHA-512": - jwk.alg = "RSA-OAEP-512"; - break; - default: - throw new Error(`Incorrect hash algorithm: ${alg.hash.name.toUpperCase()}`); - } - } - const publicKeyJSON = publicKeyInfo.toJSON(); - Object.assign(jwk, publicKeyJSON); - } - break; - case "RSAES-PKCS1-V1_5": - { - jwk.kty = "RSA"; - jwk.ext = extractable; - jwk.key_ops = keyUsages; - jwk.alg = "PS1"; - const publicKeyJSON = publicKeyInfo.toJSON(); - Object.assign(jwk, publicKeyJSON); - } - break; - default: - throw new Error(`Incorrect algorithm name: ${alg.name.toUpperCase()}`); - } - } - break; - case "pkcs8": - { - const privateKeyInfo = new PrivateKeyInfo(); - const asn1 = fromBER(BufferSourceConverter.toArrayBuffer(keyData)); - AsnError.assert(asn1, "keyData"); - try { - privateKeyInfo.fromSchema(asn1.result); - } - catch (ex) { - throw new Error("Incorrect keyData"); - } - if (!privateKeyInfo.parsedKey) - throw new Error("Incorrect keyData"); - switch (alg.name.toUpperCase()) { - case "RSA-PSS": - { - switch ((_a = alg.hash) === null || _a === void 0 ? void 0 : _a.name.toUpperCase()) { - case "SHA-1": - jwk.alg = "PS1"; - break; - case "SHA-256": - jwk.alg = "PS256"; - break; - case "SHA-384": - jwk.alg = "PS384"; - break; - case "SHA-512": - jwk.alg = "PS512"; - break; - default: - throw new Error(`Incorrect hash algorithm: ${(_b = alg.hash) === null || _b === void 0 ? void 0 : _b.name.toUpperCase()}`); - } - } - case "RSASSA-PKCS1-V1_5": - { - keyUsages = ["sign"]; - jwk.kty = "RSA"; - jwk.ext = extractable; - jwk.key_ops = keyUsages; - if (privateKeyInfo.privateKeyAlgorithm.algorithmId !== "1.2.840.113549.1.1.1") - throw new Error(`Incorrect private key algorithm: ${privateKeyInfo.privateKeyAlgorithm.algorithmId}`); - if (("alg" in jwk) === false) { - switch ((_c = alg.hash) === null || _c === void 0 ? void 0 : _c.name.toUpperCase()) { - case "SHA-1": - jwk.alg = "RS1"; - break; - case "SHA-256": - jwk.alg = "RS256"; - break; - case "SHA-384": - jwk.alg = "RS384"; - break; - case "SHA-512": - jwk.alg = "RS512"; - break; - default: - throw new Error(`Incorrect hash algorithm: ${(_d = alg.hash) === null || _d === void 0 ? void 0 : _d.name.toUpperCase()}`); - } - } - const privateKeyJSON = privateKeyInfo.toJSON(); - Object.assign(jwk, privateKeyJSON); - } - break; - case "ECDSA": - keyUsages = ["sign"]; - case "ECDH": - { - jwk = { - kty: "EC", - ext: extractable, - key_ops: keyUsages - }; - if (privateKeyInfo.privateKeyAlgorithm.algorithmId !== "1.2.840.10045.2.1") - throw new Error(`Incorrect algorithm: ${privateKeyInfo.privateKeyAlgorithm.algorithmId}`); - const privateKeyJSON = privateKeyInfo.toJSON(); - Object.assign(jwk, privateKeyJSON); - } - break; - case "RSA-OAEP": - { - jwk.kty = "RSA"; - jwk.ext = extractable; - jwk.key_ops = keyUsages; - if (this.name.toLowerCase() === "safari") - jwk.alg = "RSA-OAEP"; - else { - switch ((_e = alg.hash) === null || _e === void 0 ? void 0 : _e.name.toUpperCase()) { - case "SHA-1": - jwk.alg = "RSA-OAEP"; - break; - case "SHA-256": - jwk.alg = "RSA-OAEP-256"; - break; - case "SHA-384": - jwk.alg = "RSA-OAEP-384"; - break; - case "SHA-512": - jwk.alg = "RSA-OAEP-512"; - break; - default: - throw new Error(`Incorrect hash algorithm: ${(_f = alg.hash) === null || _f === void 0 ? void 0 : _f.name.toUpperCase()}`); - } - } - const privateKeyJSON = privateKeyInfo.toJSON(); - Object.assign(jwk, privateKeyJSON); - } - break; - case "RSAES-PKCS1-V1_5": - { - keyUsages = ["decrypt"]; - jwk.kty = "RSA"; - jwk.ext = extractable; - jwk.key_ops = keyUsages; - jwk.alg = "PS1"; - const privateKeyJSON = privateKeyInfo.toJSON(); - Object.assign(jwk, privateKeyJSON); - } - break; - default: - throw new Error(`Incorrect algorithm name: ${alg.name.toUpperCase()}`); - } - } - break; - case "jwk": - jwk = keyData; - break; - default: - throw new Error(`Incorrect format: ${format}`); - } - if (this.name.toLowerCase() === "safari") { - try { - return this.subtle.importKey("jwk", stringToArrayBuffer(JSON.stringify(jwk)), algorithm, extractable, keyUsages); - } - catch (_h) { - return this.subtle.importKey("jwk", jwk, algorithm, extractable, keyUsages); - } - } - return this.subtle.importKey("jwk", jwk, algorithm, extractable, keyUsages); - }); - } - exportKey(format, key) { - return __awaiter(this, void 0, void 0, function* () { - let jwk = yield this.subtle.exportKey("jwk", key); - if (this.name.toLowerCase() === "safari") { - if (jwk instanceof ArrayBuffer) { - jwk = JSON.parse(arrayBufferToString(jwk)); - } - } - switch (format.toLowerCase()) { - case "raw": - return this.subtle.exportKey("raw", key); - case "spki": { - const publicKeyInfo = new PublicKeyInfo(); - try { - publicKeyInfo.fromJSON(jwk); - } - catch (ex) { - throw new Error("Incorrect key data"); - } - return publicKeyInfo.toSchema().toBER(false); - } - case "pkcs8": { - const privateKeyInfo = new PrivateKeyInfo(); - try { - privateKeyInfo.fromJSON(jwk); - } - catch (ex) { - throw new Error("Incorrect key data"); - } - return privateKeyInfo.toSchema().toBER(false); - } - case "jwk": - return jwk; - default: - throw new Error(`Incorrect format: ${format}`); - } - }); - } - convert(inputFormat, outputFormat, keyData, algorithm, extractable, keyUsages) { - return __awaiter(this, void 0, void 0, function* () { - if (inputFormat.toLowerCase() === outputFormat.toLowerCase()) { - return keyData; - } - const key = yield this.importKey(inputFormat, keyData, algorithm, extractable, keyUsages); - return this.exportKey(outputFormat, key); - }); - } - getAlgorithmByOID(oid, safety = false, target) { - switch (oid) { - case "1.2.840.113549.1.1.1": - return { - name: "RSAES-PKCS1-v1_5" - }; - case "1.2.840.113549.1.1.5": - return { - name: "RSASSA-PKCS1-v1_5", - hash: { - name: "SHA-1" - } - }; - case "1.2.840.113549.1.1.11": - return { - name: "RSASSA-PKCS1-v1_5", - hash: { - name: "SHA-256" - } - }; - case "1.2.840.113549.1.1.12": - return { - name: "RSASSA-PKCS1-v1_5", - hash: { - name: "SHA-384" - } - }; - case "1.2.840.113549.1.1.13": - return { - name: "RSASSA-PKCS1-v1_5", - hash: { - name: "SHA-512" - } - }; - case "1.2.840.113549.1.1.10": - return { - name: "RSA-PSS" - }; - case "1.2.840.113549.1.1.7": - return { - name: "RSA-OAEP" - }; - case "1.2.840.10045.2.1": - case "1.2.840.10045.4.1": - return { - name: "ECDSA", - hash: { - name: "SHA-1" - } - }; - case "1.2.840.10045.4.3.2": - return { - name: "ECDSA", - hash: { - name: "SHA-256" - } - }; - case "1.2.840.10045.4.3.3": - return { - name: "ECDSA", - hash: { - name: "SHA-384" - } - }; - case "1.2.840.10045.4.3.4": - return { - name: "ECDSA", - hash: { - name: "SHA-512" - } - }; - case "1.3.133.16.840.63.0.2": - return { - name: "ECDH", - kdf: "SHA-1" - }; - case "1.3.132.1.11.1": - return { - name: "ECDH", - kdf: "SHA-256" - }; - case "1.3.132.1.11.2": - return { - name: "ECDH", - kdf: "SHA-384" - }; - case "1.3.132.1.11.3": - return { - name: "ECDH", - kdf: "SHA-512" - }; - case "2.16.840.1.101.3.4.1.2": - return { - name: "AES-CBC", - length: 128 - }; - case "2.16.840.1.101.3.4.1.22": - return { - name: "AES-CBC", - length: 192 - }; - case "2.16.840.1.101.3.4.1.42": - return { - name: "AES-CBC", - length: 256 - }; - case "2.16.840.1.101.3.4.1.6": - return { - name: "AES-GCM", - length: 128 - }; - case "2.16.840.1.101.3.4.1.26": - return { - name: "AES-GCM", - length: 192 - }; - case "2.16.840.1.101.3.4.1.46": - return { - name: "AES-GCM", - length: 256 - }; - case "2.16.840.1.101.3.4.1.4": - return { - name: "AES-CFB", - length: 128 - }; - case "2.16.840.1.101.3.4.1.24": - return { - name: "AES-CFB", - length: 192 - }; - case "2.16.840.1.101.3.4.1.44": - return { - name: "AES-CFB", - length: 256 - }; - case "2.16.840.1.101.3.4.1.5": - return { - name: "AES-KW", - length: 128 - }; - case "2.16.840.1.101.3.4.1.25": - return { - name: "AES-KW", - length: 192 - }; - case "2.16.840.1.101.3.4.1.45": - return { - name: "AES-KW", - length: 256 - }; - case "1.2.840.113549.2.7": - return { - name: "HMAC", - hash: { - name: "SHA-1" - } - }; - case "1.2.840.113549.2.9": - return { - name: "HMAC", - hash: { - name: "SHA-256" - } - }; - case "1.2.840.113549.2.10": - return { - name: "HMAC", - hash: { - name: "SHA-384" - } - }; - case "1.2.840.113549.2.11": - return { - name: "HMAC", - hash: { - name: "SHA-512" - } - }; - case "1.2.840.113549.1.9.16.3.5": - return { - name: "DH" - }; - case "1.3.14.3.2.26": - return { - name: "SHA-1" - }; - case "2.16.840.1.101.3.4.2.1": - return { - name: "SHA-256" - }; - case "2.16.840.1.101.3.4.2.2": - return { - name: "SHA-384" - }; - case "2.16.840.1.101.3.4.2.3": - return { - name: "SHA-512" - }; - case "1.2.840.113549.1.5.12": - return { - name: "PBKDF2" - }; - case "1.2.840.10045.3.1.7": - return { - name: "P-256" - }; - case "1.3.132.0.34": - return { - name: "P-384" - }; - case "1.3.132.0.35": - return { - name: "P-521" - }; - } - if (safety) { - throw new Error(`Unsupported algorithm identifier ${target ? `for ${target} ` : EMPTY_STRING}: ${oid}`); - } - return {}; - } - getOIDByAlgorithm(algorithm, safety = false, target) { - let result = EMPTY_STRING; - switch (algorithm.name.toUpperCase()) { - case "RSAES-PKCS1-V1_5": - result = "1.2.840.113549.1.1.1"; - break; - case "RSASSA-PKCS1-V1_5": - switch (algorithm.hash.name.toUpperCase()) { - case "SHA-1": - result = "1.2.840.113549.1.1.5"; - break; - case "SHA-256": - result = "1.2.840.113549.1.1.11"; - break; - case "SHA-384": - result = "1.2.840.113549.1.1.12"; - break; - case "SHA-512": - result = "1.2.840.113549.1.1.13"; - break; - } - break; - case "RSA-PSS": - result = "1.2.840.113549.1.1.10"; - break; - case "RSA-OAEP": - result = "1.2.840.113549.1.1.7"; - break; - case "ECDSA": - switch (algorithm.hash.name.toUpperCase()) { - case "SHA-1": - result = "1.2.840.10045.4.1"; - break; - case "SHA-256": - result = "1.2.840.10045.4.3.2"; - break; - case "SHA-384": - result = "1.2.840.10045.4.3.3"; - break; - case "SHA-512": - result = "1.2.840.10045.4.3.4"; - break; - } - break; - case "ECDH": - switch (algorithm.kdf.toUpperCase()) { - case "SHA-1": - result = "1.3.133.16.840.63.0.2"; - break; - case "SHA-256": - result = "1.3.132.1.11.1"; - break; - case "SHA-384": - result = "1.3.132.1.11.2"; - break; - case "SHA-512": - result = "1.3.132.1.11.3"; - break; - } - break; - case "AES-CTR": - break; - case "AES-CBC": - switch (algorithm.length) { - case 128: - result = "2.16.840.1.101.3.4.1.2"; - break; - case 192: - result = "2.16.840.1.101.3.4.1.22"; - break; - case 256: - result = "2.16.840.1.101.3.4.1.42"; - break; - } - break; - case "AES-CMAC": - break; - case "AES-GCM": - switch (algorithm.length) { - case 128: - result = "2.16.840.1.101.3.4.1.6"; - break; - case 192: - result = "2.16.840.1.101.3.4.1.26"; - break; - case 256: - result = "2.16.840.1.101.3.4.1.46"; - break; - } - break; - case "AES-CFB": - switch (algorithm.length) { - case 128: - result = "2.16.840.1.101.3.4.1.4"; - break; - case 192: - result = "2.16.840.1.101.3.4.1.24"; - break; - case 256: - result = "2.16.840.1.101.3.4.1.44"; - break; - } - break; - case "AES-KW": - switch (algorithm.length) { - case 128: - result = "2.16.840.1.101.3.4.1.5"; - break; - case 192: - result = "2.16.840.1.101.3.4.1.25"; - break; - case 256: - result = "2.16.840.1.101.3.4.1.45"; - break; - } - break; - case "HMAC": - switch (algorithm.hash.name.toUpperCase()) { - case "SHA-1": - result = "1.2.840.113549.2.7"; - break; - case "SHA-256": - result = "1.2.840.113549.2.9"; - break; - case "SHA-384": - result = "1.2.840.113549.2.10"; - break; - case "SHA-512": - result = "1.2.840.113549.2.11"; - break; - } - break; - case "DH": - result = "1.2.840.113549.1.9.16.3.5"; - break; - case "SHA-1": - result = "1.3.14.3.2.26"; - break; - case "SHA-256": - result = "2.16.840.1.101.3.4.2.1"; - break; - case "SHA-384": - result = "2.16.840.1.101.3.4.2.2"; - break; - case "SHA-512": - result = "2.16.840.1.101.3.4.2.3"; - break; - case "CONCAT": - break; - case "HKDF": - break; - case "PBKDF2": - result = "1.2.840.113549.1.5.12"; - break; - case "P-256": - result = "1.2.840.10045.3.1.7"; - break; - case "P-384": - result = "1.3.132.0.34"; - break; - case "P-521": - result = "1.3.132.0.35"; - break; - } - if (!result && safety) { - throw new Error(`Unsupported algorithm ${target ? `for ${target} ` : EMPTY_STRING}: ${algorithm.name}`); - } - return result; - } - getAlgorithmParameters(algorithmName, operation) { - let result = { - algorithm: {}, - usages: [] - }; - switch (algorithmName.toUpperCase()) { - case "RSAES-PKCS1-V1_5": - case "RSASSA-PKCS1-V1_5": - switch (operation.toLowerCase()) { - case "generatekey": - result = { - algorithm: { - name: "RSASSA-PKCS1-v1_5", - modulusLength: 2048, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - hash: { - name: "SHA-256" - } - }, - usages: ["sign", "verify"] - }; - break; - case "verify": - case "sign": - case "importkey": - result = { - algorithm: { - name: "RSASSA-PKCS1-v1_5", - hash: { - name: "SHA-256" - } - }, - usages: ["verify"] - }; - break; - case "exportkey": - default: - return { - algorithm: { - name: "RSASSA-PKCS1-v1_5" - }, - usages: [] - }; - } - break; - case "RSA-PSS": - switch (operation.toLowerCase()) { - case "sign": - case "verify": - result = { - algorithm: { - name: "RSA-PSS", - hash: { - name: "SHA-1" - }, - saltLength: 20 - }, - usages: ["sign", "verify"] - }; - break; - case "generatekey": - result = { - algorithm: { - name: "RSA-PSS", - modulusLength: 2048, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - hash: { - name: "SHA-1" - } - }, - usages: ["sign", "verify"] - }; - break; - case "importkey": - result = { - algorithm: { - name: "RSA-PSS", - hash: { - name: "SHA-1" - } - }, - usages: ["verify"] - }; - break; - case "exportkey": - default: - return { - algorithm: { - name: "RSA-PSS" - }, - usages: [] - }; - } - break; - case "RSA-OAEP": - switch (operation.toLowerCase()) { - case "encrypt": - case "decrypt": - result = { - algorithm: { - name: "RSA-OAEP" - }, - usages: ["encrypt", "decrypt"] - }; - break; - case "generatekey": - result = { - algorithm: { - name: "RSA-OAEP", - modulusLength: 2048, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - hash: { - name: "SHA-256" - } - }, - usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] - }; - break; - case "importkey": - result = { - algorithm: { - name: "RSA-OAEP", - hash: { - name: "SHA-256" - } - }, - usages: ["encrypt"] - }; - break; - case "exportkey": - default: - return { - algorithm: { - name: "RSA-OAEP" - }, - usages: [] - }; - } - break; - case "ECDSA": - switch (operation.toLowerCase()) { - case "generatekey": - result = { - algorithm: { - name: "ECDSA", - namedCurve: "P-256" - }, - usages: ["sign", "verify"] - }; - break; - case "importkey": - result = { - algorithm: { - name: "ECDSA", - namedCurve: "P-256" - }, - usages: ["verify"] - }; - break; - case "verify": - case "sign": - result = { - algorithm: { - name: "ECDSA", - hash: { - name: "SHA-256" - } - }, - usages: ["sign"] - }; - break; - default: - return { - algorithm: { - name: "ECDSA" - }, - usages: [] - }; - } - break; - case "ECDH": - switch (operation.toLowerCase()) { - case "exportkey": - case "importkey": - case "generatekey": - result = { - algorithm: { - name: "ECDH", - namedCurve: "P-256" - }, - usages: ["deriveKey", "deriveBits"] - }; - break; - case "derivekey": - case "derivebits": - result = { - algorithm: { - name: "ECDH", - namedCurve: "P-256", - public: [] - }, - usages: ["encrypt", "decrypt"] - }; - break; - default: - return { - algorithm: { - name: "ECDH" - }, - usages: [] - }; - } - break; - case "AES-CTR": - switch (operation.toLowerCase()) { - case "importkey": - case "exportkey": - case "generatekey": - result = { - algorithm: { - name: "AES-CTR", - length: 256 - }, - usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] - }; - break; - case "decrypt": - case "encrypt": - result = { - algorithm: { - name: "AES-CTR", - counter: new Uint8Array(16), - length: 10 - }, - usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] - }; - break; - default: - return { - algorithm: { - name: "AES-CTR" - }, - usages: [] - }; - } - break; - case "AES-CBC": - switch (operation.toLowerCase()) { - case "importkey": - case "exportkey": - case "generatekey": - result = { - algorithm: { - name: "AES-CBC", - length: 256 - }, - usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] - }; - break; - case "decrypt": - case "encrypt": - result = { - algorithm: { - name: "AES-CBC", - iv: this.getRandomValues(new Uint8Array(16)) - }, - usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] - }; - break; - default: - return { - algorithm: { - name: "AES-CBC" - }, - usages: [] - }; - } - break; - case "AES-GCM": - switch (operation.toLowerCase()) { - case "importkey": - case "exportkey": - case "generatekey": - result = { - algorithm: { - name: "AES-GCM", - length: 256 - }, - usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] - }; - break; - case "decrypt": - case "encrypt": - result = { - algorithm: { - name: "AES-GCM", - iv: this.getRandomValues(new Uint8Array(16)) - }, - usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] - }; - break; - default: - return { - algorithm: { - name: "AES-GCM" - }, - usages: [] - }; - } - break; - case "AES-KW": - switch (operation.toLowerCase()) { - case "importkey": - case "exportkey": - case "generatekey": - case "wrapkey": - case "unwrapkey": - result = { - algorithm: { - name: "AES-KW", - length: 256 - }, - usages: ["wrapKey", "unwrapKey"] - }; - break; - default: - return { - algorithm: { - name: "AES-KW" - }, - usages: [] - }; - } - break; - case "HMAC": - switch (operation.toLowerCase()) { - case "sign": - case "verify": - result = { - algorithm: { - name: "HMAC" - }, - usages: ["sign", "verify"] - }; - break; - case "importkey": - case "exportkey": - case "generatekey": - result = { - algorithm: { - name: "HMAC", - length: 32, - hash: { - name: "SHA-256" - } - }, - usages: ["sign", "verify"] - }; - break; - default: - return { - algorithm: { - name: "HMAC" - }, - usages: [] - }; - } - break; - case "HKDF": - switch (operation.toLowerCase()) { - case "derivekey": - result = { - algorithm: { - name: "HKDF", - hash: "SHA-256", - salt: new Uint8Array([]), - info: new Uint8Array([]) - }, - usages: ["encrypt", "decrypt"] - }; - break; - default: - return { - algorithm: { - name: "HKDF" - }, - usages: [] - }; - } - break; - case "PBKDF2": - switch (operation.toLowerCase()) { - case "derivekey": - result = { - algorithm: { - name: "PBKDF2", - hash: { name: "SHA-256" }, - salt: new Uint8Array([]), - iterations: 10000 - }, - usages: ["encrypt", "decrypt"] - }; - break; - default: - return { - algorithm: { - name: "PBKDF2" - }, - usages: [] - }; - } - break; - } - return result; - } - getHashAlgorithm(signatureAlgorithm) { - let result = EMPTY_STRING; - switch (signatureAlgorithm.algorithmId) { - case "1.2.840.10045.4.1": - case "1.2.840.113549.1.1.5": - result = "SHA-1"; - break; - case "1.2.840.10045.4.3.2": - case "1.2.840.113549.1.1.11": - result = "SHA-256"; - break; - case "1.2.840.10045.4.3.3": - case "1.2.840.113549.1.1.12": - result = "SHA-384"; - break; - case "1.2.840.10045.4.3.4": - case "1.2.840.113549.1.1.13": - result = "SHA-512"; - break; - case "1.2.840.113549.1.1.10": - { - try { - const params = new RSASSAPSSParams({ schema: signatureAlgorithm.algorithmParams }); - if (params.hashAlgorithm) { - const algorithm = this.getAlgorithmByOID(params.hashAlgorithm.algorithmId); - if ("name" in algorithm) { - result = algorithm.name; - } - else { - return EMPTY_STRING; - } - } - else - result = "SHA-1"; - } - catch (_a) { - } - } - break; - } - return result; - } - encryptEncryptedContentInfo(parameters) { - return __awaiter(this, void 0, void 0, function* () { - ParameterError.assert(parameters, "password", "contentEncryptionAlgorithm", "hmacHashAlgorithm", "iterationCount", "contentToEncrypt", "contentToEncrypt", "contentType"); - const contentEncryptionOID = this.getOIDByAlgorithm(parameters.contentEncryptionAlgorithm, true, "contentEncryptionAlgorithm"); - const pbkdf2OID = this.getOIDByAlgorithm({ - name: "PBKDF2" - }, true, "PBKDF2"); - const hmacOID = this.getOIDByAlgorithm({ - name: "HMAC", - hash: { - name: parameters.hmacHashAlgorithm - } - }, true, "hmacHashAlgorithm"); - const ivBuffer = new ArrayBuffer(16); - const ivView = new Uint8Array(ivBuffer); - this.getRandomValues(ivView); - const saltBuffer = new ArrayBuffer(64); - const saltView = new Uint8Array(saltBuffer); - this.getRandomValues(saltView); - const contentView = new Uint8Array(parameters.contentToEncrypt); - const pbkdf2Params = new PBKDF2Params({ - salt: new OctetString({ valueHex: saltBuffer }), - iterationCount: parameters.iterationCount, - prf: new AlgorithmIdentifier({ - algorithmId: hmacOID, - algorithmParams: new Null() - }) - }); - const passwordView = new Uint8Array(parameters.password); - const pbkdfKey = yield this.importKey("raw", passwordView, "PBKDF2", false, ["deriveKey"]); - const derivedKey = yield this.deriveKey({ - name: "PBKDF2", - hash: { - name: parameters.hmacHashAlgorithm - }, - salt: saltView, - iterations: parameters.iterationCount - }, pbkdfKey, parameters.contentEncryptionAlgorithm, false, ["encrypt"]); - const encryptedData = yield this.encrypt({ - name: parameters.contentEncryptionAlgorithm.name, - iv: ivView - }, derivedKey, contentView); - const pbes2Parameters = new PBES2Params({ - keyDerivationFunc: new AlgorithmIdentifier({ - algorithmId: pbkdf2OID, - algorithmParams: pbkdf2Params.toSchema() - }), - encryptionScheme: new AlgorithmIdentifier({ - algorithmId: contentEncryptionOID, - algorithmParams: new OctetString({ valueHex: ivBuffer }) - }) - }); - return new EncryptedContentInfo({ - contentType: parameters.contentType, - contentEncryptionAlgorithm: new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.5.13", - algorithmParams: pbes2Parameters.toSchema() - }), - encryptedContent: new OctetString({ valueHex: encryptedData }) - }); - }); - } - decryptEncryptedContentInfo(parameters) { - return __awaiter(this, void 0, void 0, function* () { - ParameterError.assert(parameters, "password", "encryptedContentInfo"); - if (parameters.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId !== "1.2.840.113549.1.5.13") - throw new Error(`Unknown "contentEncryptionAlgorithm": ${parameters.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId}`); - let pbes2Parameters; - try { - pbes2Parameters = new PBES2Params({ schema: parameters.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams }); - } - catch (ex) { - throw new Error("Incorrectly encoded \"pbes2Parameters\""); - } - let pbkdf2Params; - try { - pbkdf2Params = new PBKDF2Params({ schema: pbes2Parameters.keyDerivationFunc.algorithmParams }); - } - catch (ex) { - throw new Error("Incorrectly encoded \"pbkdf2Params\""); - } - const contentEncryptionAlgorithm = this.getAlgorithmByOID(pbes2Parameters.encryptionScheme.algorithmId, true); - const ivBuffer = pbes2Parameters.encryptionScheme.algorithmParams.valueBlock.valueHex; - const ivView = new Uint8Array(ivBuffer); - const saltBuffer = pbkdf2Params.salt.valueBlock.valueHex; - const saltView = new Uint8Array(saltBuffer); - const iterationCount = pbkdf2Params.iterationCount; - let hmacHashAlgorithm = "SHA-1"; - if (pbkdf2Params.prf) { - const algorithm = this.getAlgorithmByOID(pbkdf2Params.prf.algorithmId, true); - hmacHashAlgorithm = algorithm.hash.name; - } - const pbkdfKey = yield this.importKey("raw", parameters.password, "PBKDF2", false, ["deriveKey"]); - const result = yield this.deriveKey({ - name: "PBKDF2", - hash: { - name: hmacHashAlgorithm - }, - salt: saltView, - iterations: iterationCount - }, pbkdfKey, contentEncryptionAlgorithm, false, ["decrypt"]); - const dataBuffer = parameters.encryptedContentInfo.getEncryptedContent(); - return this.decrypt({ - name: contentEncryptionAlgorithm.name, - iv: ivView - }, result, dataBuffer); - }); - } - stampDataWithPassword(parameters) { - return __awaiter(this, void 0, void 0, function* () { - if ((parameters instanceof Object) === false) - throw new Error("Parameters must have type \"Object\""); - ParameterError.assert(parameters, "password", "hashAlgorithm", "iterationCount", "salt", "contentToStamp"); - let length; - switch (parameters.hashAlgorithm.toLowerCase()) { - case "sha-1": - length = 160; - break; - case "sha-256": - length = 256; - break; - case "sha-384": - length = 384; - break; - case "sha-512": - length = 512; - break; - default: - throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${parameters.hashAlgorithm}`); - } - const hmacAlgorithm = { - name: "HMAC", - length, - hash: { - name: parameters.hashAlgorithm - } - }; - const pkcsKey = yield makePKCS12B2Key(this, parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); - const hmacKey = yield this.importKey("raw", new Uint8Array(pkcsKey), hmacAlgorithm, false, ["sign"]); - return this.sign(hmacAlgorithm, hmacKey, new Uint8Array(parameters.contentToStamp)); - }); - } - verifyDataStampedWithPassword(parameters) { - return __awaiter(this, void 0, void 0, function* () { - ParameterError.assert(parameters, "password", "hashAlgorithm", "salt", "iterationCount", "contentToVerify", "signatureToVerify"); - let length = 0; - switch (parameters.hashAlgorithm.toLowerCase()) { - case "sha-1": - length = 160; - break; - case "sha-256": - length = 256; - break; - case "sha-384": - length = 384; - break; - case "sha-512": - length = 512; - break; - default: - throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${parameters.hashAlgorithm}`); - } - const hmacAlgorithm = { - name: "HMAC", - length, - hash: { - name: parameters.hashAlgorithm - } - }; - const pkcsKey = yield makePKCS12B2Key(this, parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); - const hmacKey = yield this.importKey("raw", new Uint8Array(pkcsKey), hmacAlgorithm, false, ["verify"]); - return this.verify(hmacAlgorithm, hmacKey, new Uint8Array(parameters.signatureToVerify), new Uint8Array(parameters.contentToVerify)); - }); - } - getSignatureParameters(privateKey, hashAlgorithm = "SHA-1") { - return __awaiter(this, void 0, void 0, function* () { - this.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); - const signatureAlgorithm = new AlgorithmIdentifier(); - const parameters = this.getAlgorithmParameters(privateKey.algorithm.name, "sign"); - if (!Object.keys(parameters.algorithm).length) { - throw new Error("Parameter 'algorithm' is empty"); - } - const algorithm = parameters.algorithm; - algorithm.hash.name = hashAlgorithm; - switch (privateKey.algorithm.name.toUpperCase()) { - case "RSASSA-PKCS1-V1_5": - case "ECDSA": - signatureAlgorithm.algorithmId = this.getOIDByAlgorithm(algorithm, true); - break; - case "RSA-PSS": - { - switch (hashAlgorithm.toUpperCase()) { - case "SHA-256": - algorithm.saltLength = 32; - break; - case "SHA-384": - algorithm.saltLength = 48; - break; - case "SHA-512": - algorithm.saltLength = 64; - break; - } - const paramsObject = {}; - if (hashAlgorithm.toUpperCase() !== "SHA-1") { - const hashAlgorithmOID = this.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); - paramsObject.hashAlgorithm = new AlgorithmIdentifier({ - algorithmId: hashAlgorithmOID, - algorithmParams: new Null() - }); - paramsObject.maskGenAlgorithm = new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.1.8", - algorithmParams: paramsObject.hashAlgorithm.toSchema() - }); - } - if (algorithm.saltLength !== 20) - paramsObject.saltLength = algorithm.saltLength; - const pssParameters = new RSASSAPSSParams(paramsObject); - signatureAlgorithm.algorithmId = "1.2.840.113549.1.1.10"; - signatureAlgorithm.algorithmParams = pssParameters.toSchema(); - } - break; - default: - throw new Error(`Unsupported signature algorithm: ${privateKey.algorithm.name}`); - } - return { - signatureAlgorithm, - parameters - }; - }); - } - signWithPrivateKey(data, privateKey, parameters) { - return __awaiter(this, void 0, void 0, function* () { - const signature = yield this.sign(parameters.algorithm, privateKey, data); - if (parameters.algorithm.name === "ECDSA") { - return createCMSECDSASignature(signature); - } - return signature; - }); - } - fillPublicKeyParameters(publicKeyInfo, signatureAlgorithm) { - const parameters = {}; - const shaAlgorithm = this.getHashAlgorithm(signatureAlgorithm); - if (shaAlgorithm === EMPTY_STRING) - throw new Error(`Unsupported signature algorithm: ${signatureAlgorithm.algorithmId}`); - let algorithmId; - if (signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.10") - algorithmId = signatureAlgorithm.algorithmId; - else - algorithmId = publicKeyInfo.algorithm.algorithmId; - const algorithmObject = this.getAlgorithmByOID(algorithmId, true); - parameters.algorithm = this.getAlgorithmParameters(algorithmObject.name, "importKey"); - if ("hash" in parameters.algorithm.algorithm) - parameters.algorithm.algorithm.hash.name = shaAlgorithm; - if (algorithmObject.name === "ECDSA") { - const publicKeyAlgorithm = publicKeyInfo.algorithm; - if (!publicKeyAlgorithm.algorithmParams) { - throw new Error("Algorithm parameters for ECDSA public key are missed"); - } - const publicKeyAlgorithmParams = publicKeyAlgorithm.algorithmParams; - if ("idBlock" in publicKeyAlgorithm.algorithmParams) { - if (!((publicKeyAlgorithmParams.idBlock.tagClass === 1) && (publicKeyAlgorithmParams.idBlock.tagNumber === 6))) { - throw new Error("Incorrect type for ECDSA public key parameters"); - } - } - const curveObject = this.getAlgorithmByOID(publicKeyAlgorithmParams.valueBlock.toString(), true); - parameters.algorithm.algorithm.namedCurve = curveObject.name; - } - return parameters; - } - getPublicKey(publicKeyInfo, signatureAlgorithm, parameters) { - return __awaiter(this, void 0, void 0, function* () { - if (!parameters) { - parameters = this.fillPublicKeyParameters(publicKeyInfo, signatureAlgorithm); - } - const publicKeyInfoBuffer = publicKeyInfo.toSchema().toBER(false); - return this.importKey("spki", publicKeyInfoBuffer, parameters.algorithm.algorithm, true, parameters.algorithm.usages); - }); - } - verifyWithPublicKey(data, signature, publicKeyInfo, signatureAlgorithm, shaAlgorithm) { - return __awaiter(this, void 0, void 0, function* () { - let publicKey; - if (!shaAlgorithm) { - shaAlgorithm = this.getHashAlgorithm(signatureAlgorithm); - if (!shaAlgorithm) - throw new Error(`Unsupported signature algorithm: ${signatureAlgorithm.algorithmId}`); - publicKey = yield this.getPublicKey(publicKeyInfo, signatureAlgorithm); - } - else { - const parameters = {}; - let algorithmId; - if (signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.10") - algorithmId = signatureAlgorithm.algorithmId; - else - algorithmId = publicKeyInfo.algorithm.algorithmId; - const algorithmObject = this.getAlgorithmByOID(algorithmId, true); - parameters.algorithm = this.getAlgorithmParameters(algorithmObject.name, "importKey"); - if ("hash" in parameters.algorithm.algorithm) - parameters.algorithm.algorithm.hash.name = shaAlgorithm; - if (algorithmObject.name === "ECDSA") { - let algorithmParamsChecked = false; - if (("algorithmParams" in publicKeyInfo.algorithm) === true) { - if ("idBlock" in publicKeyInfo.algorithm.algorithmParams) { - if ((publicKeyInfo.algorithm.algorithmParams.idBlock.tagClass === 1) && (publicKeyInfo.algorithm.algorithmParams.idBlock.tagNumber === 6)) - algorithmParamsChecked = true; - } - } - if (algorithmParamsChecked === false) { - throw new Error("Incorrect type for ECDSA public key parameters"); - } - const curveObject = this.getAlgorithmByOID(publicKeyInfo.algorithm.algorithmParams.valueBlock.toString(), true); - parameters.algorithm.algorithm.namedCurve = curveObject.name; - } - publicKey = yield this.getPublicKey(publicKeyInfo, null, parameters); - } - const algorithm = this.getAlgorithmParameters(publicKey.algorithm.name, "verify"); - if ("hash" in algorithm.algorithm) - algorithm.algorithm.hash.name = shaAlgorithm; - let signatureValue = signature.valueBlock.valueHexView; - if (publicKey.algorithm.name === "ECDSA") { - const namedCurve = ECNamedCurves.find(publicKey.algorithm.namedCurve); - if (!namedCurve) { - throw new Error("Unsupported named curve in use"); - } - const asn1 = fromBER(signatureValue); - AsnError.assert(asn1, "Signature value"); - signatureValue = createECDSASignatureFromCMS(asn1.result, namedCurve.size); - } - if (publicKey.algorithm.name === "RSA-PSS") { - const pssParameters = new RSASSAPSSParams({ schema: signatureAlgorithm.algorithmParams }); - if ("saltLength" in pssParameters) - algorithm.algorithm.saltLength = pssParameters.saltLength; - else - algorithm.algorithm.saltLength = 20; - let hashAlgo = "SHA-1"; - if ("hashAlgorithm" in pssParameters) { - const hashAlgorithm = this.getAlgorithmByOID(pssParameters.hashAlgorithm.algorithmId, true); - hashAlgo = hashAlgorithm.name; - } - algorithm.algorithm.hash.name = hashAlgo; - } - return this.verify(algorithm.algorithm, publicKey, signatureValue, data); - }); - } +async function makePKCS12B2Key(hashAlgorithm, keyLength, password, salt, iterationCount) { + let u; + let v; + let md; + switch (hashAlgorithm.toUpperCase()) { + case "SHA-1": + u = 20; + v = 64; + md = sha1; + break; + case "SHA-256": + u = 32; + v = 64; + md = sha256; + break; + case "SHA-384": + u = 48; + v = 128; + md = sha384; + break; + case "SHA-512": + u = 64; + v = 128; + md = sha512; + break; + default: + throw new Error("Unsupported hashing algorithm"); + } + const originalPassword = new Uint8Array(password); + let decodedPassword = new TextDecoder().decode(password); + const encodedPassword = new TextEncoder().encode(decodedPassword); + if (encodedPassword.some((byte, i) => byte !== originalPassword[i])) { + decodedPassword = String.fromCharCode(...originalPassword); + } + const passwordTransformed = new Uint8Array(decodedPassword.length * 2 + 2); + const passwordView = new DataView(passwordTransformed.buffer); + for (let i = 0; i < decodedPassword.length; i++) { + passwordView.setUint16(i * 2, decodedPassword.charCodeAt(i), false); + } + passwordView.setUint16(decodedPassword.length * 2, 0, false); + const D = new Uint8Array(v).fill(3); + const saltView = new Uint8Array(salt); + const S = new Uint8Array(v * Math.ceil(saltView.length / v)).map((_, i) => saltView[i % saltView.length]); + const P = new Uint8Array(v * Math.ceil(passwordTransformed.length / v)).map((_, i) => passwordTransformed[i % passwordTransformed.length]); + let I = new Uint8Array(S.length + P.length); + I.set(S); + I.set(P, S.length); + const c = Math.ceil((keyLength >> 3) / u); + const result = []; + for (let i = 0; i < c; i++) { + let A = new Uint8Array(D.length + I.length); + A.set(D); + A.set(I, D.length); + for (let j = 0; j < iterationCount; j++) { + A = md(A); + } + const B = new Uint8Array(v).map((_, i) => A[i % A.length]); + const k = Math.ceil(saltView.length / v) + Math.ceil(passwordTransformed.length / v); + const iRound = []; + for (let j = 0; j < k; j++) { + const chunk = Array.from(I.slice(j * v, (j + 1) * v)); + let x = 0x1ff; + for (let l = B.length - 1; l >= 0; l--) { + x >>= 8; + x += B[l] + (chunk[l] || 0); + chunk[l] = x & 0xff; + } + iRound.push(...chunk); + } + I = new Uint8Array(iRound); + result.push(...A); + } + return new Uint8Array(result.slice(0, keyLength >> 3)).buffer; +} +function prepareAlgorithm(data) { + const res = typeof data === "string" + ? { name: data } + : data; + if ("hash" in res) { + return { + ...res, + hash: prepareAlgorithm(res.hash) + }; + } + return res; +} +class CryptoEngine extends AbstractCryptoEngine { + async importKey(format, keyData, algorithm, extractable, keyUsages) { + var _a, _b, _c, _d, _e, _f; + let jwk = {}; + const alg = prepareAlgorithm(algorithm); + switch (format.toLowerCase()) { + case "raw": + return this.subtle.importKey("raw", keyData, algorithm, extractable, keyUsages); + case "spki": + { + const asn1 = fromBER(BufferSourceConverter.toArrayBuffer(keyData)); + AsnError.assert(asn1, "keyData"); + const publicKeyInfo = new PublicKeyInfo(); + try { + publicKeyInfo.fromSchema(asn1.result); + } + catch { + throw new ArgumentError("Incorrect keyData"); + } + switch (alg.name.toUpperCase()) { + case "RSA-PSS": + { + if (!alg.hash) { + throw new ParameterError("hash", "algorithm.hash", "Incorrect hash algorithm: Hash algorithm is missed"); + } + switch (alg.hash.name.toUpperCase()) { + case "SHA-1": + jwk.alg = "PS1"; + break; + case "SHA-256": + jwk.alg = "PS256"; + break; + case "SHA-384": + jwk.alg = "PS384"; + break; + case "SHA-512": + jwk.alg = "PS512"; + break; + default: + throw new Error(`Incorrect hash algorithm: ${alg.hash.name.toUpperCase()}`); + } + } + case "RSASSA-PKCS1-V1_5": + { + keyUsages = ["verify"]; + jwk.kty = "RSA"; + jwk.ext = extractable; + jwk.key_ops = keyUsages; + if (publicKeyInfo.algorithm.algorithmId !== "1.2.840.113549.1.1.1") + throw new Error(`Incorrect public key algorithm: ${publicKeyInfo.algorithm.algorithmId}`); + if (!jwk.alg) { + if (!alg.hash) { + throw new ParameterError("hash", "algorithm.hash", "Incorrect hash algorithm: Hash algorithm is missed"); + } + switch (alg.hash.name.toUpperCase()) { + case "SHA-1": + jwk.alg = "RS1"; + break; + case "SHA-256": + jwk.alg = "RS256"; + break; + case "SHA-384": + jwk.alg = "RS384"; + break; + case "SHA-512": + jwk.alg = "RS512"; + break; + default: + throw new Error(`Incorrect hash algorithm: ${alg.hash.name.toUpperCase()}`); + } + } + const publicKeyJSON = publicKeyInfo.toJSON(); + Object.assign(jwk, publicKeyJSON); + } + break; + case "ECDSA": + keyUsages = ["verify"]; + case "ECDH": + { + jwk = { + kty: "EC", + ext: extractable, + key_ops: keyUsages + }; + if (publicKeyInfo.algorithm.algorithmId !== "1.2.840.10045.2.1") { + throw new Error(`Incorrect public key algorithm: ${publicKeyInfo.algorithm.algorithmId}`); + } + const publicKeyJSON = publicKeyInfo.toJSON(); + Object.assign(jwk, publicKeyJSON); + } + break; + case "RSA-OAEP": + { + jwk.kty = "RSA"; + jwk.ext = extractable; + jwk.key_ops = keyUsages; + if (this.name.toLowerCase() === "safari") + jwk.alg = "RSA-OAEP"; + else { + if (!alg.hash) { + throw new ParameterError("hash", "algorithm.hash", "Incorrect hash algorithm: Hash algorithm is missed"); + } + switch (alg.hash.name.toUpperCase()) { + case "SHA-1": + jwk.alg = "RSA-OAEP"; + break; + case "SHA-256": + jwk.alg = "RSA-OAEP-256"; + break; + case "SHA-384": + jwk.alg = "RSA-OAEP-384"; + break; + case "SHA-512": + jwk.alg = "RSA-OAEP-512"; + break; + default: + throw new Error(`Incorrect hash algorithm: ${alg.hash.name.toUpperCase()}`); + } + } + const publicKeyJSON = publicKeyInfo.toJSON(); + Object.assign(jwk, publicKeyJSON); + } + break; + case "RSAES-PKCS1-V1_5": + { + jwk.kty = "RSA"; + jwk.ext = extractable; + jwk.key_ops = keyUsages; + jwk.alg = "PS1"; + const publicKeyJSON = publicKeyInfo.toJSON(); + Object.assign(jwk, publicKeyJSON); + } + break; + default: + throw new Error(`Incorrect algorithm name: ${alg.name.toUpperCase()}`); + } + } + break; + case "pkcs8": + { + const privateKeyInfo = new PrivateKeyInfo(); + const asn1 = fromBER(BufferSourceConverter.toArrayBuffer(keyData)); + AsnError.assert(asn1, "keyData"); + try { + privateKeyInfo.fromSchema(asn1.result); + } + catch { + throw new Error("Incorrect keyData"); + } + if (!privateKeyInfo.parsedKey) + throw new Error("Incorrect keyData"); + switch (alg.name.toUpperCase()) { + case "RSA-PSS": + { + switch ((_a = alg.hash) === null || _a === void 0 ? void 0 : _a.name.toUpperCase()) { + case "SHA-1": + jwk.alg = "PS1"; + break; + case "SHA-256": + jwk.alg = "PS256"; + break; + case "SHA-384": + jwk.alg = "PS384"; + break; + case "SHA-512": + jwk.alg = "PS512"; + break; + default: + throw new Error(`Incorrect hash algorithm: ${(_b = alg.hash) === null || _b === void 0 ? void 0 : _b.name.toUpperCase()}`); + } + } + case "RSASSA-PKCS1-V1_5": + { + keyUsages = ["sign"]; + jwk.kty = "RSA"; + jwk.ext = extractable; + jwk.key_ops = keyUsages; + if (privateKeyInfo.privateKeyAlgorithm.algorithmId !== "1.2.840.113549.1.1.1") + throw new Error(`Incorrect private key algorithm: ${privateKeyInfo.privateKeyAlgorithm.algorithmId}`); + if (("alg" in jwk) === false) { + switch ((_c = alg.hash) === null || _c === void 0 ? void 0 : _c.name.toUpperCase()) { + case "SHA-1": + jwk.alg = "RS1"; + break; + case "SHA-256": + jwk.alg = "RS256"; + break; + case "SHA-384": + jwk.alg = "RS384"; + break; + case "SHA-512": + jwk.alg = "RS512"; + break; + default: + throw new Error(`Incorrect hash algorithm: ${(_d = alg.hash) === null || _d === void 0 ? void 0 : _d.name.toUpperCase()}`); + } + } + const privateKeyJSON = privateKeyInfo.toJSON(); + Object.assign(jwk, privateKeyJSON); + } + break; + case "ECDSA": + keyUsages = ["sign"]; + case "ECDH": + { + jwk = { + kty: "EC", + ext: extractable, + key_ops: keyUsages + }; + if (privateKeyInfo.privateKeyAlgorithm.algorithmId !== "1.2.840.10045.2.1") + throw new Error(`Incorrect algorithm: ${privateKeyInfo.privateKeyAlgorithm.algorithmId}`); + const privateKeyJSON = privateKeyInfo.toJSON(); + Object.assign(jwk, privateKeyJSON); + } + break; + case "RSA-OAEP": + { + jwk.kty = "RSA"; + jwk.ext = extractable; + jwk.key_ops = keyUsages; + if (this.name.toLowerCase() === "safari") + jwk.alg = "RSA-OAEP"; + else { + switch ((_e = alg.hash) === null || _e === void 0 ? void 0 : _e.name.toUpperCase()) { + case "SHA-1": + jwk.alg = "RSA-OAEP"; + break; + case "SHA-256": + jwk.alg = "RSA-OAEP-256"; + break; + case "SHA-384": + jwk.alg = "RSA-OAEP-384"; + break; + case "SHA-512": + jwk.alg = "RSA-OAEP-512"; + break; + default: + throw new Error(`Incorrect hash algorithm: ${(_f = alg.hash) === null || _f === void 0 ? void 0 : _f.name.toUpperCase()}`); + } + } + const privateKeyJSON = privateKeyInfo.toJSON(); + Object.assign(jwk, privateKeyJSON); + } + break; + case "RSAES-PKCS1-V1_5": + { + keyUsages = ["decrypt"]; + jwk.kty = "RSA"; + jwk.ext = extractable; + jwk.key_ops = keyUsages; + jwk.alg = "PS1"; + const privateKeyJSON = privateKeyInfo.toJSON(); + Object.assign(jwk, privateKeyJSON); + } + break; + default: + throw new Error(`Incorrect algorithm name: ${alg.name.toUpperCase()}`); + } + } + break; + case "jwk": + jwk = keyData; + break; + default: + throw new Error(`Incorrect format: ${format}`); + } + if (this.name.toLowerCase() === "safari") { + try { + return this.subtle.importKey("jwk", stringToArrayBuffer(JSON.stringify(jwk)), algorithm, extractable, keyUsages); + } + catch { + return this.subtle.importKey("jwk", jwk, algorithm, extractable, keyUsages); + } + } + return this.subtle.importKey("jwk", jwk, algorithm, extractable, keyUsages); + } + async exportKey(format, key) { + let jwk = await this.subtle.exportKey("jwk", key); + if (this.name.toLowerCase() === "safari") { + if (jwk instanceof ArrayBuffer) { + jwk = JSON.parse(arrayBufferToString(jwk)); + } + } + switch (format.toLowerCase()) { + case "raw": + return this.subtle.exportKey("raw", key); + case "spki": { + const publicKeyInfo = new PublicKeyInfo(); + try { + publicKeyInfo.fromJSON(jwk); + } + catch { + throw new Error("Incorrect key data"); + } + return publicKeyInfo.toSchema().toBER(false); + } + case "pkcs8": { + const privateKeyInfo = new PrivateKeyInfo(); + try { + privateKeyInfo.fromJSON(jwk); + } + catch { + throw new Error("Incorrect key data"); + } + return privateKeyInfo.toSchema().toBER(false); + } + case "jwk": + return jwk; + default: + throw new Error(`Incorrect format: ${format}`); + } + } + async convert(inputFormat, outputFormat, keyData, algorithm, extractable, keyUsages) { + if (inputFormat.toLowerCase() === outputFormat.toLowerCase()) { + return keyData; + } + const key = await this.importKey(inputFormat, keyData, algorithm, extractable, keyUsages); + return this.exportKey(outputFormat, key); + } + getAlgorithmByOID(oid, safety = false, target) { + switch (oid) { + case "1.2.840.113549.1.1.1": + return { + name: "RSAES-PKCS1-v1_5" + }; + case "1.2.840.113549.1.1.5": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-1" + } + }; + case "1.2.840.113549.1.1.11": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-256" + } + }; + case "1.2.840.113549.1.1.12": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-384" + } + }; + case "1.2.840.113549.1.1.13": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-512" + } + }; + case "1.2.840.113549.1.1.10": + return { + name: "RSA-PSS" + }; + case "1.2.840.113549.1.1.7": + return { + name: "RSA-OAEP" + }; + case "1.2.840.10045.2.1": + case "1.2.840.10045.4.1": + return { + name: "ECDSA", + hash: { + name: "SHA-1" + } + }; + case "1.2.840.10045.4.3.2": + return { + name: "ECDSA", + hash: { + name: "SHA-256" + } + }; + case "1.2.840.10045.4.3.3": + return { + name: "ECDSA", + hash: { + name: "SHA-384" + } + }; + case "1.2.840.10045.4.3.4": + return { + name: "ECDSA", + hash: { + name: "SHA-512" + } + }; + case "1.3.133.16.840.63.0.2": + return { + name: "ECDH", + kdf: "SHA-1" + }; + case "1.3.132.1.11.1": + return { + name: "ECDH", + kdf: "SHA-256" + }; + case "1.3.132.1.11.2": + return { + name: "ECDH", + kdf: "SHA-384" + }; + case "1.3.132.1.11.3": + return { + name: "ECDH", + kdf: "SHA-512" + }; + case "2.16.840.1.101.3.4.1.2": + return { + name: "AES-CBC", + length: 128 + }; + case "2.16.840.1.101.3.4.1.22": + return { + name: "AES-CBC", + length: 192 + }; + case "2.16.840.1.101.3.4.1.42": + return { + name: "AES-CBC", + length: 256 + }; + case "2.16.840.1.101.3.4.1.6": + return { + name: "AES-GCM", + length: 128 + }; + case "2.16.840.1.101.3.4.1.26": + return { + name: "AES-GCM", + length: 192 + }; + case "2.16.840.1.101.3.4.1.46": + return { + name: "AES-GCM", + length: 256 + }; + case "2.16.840.1.101.3.4.1.4": + return { + name: "AES-CFB", + length: 128 + }; + case "2.16.840.1.101.3.4.1.24": + return { + name: "AES-CFB", + length: 192 + }; + case "2.16.840.1.101.3.4.1.44": + return { + name: "AES-CFB", + length: 256 + }; + case "2.16.840.1.101.3.4.1.5": + return { + name: "AES-KW", + length: 128 + }; + case "2.16.840.1.101.3.4.1.25": + return { + name: "AES-KW", + length: 192 + }; + case "2.16.840.1.101.3.4.1.45": + return { + name: "AES-KW", + length: 256 + }; + case "1.2.840.113549.2.7": + return { + name: "HMAC", + hash: { + name: "SHA-1" + } + }; + case "1.2.840.113549.2.9": + return { + name: "HMAC", + hash: { + name: "SHA-256" + } + }; + case "1.2.840.113549.2.10": + return { + name: "HMAC", + hash: { + name: "SHA-384" + } + }; + case "1.2.840.113549.2.11": + return { + name: "HMAC", + hash: { + name: "SHA-512" + } + }; + case "1.2.840.113549.1.9.16.3.5": + return { + name: "DH" + }; + case "1.3.14.3.2.26": + return { + name: "SHA-1" + }; + case "2.16.840.1.101.3.4.2.1": + return { + name: "SHA-256" + }; + case "2.16.840.1.101.3.4.2.2": + return { + name: "SHA-384" + }; + case "2.16.840.1.101.3.4.2.3": + return { + name: "SHA-512" + }; + case "1.2.840.113549.1.5.12": + return { + name: "PBKDF2" + }; + case "1.2.840.10045.3.1.7": + return { + name: "P-256" + }; + case "1.3.132.0.34": + return { + name: "P-384" + }; + case "1.3.132.0.35": + return { + name: "P-521" + }; + } + if (safety) { + throw new Error(`Unsupported algorithm identifier ${target ? `for ${target} ` : EMPTY_STRING}: ${oid}`); + } + return {}; + } + getOIDByAlgorithm(algorithm, safety = false, target) { + let result = EMPTY_STRING; + switch (algorithm.name.toUpperCase()) { + case "RSAES-PKCS1-V1_5": + result = "1.2.840.113549.1.1.1"; + break; + case "RSASSA-PKCS1-V1_5": + switch (algorithm.hash.name.toUpperCase()) { + case "SHA-1": + result = "1.2.840.113549.1.1.5"; + break; + case "SHA-256": + result = "1.2.840.113549.1.1.11"; + break; + case "SHA-384": + result = "1.2.840.113549.1.1.12"; + break; + case "SHA-512": + result = "1.2.840.113549.1.1.13"; + break; + } + break; + case "RSA-PSS": + result = "1.2.840.113549.1.1.10"; + break; + case "RSA-OAEP": + result = "1.2.840.113549.1.1.7"; + break; + case "ECDSA": + switch (algorithm.hash.name.toUpperCase()) { + case "SHA-1": + result = "1.2.840.10045.4.1"; + break; + case "SHA-256": + result = "1.2.840.10045.4.3.2"; + break; + case "SHA-384": + result = "1.2.840.10045.4.3.3"; + break; + case "SHA-512": + result = "1.2.840.10045.4.3.4"; + break; + } + break; + case "ECDH": + switch (algorithm.kdf.toUpperCase()) { + case "SHA-1": + result = "1.3.133.16.840.63.0.2"; + break; + case "SHA-256": + result = "1.3.132.1.11.1"; + break; + case "SHA-384": + result = "1.3.132.1.11.2"; + break; + case "SHA-512": + result = "1.3.132.1.11.3"; + break; + } + break; + case "AES-CTR": + break; + case "AES-CBC": + switch (algorithm.length) { + case 128: + result = "2.16.840.1.101.3.4.1.2"; + break; + case 192: + result = "2.16.840.1.101.3.4.1.22"; + break; + case 256: + result = "2.16.840.1.101.3.4.1.42"; + break; + } + break; + case "AES-CMAC": + break; + case "AES-GCM": + switch (algorithm.length) { + case 128: + result = "2.16.840.1.101.3.4.1.6"; + break; + case 192: + result = "2.16.840.1.101.3.4.1.26"; + break; + case 256: + result = "2.16.840.1.101.3.4.1.46"; + break; + } + break; + case "AES-CFB": + switch (algorithm.length) { + case 128: + result = "2.16.840.1.101.3.4.1.4"; + break; + case 192: + result = "2.16.840.1.101.3.4.1.24"; + break; + case 256: + result = "2.16.840.1.101.3.4.1.44"; + break; + } + break; + case "AES-KW": + switch (algorithm.length) { + case 128: + result = "2.16.840.1.101.3.4.1.5"; + break; + case 192: + result = "2.16.840.1.101.3.4.1.25"; + break; + case 256: + result = "2.16.840.1.101.3.4.1.45"; + break; + } + break; + case "HMAC": + switch (algorithm.hash.name.toUpperCase()) { + case "SHA-1": + result = "1.2.840.113549.2.7"; + break; + case "SHA-256": + result = "1.2.840.113549.2.9"; + break; + case "SHA-384": + result = "1.2.840.113549.2.10"; + break; + case "SHA-512": + result = "1.2.840.113549.2.11"; + break; + } + break; + case "DH": + result = "1.2.840.113549.1.9.16.3.5"; + break; + case "SHA-1": + result = "1.3.14.3.2.26"; + break; + case "SHA-256": + result = "2.16.840.1.101.3.4.2.1"; + break; + case "SHA-384": + result = "2.16.840.1.101.3.4.2.2"; + break; + case "SHA-512": + result = "2.16.840.1.101.3.4.2.3"; + break; + case "CONCAT": + break; + case "HKDF": + break; + case "PBKDF2": + result = "1.2.840.113549.1.5.12"; + break; + case "P-256": + result = "1.2.840.10045.3.1.7"; + break; + case "P-384": + result = "1.3.132.0.34"; + break; + case "P-521": + result = "1.3.132.0.35"; + break; + } + if (!result && safety) { + throw new Error(`Unsupported algorithm ${target ? `for ${target} ` : EMPTY_STRING}: ${algorithm.name}`); + } + return result; + } + getAlgorithmParameters(algorithmName, operation) { + let result = { + algorithm: {}, + usages: [] + }; + switch (algorithmName.toUpperCase()) { + case "RSAES-PKCS1-V1_5": + case "RSASSA-PKCS1-V1_5": + switch (operation.toLowerCase()) { + case "generatekey": + result = { + algorithm: { + name: "RSASSA-PKCS1-v1_5", + modulusLength: 2048, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + hash: { + name: "SHA-256" + } + }, + usages: ["sign", "verify"] + }; + break; + case "verify": + case "sign": + case "importkey": + result = { + algorithm: { + name: "RSASSA-PKCS1-v1_5", + hash: { + name: "SHA-256" + } + }, + usages: ["verify"] + }; + break; + case "exportkey": + default: + return { + algorithm: { + name: "RSASSA-PKCS1-v1_5" + }, + usages: [] + }; + } + break; + case "RSA-PSS": + switch (operation.toLowerCase()) { + case "sign": + case "verify": + result = { + algorithm: { + name: "RSA-PSS", + hash: { + name: "SHA-1" + }, + saltLength: 20 + }, + usages: ["sign", "verify"] + }; + break; + case "generatekey": + result = { + algorithm: { + name: "RSA-PSS", + modulusLength: 2048, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + hash: { + name: "SHA-1" + } + }, + usages: ["sign", "verify"] + }; + break; + case "importkey": + result = { + algorithm: { + name: "RSA-PSS", + hash: { + name: "SHA-1" + } + }, + usages: ["verify"] + }; + break; + case "exportkey": + default: + return { + algorithm: { + name: "RSA-PSS" + }, + usages: [] + }; + } + break; + case "RSA-OAEP": + switch (operation.toLowerCase()) { + case "encrypt": + case "decrypt": + result = { + algorithm: { + name: "RSA-OAEP" + }, + usages: ["encrypt", "decrypt"] + }; + break; + case "generatekey": + result = { + algorithm: { + name: "RSA-OAEP", + modulusLength: 2048, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + hash: { + name: "SHA-256" + } + }, + usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] + }; + break; + case "importkey": + result = { + algorithm: { + name: "RSA-OAEP", + hash: { + name: "SHA-256" + } + }, + usages: ["encrypt"] + }; + break; + case "exportkey": + default: + return { + algorithm: { + name: "RSA-OAEP" + }, + usages: [] + }; + } + break; + case "ECDSA": + switch (operation.toLowerCase()) { + case "generatekey": + result = { + algorithm: { + name: "ECDSA", + namedCurve: "P-256" + }, + usages: ["sign", "verify"] + }; + break; + case "importkey": + result = { + algorithm: { + name: "ECDSA", + namedCurve: "P-256" + }, + usages: ["verify"] + }; + break; + case "verify": + case "sign": + result = { + algorithm: { + name: "ECDSA", + hash: { + name: "SHA-256" + } + }, + usages: ["sign"] + }; + break; + default: + return { + algorithm: { + name: "ECDSA" + }, + usages: [] + }; + } + break; + case "ECDH": + switch (operation.toLowerCase()) { + case "exportkey": + case "importkey": + case "generatekey": + result = { + algorithm: { + name: "ECDH", + namedCurve: "P-256" + }, + usages: ["deriveKey", "deriveBits"] + }; + break; + case "derivekey": + case "derivebits": + result = { + algorithm: { + name: "ECDH", + namedCurve: "P-256", + public: [] + }, + usages: ["encrypt", "decrypt"] + }; + break; + default: + return { + algorithm: { + name: "ECDH" + }, + usages: [] + }; + } + break; + case "AES-CTR": + switch (operation.toLowerCase()) { + case "importkey": + case "exportkey": + case "generatekey": + result = { + algorithm: { + name: "AES-CTR", + length: 256 + }, + usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] + }; + break; + case "decrypt": + case "encrypt": + result = { + algorithm: { + name: "AES-CTR", + counter: new Uint8Array(16), + length: 10 + }, + usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] + }; + break; + default: + return { + algorithm: { + name: "AES-CTR" + }, + usages: [] + }; + } + break; + case "AES-CBC": + switch (operation.toLowerCase()) { + case "importkey": + case "exportkey": + case "generatekey": + result = { + algorithm: { + name: "AES-CBC", + length: 256 + }, + usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] + }; + break; + case "decrypt": + case "encrypt": + result = { + algorithm: { + name: "AES-CBC", + iv: this.getRandomValues(new Uint8Array(16)) + }, + usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] + }; + break; + default: + return { + algorithm: { + name: "AES-CBC" + }, + usages: [] + }; + } + break; + case "AES-GCM": + switch (operation.toLowerCase()) { + case "importkey": + case "exportkey": + case "generatekey": + result = { + algorithm: { + name: "AES-GCM", + length: 256 + }, + usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] + }; + break; + case "decrypt": + case "encrypt": + result = { + algorithm: { + name: "AES-GCM", + iv: this.getRandomValues(new Uint8Array(16)) + }, + usages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] + }; + break; + default: + return { + algorithm: { + name: "AES-GCM" + }, + usages: [] + }; + } + break; + case "AES-KW": + switch (operation.toLowerCase()) { + case "importkey": + case "exportkey": + case "generatekey": + case "wrapkey": + case "unwrapkey": + result = { + algorithm: { + name: "AES-KW", + length: 256 + }, + usages: ["wrapKey", "unwrapKey"] + }; + break; + default: + return { + algorithm: { + name: "AES-KW" + }, + usages: [] + }; + } + break; + case "HMAC": + switch (operation.toLowerCase()) { + case "sign": + case "verify": + result = { + algorithm: { + name: "HMAC" + }, + usages: ["sign", "verify"] + }; + break; + case "importkey": + case "exportkey": + case "generatekey": + result = { + algorithm: { + name: "HMAC", + length: 32, + hash: { + name: "SHA-256" + } + }, + usages: ["sign", "verify"] + }; + break; + default: + return { + algorithm: { + name: "HMAC" + }, + usages: [] + }; + } + break; + case "HKDF": + switch (operation.toLowerCase()) { + case "derivekey": + result = { + algorithm: { + name: "HKDF", + hash: "SHA-256", + salt: new Uint8Array([]), + info: new Uint8Array([]) + }, + usages: ["encrypt", "decrypt"] + }; + break; + default: + return { + algorithm: { + name: "HKDF" + }, + usages: [] + }; + } + break; + case "PBKDF2": + switch (operation.toLowerCase()) { + case "derivekey": + result = { + algorithm: { + name: "PBKDF2", + hash: { name: "SHA-256" }, + salt: new Uint8Array([]), + iterations: 10000 + }, + usages: ["encrypt", "decrypt"] + }; + break; + default: + return { + algorithm: { + name: "PBKDF2" + }, + usages: [] + }; + } + break; + } + return result; + } + getHashAlgorithm(signatureAlgorithm) { + let result = EMPTY_STRING; + switch (signatureAlgorithm.algorithmId) { + case "1.2.840.10045.4.1": + case "1.2.840.113549.1.1.5": + result = "SHA-1"; + break; + case "1.2.840.10045.4.3.2": + case "1.2.840.113549.1.1.11": + result = "SHA-256"; + break; + case "1.2.840.10045.4.3.3": + case "1.2.840.113549.1.1.12": + result = "SHA-384"; + break; + case "1.2.840.10045.4.3.4": + case "1.2.840.113549.1.1.13": + result = "SHA-512"; + break; + case "1.2.840.113549.1.1.10": + { + try { + const params = new RSASSAPSSParams({ schema: signatureAlgorithm.algorithmParams }); + if (params.hashAlgorithm) { + const algorithm = this.getAlgorithmByOID(params.hashAlgorithm.algorithmId); + if ("name" in algorithm) { + result = algorithm.name; + } + else { + return EMPTY_STRING; + } + } + else + result = "SHA-1"; + } + catch { + } + } + break; + } + return result; + } + async encryptEncryptedContentInfo(parameters) { + ParameterError.assert(parameters, "password", "contentEncryptionAlgorithm", "hmacHashAlgorithm", "iterationCount", "contentToEncrypt", "contentToEncrypt", "contentType"); + const contentEncryptionOID = this.getOIDByAlgorithm(parameters.contentEncryptionAlgorithm, true, "contentEncryptionAlgorithm"); + const pbkdf2OID = this.getOIDByAlgorithm({ + name: "PBKDF2" + }, true, "PBKDF2"); + const hmacOID = this.getOIDByAlgorithm({ + name: "HMAC", + hash: { + name: parameters.hmacHashAlgorithm + } + }, true, "hmacHashAlgorithm"); + const ivBuffer = new ArrayBuffer(16); + const ivView = new Uint8Array(ivBuffer); + this.getRandomValues(ivView); + const saltBuffer = new ArrayBuffer(64); + const saltView = new Uint8Array(saltBuffer); + this.getRandomValues(saltView); + const contentView = new Uint8Array(parameters.contentToEncrypt); + const pbkdf2Params = new PBKDF2Params({ + salt: new OctetString({ valueHex: saltBuffer }), + iterationCount: parameters.iterationCount, + prf: new AlgorithmIdentifier({ + algorithmId: hmacOID, + algorithmParams: new Null() + }) + }); + const passwordView = new Uint8Array(parameters.password); + const pbkdfKey = await this.importKey("raw", passwordView, "PBKDF2", false, ["deriveKey"]); + const derivedKey = await this.deriveKey({ + name: "PBKDF2", + hash: { + name: parameters.hmacHashAlgorithm + }, + salt: saltView, + iterations: parameters.iterationCount + }, pbkdfKey, parameters.contentEncryptionAlgorithm, false, ["encrypt"]); + const encryptedData = await this.encrypt({ + name: parameters.contentEncryptionAlgorithm.name, + iv: ivView + }, derivedKey, contentView); + const pbes2Parameters = new PBES2Params({ + keyDerivationFunc: new AlgorithmIdentifier({ + algorithmId: pbkdf2OID, + algorithmParams: pbkdf2Params.toSchema() + }), + encryptionScheme: new AlgorithmIdentifier({ + algorithmId: contentEncryptionOID, + algorithmParams: new OctetString({ valueHex: ivBuffer }) + }) + }); + return new EncryptedContentInfo({ + contentType: parameters.contentType, + contentEncryptionAlgorithm: new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.5.13", + algorithmParams: pbes2Parameters.toSchema() + }), + encryptedContent: new OctetString({ valueHex: encryptedData }) + }); + } + async decryptEncryptedContentInfo(parameters) { + ParameterError.assert(parameters, "password", "encryptedContentInfo"); + if (parameters.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId !== "1.2.840.113549.1.5.13") + throw new Error(`Unknown "contentEncryptionAlgorithm": ${parameters.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId}`); + let pbes2Parameters; + try { + pbes2Parameters = new PBES2Params({ schema: parameters.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams }); + } + catch { + throw new Error("Incorrectly encoded \"pbes2Parameters\""); + } + let pbkdf2Params; + try { + pbkdf2Params = new PBKDF2Params({ schema: pbes2Parameters.keyDerivationFunc.algorithmParams }); + } + catch { + throw new Error("Incorrectly encoded \"pbkdf2Params\""); + } + const contentEncryptionAlgorithm = this.getAlgorithmByOID(pbes2Parameters.encryptionScheme.algorithmId, true); + const ivBuffer = pbes2Parameters.encryptionScheme.algorithmParams.valueBlock.valueHex; + const ivView = new Uint8Array(ivBuffer); + const saltBuffer = pbkdf2Params.salt.valueBlock.valueHex; + const saltView = new Uint8Array(saltBuffer); + const iterationCount = pbkdf2Params.iterationCount; + let hmacHashAlgorithm = "SHA-1"; + if (pbkdf2Params.prf) { + const algorithm = this.getAlgorithmByOID(pbkdf2Params.prf.algorithmId, true); + hmacHashAlgorithm = algorithm.hash.name; + } + const pbkdfKey = await this.importKey("raw", parameters.password, "PBKDF2", false, ["deriveKey"]); + const result = await this.deriveKey({ + name: "PBKDF2", + hash: { + name: hmacHashAlgorithm + }, + salt: saltView, + iterations: iterationCount + }, pbkdfKey, contentEncryptionAlgorithm, false, ["decrypt"]); + const dataBuffer = parameters.encryptedContentInfo.getEncryptedContent(); + return this.decrypt({ + name: contentEncryptionAlgorithm.name, + iv: ivView + }, result, dataBuffer); + } + async stampDataWithPassword(parameters) { + if ((parameters instanceof Object) === false) + throw new Error("Parameters must have type \"Object\""); + ParameterError.assert(parameters, "password", "hashAlgorithm", "iterationCount", "salt", "contentToStamp"); + let length; + switch (parameters.hashAlgorithm.toLowerCase()) { + case "sha-1": + length = 160; + break; + case "sha-256": + length = 256; + break; + case "sha-384": + length = 384; + break; + case "sha-512": + length = 512; + break; + default: + throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${parameters.hashAlgorithm}`); + } + const hmacAlgorithm = { + name: "HMAC", + length, + hash: { + name: parameters.hashAlgorithm + } + }; + const pkcsKey = await makePKCS12B2Key(parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); + const hmacKey = await this.importKey("raw", new Uint8Array(pkcsKey), hmacAlgorithm, false, ["sign"]); + return this.sign(hmacAlgorithm, hmacKey, new Uint8Array(parameters.contentToStamp)); + } + async verifyDataStampedWithPassword(parameters) { + ParameterError.assert(parameters, "password", "hashAlgorithm", "salt", "iterationCount", "contentToVerify", "signatureToVerify"); + let length = 0; + switch (parameters.hashAlgorithm.toLowerCase()) { + case "sha-1": + length = 160; + break; + case "sha-256": + length = 256; + break; + case "sha-384": + length = 384; + break; + case "sha-512": + length = 512; + break; + default: + throw new Error(`Incorrect "parameters.hashAlgorithm" parameter: ${parameters.hashAlgorithm}`); + } + const hmacAlgorithm = { + name: "HMAC", + length, + hash: { + name: parameters.hashAlgorithm + } + }; + const pkcsKey = await makePKCS12B2Key(parameters.hashAlgorithm, length, parameters.password, parameters.salt, parameters.iterationCount); + const hmacKey = await this.importKey("raw", new Uint8Array(pkcsKey), hmacAlgorithm, false, ["verify"]); + return this.verify(hmacAlgorithm, hmacKey, new Uint8Array(parameters.signatureToVerify), new Uint8Array(parameters.contentToVerify)); + } + async getSignatureParameters(privateKey, hashAlgorithm = "SHA-1") { + this.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); + const signatureAlgorithm = new AlgorithmIdentifier(); + const parameters = this.getAlgorithmParameters(privateKey.algorithm.name, "sign"); + if (!Object.keys(parameters.algorithm).length) { + throw new Error("Parameter 'algorithm' is empty"); + } + const algorithm = parameters.algorithm; + if ("hash" in privateKey.algorithm && privateKey.algorithm.hash && privateKey.algorithm.hash.name) { + algorithm.hash.name = privateKey.algorithm.hash.name; + } + else { + algorithm.hash.name = hashAlgorithm; + } + switch (privateKey.algorithm.name.toUpperCase()) { + case "RSASSA-PKCS1-V1_5": + case "ECDSA": + signatureAlgorithm.algorithmId = this.getOIDByAlgorithm(algorithm, true); + break; + case "RSA-PSS": + { + switch (algorithm.hash.name.toUpperCase()) { + case "SHA-256": + algorithm.saltLength = 32; + break; + case "SHA-384": + algorithm.saltLength = 48; + break; + case "SHA-512": + algorithm.saltLength = 64; + break; + } + const paramsObject = {}; + if (algorithm.hash.name.toUpperCase() !== "SHA-1") { + const hashAlgorithmOID = this.getOIDByAlgorithm({ name: algorithm.hash.name }, true, "hashAlgorithm"); + paramsObject.hashAlgorithm = new AlgorithmIdentifier({ + algorithmId: hashAlgorithmOID, + algorithmParams: new Null() + }); + paramsObject.maskGenAlgorithm = new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.1.8", + algorithmParams: paramsObject.hashAlgorithm.toSchema() + }); + } + if (algorithm.saltLength !== 20) + paramsObject.saltLength = algorithm.saltLength; + const pssParameters = new RSASSAPSSParams(paramsObject); + signatureAlgorithm.algorithmId = "1.2.840.113549.1.1.10"; + signatureAlgorithm.algorithmParams = pssParameters.toSchema(); + } + break; + default: + throw new Error(`Unsupported signature algorithm: ${privateKey.algorithm.name}`); + } + return { + signatureAlgorithm, + parameters + }; + } + async signWithPrivateKey(data, privateKey, parameters) { + const signature = await this.sign(parameters.algorithm, privateKey, data); + if (parameters.algorithm.name === "ECDSA") { + return createCMSECDSASignature(signature); + } + return signature; + } + fillPublicKeyParameters(publicKeyInfo, signatureAlgorithm) { + const parameters = {}; + const shaAlgorithm = this.getHashAlgorithm(signatureAlgorithm); + if (shaAlgorithm === EMPTY_STRING) + throw new Error(`Unsupported signature algorithm: ${signatureAlgorithm.algorithmId}`); + let algorithmId; + if (signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.10") + algorithmId = signatureAlgorithm.algorithmId; + else + algorithmId = publicKeyInfo.algorithm.algorithmId; + const algorithmObject = this.getAlgorithmByOID(algorithmId, true); + parameters.algorithm = this.getAlgorithmParameters(algorithmObject.name, "importKey"); + if ("hash" in parameters.algorithm.algorithm) + parameters.algorithm.algorithm.hash.name = shaAlgorithm; + if (algorithmObject.name === "ECDSA") { + const publicKeyAlgorithm = publicKeyInfo.algorithm; + if (!publicKeyAlgorithm.algorithmParams) { + throw new Error("Algorithm parameters for ECDSA public key are missed"); + } + const publicKeyAlgorithmParams = publicKeyAlgorithm.algorithmParams; + if ("idBlock" in publicKeyAlgorithm.algorithmParams) { + if (!((publicKeyAlgorithmParams.idBlock.tagClass === 1) && (publicKeyAlgorithmParams.idBlock.tagNumber === 6))) { + throw new Error("Incorrect type for ECDSA public key parameters"); + } + } + const curveObject = this.getAlgorithmByOID(publicKeyAlgorithmParams.valueBlock.toString(), true); + parameters.algorithm.algorithm.namedCurve = curveObject.name; + } + return parameters; + } + async getPublicKey(publicKeyInfo, signatureAlgorithm, parameters) { + if (!parameters) { + parameters = this.fillPublicKeyParameters(publicKeyInfo, signatureAlgorithm); + } + const publicKeyInfoBuffer = publicKeyInfo.toSchema().toBER(false); + return this.importKey("spki", publicKeyInfoBuffer, parameters.algorithm.algorithm, true, parameters.algorithm.usages); + } + async verifyWithPublicKey(data, signature, publicKeyInfo, signatureAlgorithm, shaAlgorithm) { + let publicKey; + if (!shaAlgorithm) { + shaAlgorithm = this.getHashAlgorithm(signatureAlgorithm); + if (!shaAlgorithm) + throw new Error(`Unsupported signature algorithm: ${signatureAlgorithm.algorithmId}`); + publicKey = await this.getPublicKey(publicKeyInfo, signatureAlgorithm); + } + else { + const parameters = {}; + let algorithmId; + if (signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.10") + algorithmId = signatureAlgorithm.algorithmId; + else + algorithmId = publicKeyInfo.algorithm.algorithmId; + const algorithmObject = this.getAlgorithmByOID(algorithmId, true); + parameters.algorithm = this.getAlgorithmParameters(algorithmObject.name, "importKey"); + if ("hash" in parameters.algorithm.algorithm) + parameters.algorithm.algorithm.hash.name = shaAlgorithm; + if (algorithmObject.name === "ECDSA") { + let algorithmParamsChecked = false; + if (("algorithmParams" in publicKeyInfo.algorithm) === true) { + if ("idBlock" in publicKeyInfo.algorithm.algorithmParams) { + if ((publicKeyInfo.algorithm.algorithmParams.idBlock.tagClass === 1) && (publicKeyInfo.algorithm.algorithmParams.idBlock.tagNumber === 6)) + algorithmParamsChecked = true; + } + } + if (algorithmParamsChecked === false) { + throw new Error("Incorrect type for ECDSA public key parameters"); + } + const curveObject = this.getAlgorithmByOID(publicKeyInfo.algorithm.algorithmParams.valueBlock.toString(), true); + parameters.algorithm.algorithm.namedCurve = curveObject.name; + } + publicKey = await this.getPublicKey(publicKeyInfo, null, parameters); + } + const algorithm = this.getAlgorithmParameters(publicKey.algorithm.name, "verify"); + if ("hash" in algorithm.algorithm) + algorithm.algorithm.hash.name = shaAlgorithm; + let signatureValue = signature.valueBlock.valueHexView; + if (publicKey.algorithm.name === "ECDSA") { + const namedCurve = ECNamedCurves.find(publicKey.algorithm.namedCurve); + if (!namedCurve) { + throw new Error("Unsupported named curve in use"); + } + const asn1 = fromBER(signatureValue); + AsnError.assert(asn1, "Signature value"); + signatureValue = createECDSASignatureFromCMS(asn1.result, namedCurve.size); + } + if (publicKey.algorithm.name === "RSA-PSS") { + const pssParameters = new RSASSAPSSParams({ schema: signatureAlgorithm.algorithmParams }); + if ("saltLength" in pssParameters) + algorithm.algorithm.saltLength = pssParameters.saltLength; + else + algorithm.algorithm.saltLength = 20; + let hashAlgo = "SHA-1"; + if ("hashAlgorithm" in pssParameters) { + const hashAlgorithm = this.getAlgorithmByOID(pssParameters.hashAlgorithm.algorithmId, true); + hashAlgo = hashAlgorithm.name; + } + algorithm.algorithm.hash.name = hashAlgo; + } + return this.verify(algorithm.algorithm, publicKey, signatureValue, data); + } } -let engine = { - name: "none", - crypto: null, -}; -function isCryptoEngine(engine) { - return engine - && typeof engine === "object" - && "crypto" in engine - ? true - : false; -} -function setEngine(name, ...args) { - let crypto = null; - if (args.length < 2) { - if (args.length) { - crypto = args[0]; - } - else { - crypto = typeof self !== "undefined" && self.crypto ? new CryptoEngine({ name: "browser", crypto: self.crypto }) : null; - } - } - else { - const cryptoArg = args[0]; - const subtleArg = args[1]; - if (isCryptoEngine(subtleArg)) { - crypto = subtleArg; - } - else if (isCryptoEngine(cryptoArg)) { - crypto = cryptoArg; - } - else if ("subtle" in cryptoArg && "getRandomValues" in cryptoArg) { - crypto = new CryptoEngine({ - crypto: cryptoArg, - }); - } - } - if ((typeof process !== "undefined") && ("pid" in process) && (typeof global !== "undefined") && (typeof window === "undefined")) { - if (typeof global[process.pid] === "undefined") { - global[process.pid] = {}; - } - else { - if (typeof global[process.pid] !== "object") { - throw new Error(`Name global.${process.pid} already exists and it is not an object`); - } - } - if (typeof global[process.pid].pkijs === "undefined") { - global[process.pid].pkijs = {}; - } - else { - if (typeof global[process.pid].pkijs !== "object") { - throw new Error(`Name global.${process.pid}.pkijs already exists and it is not an object`); - } - } - global[process.pid].pkijs.engine = { - name: name, - crypto, - }; - } - else { - engine = { - name: name, - crypto, - }; - } -} -function getEngine() { - if ((typeof process !== "undefined") && ("pid" in process) && (typeof global !== "undefined") && (typeof window === "undefined")) { - let _engine; - try { - _engine = global[process.pid].pkijs.engine; - } - catch (ex) { - throw new Error("Please call 'setEngine' before call to 'getEngine'"); - } - return _engine; - } - return engine; -} -function getCrypto(safety = false) { - const _engine = getEngine(); - if (!_engine.crypto && safety) { - throw new Error("Unable to create WebCrypto object"); - } - return _engine.crypto; -} -function getRandomValues(view) { - return getCrypto(true).getRandomValues(view); -} -function getOIDByAlgorithm(algorithm, safety, target) { - return getCrypto(true).getOIDByAlgorithm(algorithm, safety, target); -} -function getAlgorithmParameters(algorithmName, operation) { - return getCrypto(true).getAlgorithmParameters(algorithmName, operation); -} -function createCMSECDSASignature(signatureBuffer) { - if ((signatureBuffer.byteLength % 2) !== 0) - return EMPTY_BUFFER; - const length = signatureBuffer.byteLength / 2; - const rBuffer = new ArrayBuffer(length); - const rView = new Uint8Array(rBuffer); - rView.set(new Uint8Array(signatureBuffer, 0, length)); - const rInteger = new Integer({ valueHex: rBuffer }); - const sBuffer = new ArrayBuffer(length); - const sView = new Uint8Array(sBuffer); - sView.set(new Uint8Array(signatureBuffer, length, length)); - const sInteger = new Integer({ valueHex: sBuffer }); - return (new Sequence({ - value: [ - rInteger.convertToDER(), - sInteger.convertToDER() - ] - })).toBER(false); -} -function createECDSASignatureFromCMS(cmsSignature, pointSize) { - if (!(cmsSignature instanceof Sequence - && cmsSignature.valueBlock.value.length === 2 - && cmsSignature.valueBlock.value[0] instanceof Integer - && cmsSignature.valueBlock.value[1] instanceof Integer)) - return EMPTY_BUFFER; - const rValueView = cmsSignature.valueBlock.value[0].convertFromDER().valueBlock.valueHexView; - const sValueView = cmsSignature.valueBlock.value[1].convertFromDER().valueBlock.valueHexView; - const res = new Uint8Array(pointSize * 2); - res.set(rValueView, pointSize - rValueView.byteLength); - res.set(sValueView, (2 * pointSize) - sValueView.byteLength); - return res.buffer; -} -function getAlgorithmByOID(oid, safety = false, target) { - return getCrypto(true).getAlgorithmByOID(oid, safety, target); -} -function getHashAlgorithm(signatureAlgorithm) { - return getCrypto(true).getHashAlgorithm(signatureAlgorithm); -} -function kdfWithCounter(hashFunction, zBuffer, Counter, SharedInfo, crypto) { - return __awaiter(this, void 0, void 0, function* () { - switch (hashFunction.toUpperCase()) { - case "SHA-1": - case "SHA-256": - case "SHA-384": - case "SHA-512": - break; - default: - throw new ArgumentError(`Unknown hash function: ${hashFunction}`); - } - ArgumentError.assert(zBuffer, "zBuffer", "ArrayBuffer"); - if (zBuffer.byteLength === 0) - throw new ArgumentError("'zBuffer' has zero length, error"); - ArgumentError.assert(SharedInfo, "SharedInfo", "ArrayBuffer"); - if (Counter > 255) - throw new ArgumentError("Please set 'Counter' argument to value less or equal to 255"); - const counterBuffer = new ArrayBuffer(4); - const counterView = new Uint8Array(counterBuffer); - counterView[0] = 0x00; - counterView[1] = 0x00; - counterView[2] = 0x00; - counterView[3] = Counter; - let combinedBuffer = EMPTY_BUFFER; - combinedBuffer = utilConcatBuf(combinedBuffer, zBuffer); - combinedBuffer = utilConcatBuf(combinedBuffer, counterBuffer); - combinedBuffer = utilConcatBuf(combinedBuffer, SharedInfo); - const result = yield crypto.digest({ name: hashFunction }, combinedBuffer); - return { - counter: Counter, - result - }; - }); -} -function kdf(hashFunction, Zbuffer, keydatalen, SharedInfo, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - let hashLength = 0; - let maxCounter = 1; - switch (hashFunction.toUpperCase()) { - case "SHA-1": - hashLength = 160; - break; - case "SHA-256": - hashLength = 256; - break; - case "SHA-384": - hashLength = 384; - break; - case "SHA-512": - hashLength = 512; - break; - default: - throw new ArgumentError(`Unknown hash function: ${hashFunction}`); - } - ArgumentError.assert(Zbuffer, "Zbuffer", "ArrayBuffer"); - if (Zbuffer.byteLength === 0) - throw new ArgumentError("'Zbuffer' has zero length, error"); - ArgumentError.assert(SharedInfo, "SharedInfo", "ArrayBuffer"); - const quotient = keydatalen / hashLength; - if (Math.floor(quotient) > 0) { - maxCounter = Math.floor(quotient); - if ((quotient - maxCounter) > 0) - maxCounter++; - } - const incomingResult = []; - for (let i = 1; i <= maxCounter; i++) - incomingResult.push(yield kdfWithCounter(hashFunction, Zbuffer, i, SharedInfo, crypto)); - let combinedBuffer = EMPTY_BUFFER; - let currentCounter = 1; - let found = true; - while (found) { - found = false; - for (const result of incomingResult) { - if (result.counter === currentCounter) { - combinedBuffer = utilConcatBuf(combinedBuffer, result.result); - found = true; - break; - } - } - currentCounter++; - } - keydatalen >>= 3; - if (combinedBuffer.byteLength > keydatalen) { - const newBuffer = new ArrayBuffer(keydatalen); - const newView = new Uint8Array(newBuffer); - const combinedView = new Uint8Array(combinedBuffer); - for (let i = 0; i < keydatalen; i++) - newView[i] = combinedView[i]; - return newBuffer; - } - return combinedBuffer; - }); +let engine = { + name: "none", + crypto: null, +}; +function isCryptoEngine(engine) { + return engine + && typeof engine === "object" + && "crypto" in engine + ? true + : false; +} +function setEngine(name, ...args) { + let crypto = null; + if (args.length < 2) { + if (args.length) { + crypto = args[0]; + } + else { + crypto = typeof self !== "undefined" && self.crypto ? new CryptoEngine({ name: "browser", crypto: self.crypto }) : null; + } + } + else { + const cryptoArg = args[0]; + const subtleArg = args[1]; + if (isCryptoEngine(subtleArg)) { + crypto = subtleArg; + } + else if (isCryptoEngine(cryptoArg)) { + crypto = cryptoArg; + } + else if ("subtle" in cryptoArg && "getRandomValues" in cryptoArg) { + crypto = new CryptoEngine({ + crypto: cryptoArg, + }); + } + } + if ((typeof process !== "undefined") && ("pid" in process) && (typeof global !== "undefined") && (typeof window === "undefined")) { + if (typeof global[process.pid] === "undefined") { + global[process.pid] = {}; + } + else { + if (typeof global[process.pid] !== "object") { + throw new Error(`Name global.${process.pid} already exists and it is not an object`); + } + } + if (typeof global[process.pid].pkijs === "undefined") { + global[process.pid].pkijs = {}; + } + else { + if (typeof global[process.pid].pkijs !== "object") { + throw new Error(`Name global.${process.pid}.pkijs already exists and it is not an object`); + } + } + global[process.pid].pkijs.engine = { + name: name, + crypto, + }; + } + else { + engine = { + name: name, + crypto, + }; + } +} +function getEngine() { + if ((typeof process !== "undefined") && ("pid" in process) && (typeof global !== "undefined") && (typeof window === "undefined")) { + let _engine; + try { + _engine = global[process.pid].pkijs.engine; + } + catch { + throw new Error("Please call 'setEngine' before call to 'getEngine'"); + } + return _engine; + } + return engine; +} +function getCrypto(safety = false) { + const _engine = getEngine(); + if (!_engine.crypto && safety) { + throw new Error("Unable to create WebCrypto object"); + } + return _engine.crypto; +} +function getRandomValues(view) { + return getCrypto(true).getRandomValues(view); +} +function getOIDByAlgorithm(algorithm, safety, target) { + return getCrypto(true).getOIDByAlgorithm(algorithm, safety, target); +} +function getAlgorithmParameters(algorithmName, operation) { + return getCrypto(true).getAlgorithmParameters(algorithmName, operation); +} +function createCMSECDSASignature(signatureBuffer) { + if ((signatureBuffer.byteLength % 2) !== 0) + return EMPTY_BUFFER; + const length = signatureBuffer.byteLength / 2; + const rBuffer = new ArrayBuffer(length); + const rView = new Uint8Array(rBuffer); + rView.set(new Uint8Array(signatureBuffer, 0, length)); + const rInteger = new Integer({ valueHex: rBuffer }); + const sBuffer = new ArrayBuffer(length); + const sView = new Uint8Array(sBuffer); + sView.set(new Uint8Array(signatureBuffer, length, length)); + const sInteger = new Integer({ valueHex: sBuffer }); + return (new Sequence({ + value: [ + rInteger.convertToDER(), + sInteger.convertToDER() + ] + })).toBER(false); +} +function createECDSASignatureFromCMS(cmsSignature, pointSize) { + if (!(cmsSignature instanceof Sequence + && cmsSignature.valueBlock.value.length === 2 + && cmsSignature.valueBlock.value[0] instanceof Integer + && cmsSignature.valueBlock.value[1] instanceof Integer)) + return EMPTY_BUFFER; + const rValueView = cmsSignature.valueBlock.value[0].convertFromDER().valueBlock.valueHexView; + const sValueView = cmsSignature.valueBlock.value[1].convertFromDER().valueBlock.valueHexView; + const res = new Uint8Array(pointSize * 2); + res.set(rValueView, pointSize - rValueView.byteLength); + res.set(sValueView, (2 * pointSize) - sValueView.byteLength); + return res.buffer; +} +function getAlgorithmByOID(oid, safety = false, target) { + return getCrypto(true).getAlgorithmByOID(oid, safety, target); +} +function getHashAlgorithm(signatureAlgorithm) { + return getCrypto(true).getHashAlgorithm(signatureAlgorithm); +} +async function kdfWithCounter(hashFunction, zBuffer, Counter, SharedInfo, crypto) { + switch (hashFunction.toUpperCase()) { + case "SHA-1": + case "SHA-256": + case "SHA-384": + case "SHA-512": + break; + default: + throw new ArgumentError(`Unknown hash function: ${hashFunction}`); + } + ArgumentError.assert(zBuffer, "zBuffer", "ArrayBuffer"); + if (zBuffer.byteLength === 0) + throw new ArgumentError("'zBuffer' has zero length, error"); + ArgumentError.assert(SharedInfo, "SharedInfo", "ArrayBuffer"); + if (Counter > 255) + throw new ArgumentError("Please set 'Counter' argument to value less or equal to 255"); + const counterBuffer = new ArrayBuffer(4); + const counterView = new Uint8Array(counterBuffer); + counterView[0] = 0x00; + counterView[1] = 0x00; + counterView[2] = 0x00; + counterView[3] = Counter; + let combinedBuffer = EMPTY_BUFFER; + combinedBuffer = utilConcatBuf(combinedBuffer, zBuffer); + combinedBuffer = utilConcatBuf(combinedBuffer, counterBuffer); + combinedBuffer = utilConcatBuf(combinedBuffer, SharedInfo); + const result = await crypto.digest({ name: hashFunction }, combinedBuffer); + return { + counter: Counter, + result + }; +} +async function kdf(hashFunction, Zbuffer, keydatalen, SharedInfo, crypto = getCrypto(true)) { + let hashLength = 0; + let maxCounter = 1; + switch (hashFunction.toUpperCase()) { + case "SHA-1": + hashLength = 160; + break; + case "SHA-256": + hashLength = 256; + break; + case "SHA-384": + hashLength = 384; + break; + case "SHA-512": + hashLength = 512; + break; + default: + throw new ArgumentError(`Unknown hash function: ${hashFunction}`); + } + ArgumentError.assert(Zbuffer, "Zbuffer", "ArrayBuffer"); + if (Zbuffer.byteLength === 0) + throw new ArgumentError("'Zbuffer' has zero length, error"); + ArgumentError.assert(SharedInfo, "SharedInfo", "ArrayBuffer"); + const quotient = keydatalen / hashLength; + if (Math.floor(quotient) > 0) { + maxCounter = Math.floor(quotient); + if ((quotient - maxCounter) > 0) + maxCounter++; + } + const incomingResult = []; + for (let i = 1; i <= maxCounter; i++) + incomingResult.push(await kdfWithCounter(hashFunction, Zbuffer, i, SharedInfo, crypto)); + let combinedBuffer = EMPTY_BUFFER; + let currentCounter = 1; + let found = true; + while (found) { + found = false; + for (const result of incomingResult) { + if (result.counter === currentCounter) { + combinedBuffer = utilConcatBuf(combinedBuffer, result.result); + found = true; + break; + } + } + currentCounter++; + } + keydatalen >>= 3; + if (combinedBuffer.byteLength > keydatalen) { + const newBuffer = new ArrayBuffer(keydatalen); + const newView = new Uint8Array(newBuffer); + const combinedView = new Uint8Array(combinedBuffer); + for (let i = 0; i < keydatalen; i++) + newView[i] = combinedView[i]; + return newBuffer; + } + return combinedBuffer; } -const VERSION$i = "version"; -const LOG_ID = "logID"; -const EXTENSIONS$6 = "extensions"; -const TIMESTAMP = "timestamp"; -const HASH_ALGORITHM$3 = "hashAlgorithm"; -const SIGNATURE_ALGORITHM$8 = "signatureAlgorithm"; -const SIGNATURE$7 = "signature"; -const NONE = "none"; -const MD5 = "md5"; -const SHA1 = "sha1"; -const SHA224 = "sha224"; -const SHA256 = "sha256"; -const SHA384 = "sha384"; -const SHA512 = "sha512"; -const ANONYMOUS = "anonymous"; -const RSA = "rsa"; -const DSA = "dsa"; -const ECDSA = "ecdsa"; -class SignedCertificateTimestamp extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$i, SignedCertificateTimestamp.defaultValues(VERSION$i)); - this.logID = getParametersValue(parameters, LOG_ID, SignedCertificateTimestamp.defaultValues(LOG_ID)); - this.timestamp = getParametersValue(parameters, TIMESTAMP, SignedCertificateTimestamp.defaultValues(TIMESTAMP)); - this.extensions = getParametersValue(parameters, EXTENSIONS$6, SignedCertificateTimestamp.defaultValues(EXTENSIONS$6)); - this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$3, SignedCertificateTimestamp.defaultValues(HASH_ALGORITHM$3)); - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$8, SignedCertificateTimestamp.defaultValues(SIGNATURE_ALGORITHM$8)); - this.signature = getParametersValue(parameters, SIGNATURE$7, SignedCertificateTimestamp.defaultValues(SIGNATURE$7)); - if ("stream" in parameters && parameters.stream) { - this.fromStream(parameters.stream); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$i: - return 0; - case LOG_ID: - case EXTENSIONS$6: - return EMPTY_BUFFER; - case TIMESTAMP: - return new Date(0); - case HASH_ALGORITHM$3: - case SIGNATURE_ALGORITHM$8: - return EMPTY_STRING; - case SIGNATURE$7: - return new Any(); - default: - return super.defaultValues(memberName); - } - } - fromSchema(schema) { - if ((schema instanceof RawData) === false) - throw new Error("Object's schema was not verified against input data for SignedCertificateTimestamp"); - const seqStream = new SeqStream({ - stream: new ByteStream({ - buffer: schema.data - }) - }); - this.fromStream(seqStream); - } - fromStream(stream) { - const blockLength = stream.getUint16(); - this.version = (stream.getBlock(1))[0]; - if (this.version === 0) { - this.logID = (new Uint8Array(stream.getBlock(32))).buffer.slice(0); - this.timestamp = new Date(utilFromBase(new Uint8Array(stream.getBlock(8)), 8)); - const extensionsLength = stream.getUint16(); - this.extensions = (new Uint8Array(stream.getBlock(extensionsLength))).buffer.slice(0); - switch ((stream.getBlock(1))[0]) { - case 0: - this.hashAlgorithm = NONE; - break; - case 1: - this.hashAlgorithm = MD5; - break; - case 2: - this.hashAlgorithm = SHA1; - break; - case 3: - this.hashAlgorithm = SHA224; - break; - case 4: - this.hashAlgorithm = SHA256; - break; - case 5: - this.hashAlgorithm = SHA384; - break; - case 6: - this.hashAlgorithm = SHA512; - break; - default: - throw new Error("Object's stream was not correct for SignedCertificateTimestamp"); - } - switch ((stream.getBlock(1))[0]) { - case 0: - this.signatureAlgorithm = ANONYMOUS; - break; - case 1: - this.signatureAlgorithm = RSA; - break; - case 2: - this.signatureAlgorithm = DSA; - break; - case 3: - this.signatureAlgorithm = ECDSA; - break; - default: - throw new Error("Object's stream was not correct for SignedCertificateTimestamp"); - } - const signatureLength = stream.getUint16(); - const signatureData = new Uint8Array(stream.getBlock(signatureLength)).buffer.slice(0); - const asn1 = fromBER(signatureData); - AsnError.assert(asn1, "SignedCertificateTimestamp"); - this.signature = asn1.result; - if (blockLength !== (47 + extensionsLength + signatureLength)) { - throw new Error("Object's stream was not correct for SignedCertificateTimestamp"); - } - } - } - toSchema() { - const stream = this.toStream(); - return new RawData({ data: stream.stream.buffer }); - } - toStream() { - const stream = new SeqStream(); - stream.appendUint16(47 + this.extensions.byteLength + this.signature.valueBeforeDecodeView.byteLength); - stream.appendChar(this.version); - stream.appendView(new Uint8Array(this.logID)); - const timeBuffer = new ArrayBuffer(8); - const timeView = new Uint8Array(timeBuffer); - const baseArray = utilToBase(this.timestamp.valueOf(), 8); - timeView.set(new Uint8Array(baseArray), 8 - baseArray.byteLength); - stream.appendView(timeView); - stream.appendUint16(this.extensions.byteLength); - if (this.extensions.byteLength) - stream.appendView(new Uint8Array(this.extensions)); - let _hashAlgorithm; - switch (this.hashAlgorithm.toLowerCase()) { - case NONE: - _hashAlgorithm = 0; - break; - case MD5: - _hashAlgorithm = 1; - break; - case SHA1: - _hashAlgorithm = 2; - break; - case SHA224: - _hashAlgorithm = 3; - break; - case SHA256: - _hashAlgorithm = 4; - break; - case SHA384: - _hashAlgorithm = 5; - break; - case SHA512: - _hashAlgorithm = 6; - break; - default: - throw new Error(`Incorrect data for hashAlgorithm: ${this.hashAlgorithm}`); - } - stream.appendChar(_hashAlgorithm); - let _signatureAlgorithm; - switch (this.signatureAlgorithm.toLowerCase()) { - case ANONYMOUS: - _signatureAlgorithm = 0; - break; - case RSA: - _signatureAlgorithm = 1; - break; - case DSA: - _signatureAlgorithm = 2; - break; - case ECDSA: - _signatureAlgorithm = 3; - break; - default: - throw new Error(`Incorrect data for signatureAlgorithm: ${this.signatureAlgorithm}`); - } - stream.appendChar(_signatureAlgorithm); - const _signature = this.signature.toBER(false); - stream.appendUint16(_signature.byteLength); - stream.appendView(new Uint8Array(_signature)); - return stream; - } - toJSON() { - return { - version: this.version, - logID: bufferToHexCodes(this.logID), - timestamp: this.timestamp, - extensions: bufferToHexCodes(this.extensions), - hashAlgorithm: this.hashAlgorithm, - signatureAlgorithm: this.signatureAlgorithm, - signature: this.signature.toJSON() - }; - } - verify(logs, data, dataType = 0, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const logId = toBase64(arrayBufferToString(this.logID)); - let publicKeyBase64 = null; - const stream = new SeqStream(); - for (const log of logs) { - if (log.log_id === logId) { - publicKeyBase64 = log.key; - break; - } - } - if (!publicKeyBase64) { - throw new Error(`Public key not found for CT with logId: ${logId}`); - } - const pki = stringToArrayBuffer(fromBase64(publicKeyBase64)); - const publicKeyInfo = PublicKeyInfo.fromBER(pki); - stream.appendChar(0x00); - stream.appendChar(0x00); - const timeBuffer = new ArrayBuffer(8); - const timeView = new Uint8Array(timeBuffer); - const baseArray = utilToBase(this.timestamp.valueOf(), 8); - timeView.set(new Uint8Array(baseArray), 8 - baseArray.byteLength); - stream.appendView(timeView); - stream.appendUint16(dataType); - if (dataType === 0) - stream.appendUint24(data.byteLength); - stream.appendView(new Uint8Array(data)); - stream.appendUint16(this.extensions.byteLength); - if (this.extensions.byteLength !== 0) - stream.appendView(new Uint8Array(this.extensions)); - return crypto.verifyWithPublicKey(stream.buffer.slice(0, stream.length), new OctetString({ valueHex: this.signature.toBER(false) }), publicKeyInfo, { algorithmId: EMPTY_STRING }, "SHA-256"); - }); - } -} -SignedCertificateTimestamp.CLASS_NAME = "SignedCertificateTimestamp"; -function verifySCTsForCertificate(certificate, issuerCertificate, logs, index = (-1), crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - let parsedValue = null; - const stream = new SeqStream(); - for (let i = 0; certificate.extensions && i < certificate.extensions.length; i++) { - switch (certificate.extensions[i].extnID) { - case id_SignedCertificateTimestampList: - { - parsedValue = certificate.extensions[i].parsedValue; - if (!parsedValue || parsedValue.timestamps.length === 0) - throw new Error("Nothing to verify in the certificate"); - certificate.extensions.splice(i, 1); - } - break; - } - } - if (parsedValue === null) - throw new Error("No SignedCertificateTimestampList extension in the specified certificate"); - const tbs = certificate.encodeTBS().toBER(); - const issuerId = yield crypto.digest({ name: "SHA-256" }, new Uint8Array(issuerCertificate.subjectPublicKeyInfo.toSchema().toBER(false))); - stream.appendView(new Uint8Array(issuerId)); - stream.appendUint24(tbs.byteLength); - stream.appendView(new Uint8Array(tbs)); - const preCert = stream.stream.slice(0, stream.length); - if (index === (-1)) { - const verifyArray = []; - for (const timestamp of parsedValue.timestamps) { - const verifyResult = yield timestamp.verify(logs, preCert.buffer, 1, crypto); - verifyArray.push(verifyResult); - } - return verifyArray; - } - if (index >= parsedValue.timestamps.length) - index = (parsedValue.timestamps.length - 1); - return [yield parsedValue.timestamps[index].verify(logs, preCert.buffer, 1, crypto)]; - }); +const VERSION$i = "version"; +const LOG_ID = "logID"; +const EXTENSIONS$6 = "extensions"; +const TIMESTAMP = "timestamp"; +const HASH_ALGORITHM$3 = "hashAlgorithm"; +const SIGNATURE_ALGORITHM$8 = "signatureAlgorithm"; +const SIGNATURE$7 = "signature"; +const NONE = "none"; +const MD5 = "md5"; +const SHA1 = "sha1"; +const SHA224 = "sha224"; +const SHA256 = "sha256"; +const SHA384 = "sha384"; +const SHA512 = "sha512"; +const ANONYMOUS = "anonymous"; +const RSA = "rsa"; +const DSA = "dsa"; +const ECDSA = "ecdsa"; +class SignedCertificateTimestamp extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$i, SignedCertificateTimestamp.defaultValues(VERSION$i)); + this.logID = getParametersValue(parameters, LOG_ID, SignedCertificateTimestamp.defaultValues(LOG_ID)); + this.timestamp = getParametersValue(parameters, TIMESTAMP, SignedCertificateTimestamp.defaultValues(TIMESTAMP)); + this.extensions = getParametersValue(parameters, EXTENSIONS$6, SignedCertificateTimestamp.defaultValues(EXTENSIONS$6)); + this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$3, SignedCertificateTimestamp.defaultValues(HASH_ALGORITHM$3)); + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$8, SignedCertificateTimestamp.defaultValues(SIGNATURE_ALGORITHM$8)); + this.signature = getParametersValue(parameters, SIGNATURE$7, SignedCertificateTimestamp.defaultValues(SIGNATURE$7)); + if ("stream" in parameters && parameters.stream) { + this.fromStream(parameters.stream); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$i: + return 0; + case LOG_ID: + case EXTENSIONS$6: + return EMPTY_BUFFER; + case TIMESTAMP: + return new Date(0); + case HASH_ALGORITHM$3: + case SIGNATURE_ALGORITHM$8: + return EMPTY_STRING; + case SIGNATURE$7: + return EMPTY_BUFFER; + default: + return super.defaultValues(memberName); + } + } + fromSchema(schema) { + if ((schema instanceof RawData) === false) + throw new Error("Object's schema was not verified against input data for SignedCertificateTimestamp"); + const seqStream = new SeqStream({ + stream: new ByteStream({ + buffer: schema.data + }) + }); + this.fromStream(seqStream); + } + fromStream(stream) { + const blockLength = stream.getUint16(); + this.version = (stream.getBlock(1))[0]; + if (this.version === 0) { + this.logID = (new Uint8Array(stream.getBlock(32))).buffer.slice(0); + this.timestamp = new Date(utilFromBase(new Uint8Array(stream.getBlock(8)), 8)); + const extensionsLength = stream.getUint16(); + this.extensions = (new Uint8Array(stream.getBlock(extensionsLength))).buffer.slice(0); + switch ((stream.getBlock(1))[0]) { + case 0: + this.hashAlgorithm = NONE; + break; + case 1: + this.hashAlgorithm = MD5; + break; + case 2: + this.hashAlgorithm = SHA1; + break; + case 3: + this.hashAlgorithm = SHA224; + break; + case 4: + this.hashAlgorithm = SHA256; + break; + case 5: + this.hashAlgorithm = SHA384; + break; + case 6: + this.hashAlgorithm = SHA512; + break; + default: + throw new Error("Object's stream was not correct for SignedCertificateTimestamp"); + } + switch ((stream.getBlock(1))[0]) { + case 0: + this.signatureAlgorithm = ANONYMOUS; + break; + case 1: + this.signatureAlgorithm = RSA; + break; + case 2: + this.signatureAlgorithm = DSA; + break; + case 3: + this.signatureAlgorithm = ECDSA; + break; + default: + throw new Error("Object's stream was not correct for SignedCertificateTimestamp"); + } + const signatureLength = stream.getUint16(); + this.signature = new Uint8Array(stream.getBlock(signatureLength)).buffer.slice(0); + if (blockLength !== (47 + extensionsLength + signatureLength)) { + throw new Error("Object's stream was not correct for SignedCertificateTimestamp"); + } + } + } + toSchema() { + const stream = this.toStream(); + return new RawData({ data: stream.stream.buffer }); + } + toStream() { + const stream = new SeqStream(); + stream.appendUint16(47 + this.extensions.byteLength + this.signature.byteLength); + stream.appendChar(this.version); + stream.appendView(new Uint8Array(this.logID)); + const timeBuffer = new ArrayBuffer(8); + const timeView = new Uint8Array(timeBuffer); + const baseArray = utilToBase(this.timestamp.valueOf(), 8); + timeView.set(new Uint8Array(baseArray), 8 - baseArray.byteLength); + stream.appendView(timeView); + stream.appendUint16(this.extensions.byteLength); + if (this.extensions.byteLength) + stream.appendView(new Uint8Array(this.extensions)); + let _hashAlgorithm; + switch (this.hashAlgorithm.toLowerCase()) { + case NONE: + _hashAlgorithm = 0; + break; + case MD5: + _hashAlgorithm = 1; + break; + case SHA1: + _hashAlgorithm = 2; + break; + case SHA224: + _hashAlgorithm = 3; + break; + case SHA256: + _hashAlgorithm = 4; + break; + case SHA384: + _hashAlgorithm = 5; + break; + case SHA512: + _hashAlgorithm = 6; + break; + default: + throw new Error(`Incorrect data for hashAlgorithm: ${this.hashAlgorithm}`); + } + stream.appendChar(_hashAlgorithm); + let _signatureAlgorithm; + switch (this.signatureAlgorithm.toLowerCase()) { + case ANONYMOUS: + _signatureAlgorithm = 0; + break; + case RSA: + _signatureAlgorithm = 1; + break; + case DSA: + _signatureAlgorithm = 2; + break; + case ECDSA: + _signatureAlgorithm = 3; + break; + default: + throw new Error(`Incorrect data for signatureAlgorithm: ${this.signatureAlgorithm}`); + } + stream.appendChar(_signatureAlgorithm); + stream.appendUint16(this.signature.byteLength); + stream.appendView(new Uint8Array(this.signature)); + return stream; + } + toJSON() { + return { + version: this.version, + logID: bufferToHexCodes(this.logID), + timestamp: this.timestamp, + extensions: bufferToHexCodes(this.extensions), + hashAlgorithm: this.hashAlgorithm, + signatureAlgorithm: this.signatureAlgorithm, + signature: bufferToHexCodes(this.signature), + }; + } + async verify(logs, data, dataType = 0, crypto = getCrypto(true)) { + const logId = toBase64(arrayBufferToString(this.logID)); + let publicKeyBase64 = null; + const stream = new SeqStream(); + for (const log of logs) { + if (log.log_id === logId) { + publicKeyBase64 = log.key; + break; + } + } + if (!publicKeyBase64) { + throw new Error(`Public key not found for CT with logId: ${logId}`); + } + const pki = stringToArrayBuffer(fromBase64(publicKeyBase64)); + const publicKeyInfo = PublicKeyInfo.fromBER(pki); + stream.appendChar(0x00); + stream.appendChar(0x00); + const timeBuffer = new ArrayBuffer(8); + const timeView = new Uint8Array(timeBuffer); + const baseArray = utilToBase(this.timestamp.valueOf(), 8); + timeView.set(new Uint8Array(baseArray), 8 - baseArray.byteLength); + stream.appendView(timeView); + stream.appendUint16(dataType); + if (dataType === 0) + stream.appendUint24(data.byteLength); + stream.appendView(new Uint8Array(data)); + stream.appendUint16(this.extensions.byteLength); + if (this.extensions.byteLength !== 0) + stream.appendView(new Uint8Array(this.extensions)); + return crypto.verifyWithPublicKey(stream.buffer.slice(0, stream.length), new OctetString({ valueHex: this.signature }), publicKeyInfo, { algorithmId: EMPTY_STRING }, "SHA-256"); + } +} +SignedCertificateTimestamp.CLASS_NAME = "SignedCertificateTimestamp"; +async function verifySCTsForCertificate(certificate, issuerCertificate, logs, index = (-1), crypto = getCrypto(true)) { + let parsedValue = null; + const stream = new SeqStream(); + if (certificate.extensions) { + for (let i = certificate.extensions.length - 1; i >= 0; i--) { + switch (certificate.extensions[i].extnID) { + case id_SignedCertificateTimestampList: + { + parsedValue = certificate.extensions[i].parsedValue; + if (!parsedValue || parsedValue.timestamps.length === 0) + throw new Error("Nothing to verify in the certificate"); + certificate.extensions.splice(i, 1); + } + break; + } + } + } + if (parsedValue === null) + throw new Error("No SignedCertificateTimestampList extension in the specified certificate"); + const tbs = certificate.encodeTBS().toBER(); + const issuerId = await crypto.digest({ name: "SHA-256" }, new Uint8Array(issuerCertificate.subjectPublicKeyInfo.toSchema().toBER(false))); + stream.appendView(new Uint8Array(issuerId)); + stream.appendUint24(tbs.byteLength); + stream.appendView(new Uint8Array(tbs)); + const preCert = stream.stream.slice(0, stream.length); + if (index === (-1)) { + const verifyArray = []; + for (const timestamp of parsedValue.timestamps) { + const verifyResult = await timestamp.verify(logs, preCert.buffer, 1, crypto); + verifyArray.push(verifyResult); + } + return verifyArray; + } + if (index >= parsedValue.timestamps.length) + index = (parsedValue.timestamps.length - 1); + return [await parsedValue.timestamps[index].verify(logs, preCert.buffer, 1, crypto)]; } -const TIMESTAMPS = "timestamps"; -class SignedCertificateTimestampList extends PkiObject { - constructor(parameters = {}) { - super(); - this.timestamps = getParametersValue(parameters, TIMESTAMPS, SignedCertificateTimestampList.defaultValues(TIMESTAMPS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TIMESTAMPS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TIMESTAMPS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - var _a; - const names = getParametersValue(parameters, "names", {}); - (_a = names.optional) !== null && _a !== void 0 ? _a : (names.optional = false); - return (new OctetString({ - name: (names.blockName || "SignedCertificateTimestampList"), - optional: names.optional - })); - } - fromSchema(schema) { - if ((schema instanceof OctetString) === false) { - throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList"); - } - const seqStream = new SeqStream({ - stream: new ByteStream({ - buffer: schema.valueBlock.valueHex - }) - }); - const dataLength = seqStream.getUint16(); - if (dataLength !== seqStream.length) { - throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList"); - } - while (seqStream.length) { - this.timestamps.push(new SignedCertificateTimestamp({ stream: seqStream })); - } - } - toSchema() { - const stream = new SeqStream(); - let overallLength = 0; - const timestampsData = []; - for (const timestamp of this.timestamps) { - const timestampStream = timestamp.toStream(); - timestampsData.push(timestampStream); - overallLength += timestampStream.stream.buffer.byteLength; - } - stream.appendUint16(overallLength); - for (const timestamp of timestampsData) { - stream.appendView(timestamp.stream.view); - } - return new OctetString({ valueHex: stream.stream.buffer.slice(0) }); - } - toJSON() { - return { - timestamps: Array.from(this.timestamps, o => o.toJSON()) - }; - } -} +const TIMESTAMPS = "timestamps"; +class SignedCertificateTimestampList extends PkiObject { + constructor(parameters = {}) { + super(); + this.timestamps = getParametersValue(parameters, TIMESTAMPS, SignedCertificateTimestampList.defaultValues(TIMESTAMPS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TIMESTAMPS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TIMESTAMPS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + var _a; + const names = getParametersValue(parameters, "names", {}); + (_a = names.optional) !== null && _a !== void 0 ? _a : (names.optional = false); + return (new OctetString({ + name: (names.blockName || "SignedCertificateTimestampList"), + optional: names.optional + })); + } + fromSchema(schema) { + if ((schema instanceof OctetString) === false) { + throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList"); + } + const seqStream = new SeqStream({ + stream: new ByteStream({ + buffer: schema.valueBlock.valueHex + }) + }); + const dataLength = seqStream.getUint16(); + if (dataLength !== seqStream.length) { + throw new Error("Object's schema was not verified against input data for SignedCertificateTimestampList"); + } + while (seqStream.length) { + this.timestamps.push(new SignedCertificateTimestamp({ stream: seqStream })); + } + } + toSchema() { + const stream = new SeqStream(); + let overallLength = 0; + const timestampsData = []; + for (const timestamp of this.timestamps) { + const timestampStream = timestamp.toStream(); + timestampsData.push(timestampStream); + overallLength += timestampStream.stream.buffer.byteLength; + } + stream.appendUint16(overallLength); + for (const timestamp of timestampsData) { + stream.appendView(timestamp.stream.view); + } + return new OctetString({ valueHex: stream.stream.buffer.slice(0) }); + } + toJSON() { + return { + timestamps: Array.from(this.timestamps, o => o.toJSON()) + }; + } +} SignedCertificateTimestampList.CLASS_NAME = "SignedCertificateTimestampList"; -const ATTRIBUTES$4 = "attributes"; -const CLEAR_PROPS$11 = [ - ATTRIBUTES$4 -]; -class SubjectDirectoryAttributes extends PkiObject { - constructor(parameters = {}) { - super(); - this.attributes = getParametersValue(parameters, ATTRIBUTES$4, SubjectDirectoryAttributes.defaultValues(ATTRIBUTES$4)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ATTRIBUTES$4: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.attributes || EMPTY_STRING), - value: Attribute.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$11); - const asn1 = compareSchema(schema, schema, SubjectDirectoryAttributes.schema({ - names: { - attributes: ATTRIBUTES$4 - } - })); - AsnError.assertSchema(asn1, this.className); - this.attributes = Array.from(asn1.result.attributes, element => new Attribute({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.attributes, o => o.toSchema()) - })); - } - toJSON() { - return { - attributes: Array.from(this.attributes, o => o.toJSON()) - }; - } -} +const ATTRIBUTES$4 = "attributes"; +const CLEAR_PROPS$11 = [ + ATTRIBUTES$4 +]; +class SubjectDirectoryAttributes extends PkiObject { + constructor(parameters = {}) { + super(); + this.attributes = getParametersValue(parameters, ATTRIBUTES$4, SubjectDirectoryAttributes.defaultValues(ATTRIBUTES$4)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ATTRIBUTES$4: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.attributes || EMPTY_STRING), + value: Attribute.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$11); + const asn1 = compareSchema(schema, schema, SubjectDirectoryAttributes.schema({ + names: { + attributes: ATTRIBUTES$4 + } + })); + AsnError.assertSchema(asn1, this.className); + this.attributes = Array.from(asn1.result.attributes, element => new Attribute({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.attributes, o => o.toSchema()) + })); + } + toJSON() { + return { + attributes: Array.from(this.attributes, o => o.toJSON()) + }; + } +} SubjectDirectoryAttributes.CLASS_NAME = "SubjectDirectoryAttributes"; -class ExtensionValueFactory { - static getItems() { - if (!this.types) { - this.types = {}; - ExtensionValueFactory.register(id_SubjectAltName, "SubjectAltName", AltName); - ExtensionValueFactory.register(id_IssuerAltName, "IssuerAltName", AltName); - ExtensionValueFactory.register(id_AuthorityKeyIdentifier, "AuthorityKeyIdentifier", AuthorityKeyIdentifier); - ExtensionValueFactory.register(id_BasicConstraints, "BasicConstraints", BasicConstraints); - ExtensionValueFactory.register(id_MicrosoftCaVersion, "MicrosoftCaVersion", CAVersion); - ExtensionValueFactory.register(id_CertificatePolicies, "CertificatePolicies", CertificatePolicies); - ExtensionValueFactory.register(id_MicrosoftAppPolicies, "CertificatePoliciesMicrosoft", CertificatePolicies); - ExtensionValueFactory.register(id_MicrosoftCertTemplateV2, "MicrosoftCertTemplateV2", CertificateTemplate); - ExtensionValueFactory.register(id_CRLDistributionPoints, "CRLDistributionPoints", CRLDistributionPoints); - ExtensionValueFactory.register(id_FreshestCRL, "FreshestCRL", CRLDistributionPoints); - ExtensionValueFactory.register(id_ExtKeyUsage, "ExtKeyUsage", ExtKeyUsage); - ExtensionValueFactory.register(id_CertificateIssuer, "CertificateIssuer", GeneralNames); - ExtensionValueFactory.register(id_AuthorityInfoAccess, "AuthorityInfoAccess", InfoAccess); - ExtensionValueFactory.register(id_SubjectInfoAccess, "SubjectInfoAccess", InfoAccess); - ExtensionValueFactory.register(id_IssuingDistributionPoint, "IssuingDistributionPoint", IssuingDistributionPoint); - ExtensionValueFactory.register(id_NameConstraints, "NameConstraints", NameConstraints); - ExtensionValueFactory.register(id_PolicyConstraints, "PolicyConstraints", PolicyConstraints); - ExtensionValueFactory.register(id_PolicyMappings, "PolicyMappings", PolicyMappings); - ExtensionValueFactory.register(id_PrivateKeyUsagePeriod, "PrivateKeyUsagePeriod", PrivateKeyUsagePeriod); - ExtensionValueFactory.register(id_QCStatements, "QCStatements", QCStatements); - ExtensionValueFactory.register(id_SignedCertificateTimestampList, "SignedCertificateTimestampList", SignedCertificateTimestampList); - ExtensionValueFactory.register(id_SubjectDirectoryAttributes, "SubjectDirectoryAttributes", SubjectDirectoryAttributes); - } - return this.types; - } - static fromBER(id, raw) { - const asn1 = fromBER(raw); - if (asn1.offset === -1) { - return null; - } - const item = this.find(id); - if (item) { - try { - return new item.type({ schema: asn1.result }); - } - catch (ex) { - const res = new item.type(); - res.parsingError = `Incorrectly formatted value of extension ${item.name} (${id})`; - return res; - } - } - return asn1.result; - } - static find(id) { - const types = this.getItems(); - return types[id] || null; - } - static register(id, name, type) { - this.getItems()[id] = { name, type }; - } +class ExtensionValueFactory { + static getItems() { + if (!this.types) { + this.types = {}; + ExtensionValueFactory.register(id_SubjectAltName, "SubjectAltName", AltName); + ExtensionValueFactory.register(id_IssuerAltName, "IssuerAltName", AltName); + ExtensionValueFactory.register(id_AuthorityKeyIdentifier, "AuthorityKeyIdentifier", AuthorityKeyIdentifier); + ExtensionValueFactory.register(id_BasicConstraints, "BasicConstraints", BasicConstraints); + ExtensionValueFactory.register(id_MicrosoftCaVersion, "MicrosoftCaVersion", CAVersion); + ExtensionValueFactory.register(id_CertificatePolicies, "CertificatePolicies", CertificatePolicies); + ExtensionValueFactory.register(id_MicrosoftAppPolicies, "CertificatePoliciesMicrosoft", CertificatePolicies); + ExtensionValueFactory.register(id_MicrosoftCertTemplateV2, "MicrosoftCertTemplateV2", CertificateTemplate); + ExtensionValueFactory.register(id_CRLDistributionPoints, "CRLDistributionPoints", CRLDistributionPoints); + ExtensionValueFactory.register(id_FreshestCRL, "FreshestCRL", CRLDistributionPoints); + ExtensionValueFactory.register(id_ExtKeyUsage, "ExtKeyUsage", ExtKeyUsage); + ExtensionValueFactory.register(id_CertificateIssuer, "CertificateIssuer", GeneralNames); + ExtensionValueFactory.register(id_AuthorityInfoAccess, "AuthorityInfoAccess", InfoAccess); + ExtensionValueFactory.register(id_SubjectInfoAccess, "SubjectInfoAccess", InfoAccess); + ExtensionValueFactory.register(id_IssuingDistributionPoint, "IssuingDistributionPoint", IssuingDistributionPoint); + ExtensionValueFactory.register(id_NameConstraints, "NameConstraints", NameConstraints); + ExtensionValueFactory.register(id_PolicyConstraints, "PolicyConstraints", PolicyConstraints); + ExtensionValueFactory.register(id_PolicyMappings, "PolicyMappings", PolicyMappings); + ExtensionValueFactory.register(id_PrivateKeyUsagePeriod, "PrivateKeyUsagePeriod", PrivateKeyUsagePeriod); + ExtensionValueFactory.register(id_QCStatements, "QCStatements", QCStatements); + ExtensionValueFactory.register(id_SignedCertificateTimestampList, "SignedCertificateTimestampList", SignedCertificateTimestampList); + ExtensionValueFactory.register(id_SubjectDirectoryAttributes, "SubjectDirectoryAttributes", SubjectDirectoryAttributes); + } + return this.types; + } + static fromBER(id, raw) { + const asn1 = fromBER(raw); + if (asn1.offset === -1) { + return null; + } + const item = this.find(id); + if (item) { + try { + return new item.type({ schema: asn1.result }); + } + catch { + const res = new item.type(); + res.parsingError = `Incorrectly formatted value of extension ${item.name} (${id})`; + return res; + } + } + return asn1.result; + } + static find(id) { + const types = this.getItems(); + return types[id] || null; + } + static register(id, name, type) { + this.getItems()[id] = { name, type }; + } } -const EXTN_ID = "extnID"; -const CRITICAL = "critical"; -const EXTN_VALUE = "extnValue"; -const PARSED_VALUE$5 = "parsedValue"; -const CLEAR_PROPS$10 = [ - EXTN_ID, - CRITICAL, - EXTN_VALUE -]; -class Extension extends PkiObject { - constructor(parameters = {}) { - super(); - this.extnID = getParametersValue(parameters, EXTN_ID, Extension.defaultValues(EXTN_ID)); - this.critical = getParametersValue(parameters, CRITICAL, Extension.defaultValues(CRITICAL)); - if (EXTN_VALUE in parameters) { - this.extnValue = new OctetString({ valueHex: parameters.extnValue }); - } - else { - this.extnValue = Extension.defaultValues(EXTN_VALUE); - } - if (PARSED_VALUE$5 in parameters) { - this.parsedValue = getParametersValue(parameters, PARSED_VALUE$5, Extension.defaultValues(PARSED_VALUE$5)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - get parsedValue() { - if (this._parsedValue === undefined) { - const parsedValue = ExtensionValueFactory.fromBER(this.extnID, this.extnValue.valueBlock.valueHexView); - this._parsedValue = parsedValue; - } - return this._parsedValue || undefined; - } - set parsedValue(value) { - this._parsedValue = value; - } - static defaultValues(memberName) { - switch (memberName) { - case EXTN_ID: - return EMPTY_STRING; - case CRITICAL: - return false; - case EXTN_VALUE: - return new OctetString(); - case PARSED_VALUE$5: - return {}; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.extnID || EMPTY_STRING) }), - new Boolean({ - name: (names.critical || EMPTY_STRING), - optional: true - }), - new OctetString({ name: (names.extnValue || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$10); - const asn1 = compareSchema(schema, schema, Extension.schema({ - names: { - extnID: EXTN_ID, - critical: CRITICAL, - extnValue: EXTN_VALUE - } - })); - AsnError.assertSchema(asn1, this.className); - this.extnID = asn1.result.extnID.valueBlock.toString(); - if (CRITICAL in asn1.result) { - this.critical = asn1.result.critical.valueBlock.value; - } - this.extnValue = asn1.result.extnValue; - } - toSchema() { - const outputArray = []; - outputArray.push(new ObjectIdentifier({ value: this.extnID })); - if (this.critical !== Extension.defaultValues(CRITICAL)) { - outputArray.push(new Boolean({ value: this.critical })); - } - outputArray.push(this.extnValue); - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const object = { - extnID: this.extnID, - extnValue: this.extnValue.toJSON(), - }; - if (this.critical !== Extension.defaultValues(CRITICAL)) { - object.critical = this.critical; - } - if (this.parsedValue && this.parsedValue.toJSON) { - object.parsedValue = this.parsedValue.toJSON(); - } - return object; - } -} +const EXTN_ID = "extnID"; +const CRITICAL = "critical"; +const EXTN_VALUE = "extnValue"; +const PARSED_VALUE$5 = "parsedValue"; +const CLEAR_PROPS$10 = [ + EXTN_ID, + CRITICAL, + EXTN_VALUE +]; +class Extension extends PkiObject { + get parsedValue() { + if (this._parsedValue === undefined) { + const parsedValue = ExtensionValueFactory.fromBER(this.extnID, this.extnValue.valueBlock.valueHexView); + this._parsedValue = parsedValue; + } + return this._parsedValue || undefined; + } + set parsedValue(value) { + this._parsedValue = value; + } + constructor(parameters = {}) { + super(); + this.extnID = getParametersValue(parameters, EXTN_ID, Extension.defaultValues(EXTN_ID)); + this.critical = getParametersValue(parameters, CRITICAL, Extension.defaultValues(CRITICAL)); + if (EXTN_VALUE in parameters) { + this.extnValue = new OctetString({ valueHex: parameters.extnValue }); + } + else { + this.extnValue = Extension.defaultValues(EXTN_VALUE); + } + if (PARSED_VALUE$5 in parameters) { + this.parsedValue = getParametersValue(parameters, PARSED_VALUE$5, Extension.defaultValues(PARSED_VALUE$5)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case EXTN_ID: + return EMPTY_STRING; + case CRITICAL: + return false; + case EXTN_VALUE: + return new OctetString(); + case PARSED_VALUE$5: + return {}; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.extnID || EMPTY_STRING) }), + new Boolean({ + name: (names.critical || EMPTY_STRING), + optional: true + }), + new OctetString({ name: (names.extnValue || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$10); + const asn1 = compareSchema(schema, schema, Extension.schema({ + names: { + extnID: EXTN_ID, + critical: CRITICAL, + extnValue: EXTN_VALUE + } + })); + AsnError.assertSchema(asn1, this.className); + this.extnID = asn1.result.extnID.valueBlock.toString(); + if (CRITICAL in asn1.result) { + this.critical = asn1.result.critical.valueBlock.value; + } + this.extnValue = asn1.result.extnValue; + } + toSchema() { + const outputArray = []; + outputArray.push(new ObjectIdentifier({ value: this.extnID })); + if (this.critical !== Extension.defaultValues(CRITICAL)) { + outputArray.push(new Boolean({ value: this.critical })); + } + outputArray.push(this.extnValue); + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const object = { + extnID: this.extnID, + extnValue: this.extnValue.toJSON(), + }; + if (this.critical !== Extension.defaultValues(CRITICAL)) { + object.critical = this.critical; + } + if (this.parsedValue && this.parsedValue.toJSON) { + object.parsedValue = this.parsedValue.toJSON(); + } + return object; + } +} Extension.CLASS_NAME = "Extension"; -const EXTENSIONS$5 = "extensions"; -const CLEAR_PROPS$$ = [ - EXTENSIONS$5, -]; -class Extensions extends PkiObject { - constructor(parameters = {}) { - super(); - this.extensions = getParametersValue(parameters, EXTENSIONS$5, Extensions.defaultValues(EXTENSIONS$5)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case EXTENSIONS$5: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}, optional = false) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - optional, - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.extensions || EMPTY_STRING), - value: Extension.schema(names.extension || {}) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$$); - const asn1 = compareSchema(schema, schema, Extensions.schema({ - names: { - extensions: EXTENSIONS$5 - } - })); - AsnError.assertSchema(asn1, this.className); - this.extensions = Array.from(asn1.result.extensions, element => new Extension({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.extensions, o => o.toSchema()) - })); - } - toJSON() { - return { - extensions: this.extensions.map(o => o.toJSON()) - }; - } -} +const EXTENSIONS$5 = "extensions"; +const CLEAR_PROPS$$ = [ + EXTENSIONS$5, +]; +class Extensions extends PkiObject { + constructor(parameters = {}) { + super(); + this.extensions = getParametersValue(parameters, EXTENSIONS$5, Extensions.defaultValues(EXTENSIONS$5)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case EXTENSIONS$5: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}, optional = false) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + optional, + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.extensions || EMPTY_STRING), + value: Extension.schema(names.extension || {}) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$$); + const asn1 = compareSchema(schema, schema, Extensions.schema({ + names: { + extensions: EXTENSIONS$5 + } + })); + AsnError.assertSchema(asn1, this.className); + this.extensions = Array.from(asn1.result.extensions, element => new Extension({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.extensions, o => o.toSchema()) + })); + } + toJSON() { + return { + extensions: this.extensions.map(o => o.toJSON()) + }; + } +} Extensions.CLASS_NAME = "Extensions"; -const ISSUER$5 = "issuer"; -const SERIAL_NUMBER$6 = "serialNumber"; -const ISSUER_UID = "issuerUID"; -const CLEAR_PROPS$_ = [ - ISSUER$5, - SERIAL_NUMBER$6, - ISSUER_UID, -]; -class IssuerSerial extends PkiObject { - constructor(parameters = {}) { - super(); - this.issuer = getParametersValue(parameters, ISSUER$5, IssuerSerial.defaultValues(ISSUER$5)); - this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$6, IssuerSerial.defaultValues(SERIAL_NUMBER$6)); - if (ISSUER_UID in parameters) { - this.issuerUID = getParametersValue(parameters, ISSUER_UID, IssuerSerial.defaultValues(ISSUER_UID)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ISSUER$5: - return new GeneralNames(); - case SERIAL_NUMBER$6: - return new Integer(); - case ISSUER_UID: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - GeneralNames.schema(names.issuer || {}), - new Integer({ name: (names.serialNumber || EMPTY_STRING) }), - new BitString({ - optional: true, - name: (names.issuerUID || EMPTY_STRING) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$_); - const asn1 = compareSchema(schema, schema, IssuerSerial.schema({ - names: { - issuer: { - names: { - blockName: ISSUER$5 - } - }, - serialNumber: SERIAL_NUMBER$6, - issuerUID: ISSUER_UID - } - })); - AsnError.assertSchema(asn1, this.className); - this.issuer = new GeneralNames({ schema: asn1.result.issuer }); - this.serialNumber = asn1.result.serialNumber; - if (ISSUER_UID in asn1.result) - this.issuerUID = asn1.result.issuerUID; - } - toSchema() { - const result = new Sequence({ - value: [ - this.issuer.toSchema(), - this.serialNumber - ] - }); - if (this.issuerUID) { - result.valueBlock.value.push(this.issuerUID); - } - return result; - } - toJSON() { - const result = { - issuer: this.issuer.toJSON(), - serialNumber: this.serialNumber.toJSON() - }; - if (this.issuerUID) { - result.issuerUID = this.issuerUID.toJSON(); - } - return result; - } -} +const ISSUER$5 = "issuer"; +const SERIAL_NUMBER$6 = "serialNumber"; +const ISSUER_UID = "issuerUID"; +const CLEAR_PROPS$_ = [ + ISSUER$5, + SERIAL_NUMBER$6, + ISSUER_UID, +]; +class IssuerSerial extends PkiObject { + constructor(parameters = {}) { + super(); + this.issuer = getParametersValue(parameters, ISSUER$5, IssuerSerial.defaultValues(ISSUER$5)); + this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$6, IssuerSerial.defaultValues(SERIAL_NUMBER$6)); + if (ISSUER_UID in parameters) { + this.issuerUID = getParametersValue(parameters, ISSUER_UID, IssuerSerial.defaultValues(ISSUER_UID)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ISSUER$5: + return new GeneralNames(); + case SERIAL_NUMBER$6: + return new Integer(); + case ISSUER_UID: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + GeneralNames.schema(names.issuer || {}), + new Integer({ name: (names.serialNumber || EMPTY_STRING) }), + new BitString({ + optional: true, + name: (names.issuerUID || EMPTY_STRING) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$_); + const asn1 = compareSchema(schema, schema, IssuerSerial.schema({ + names: { + issuer: { + names: { + blockName: ISSUER$5 + } + }, + serialNumber: SERIAL_NUMBER$6, + issuerUID: ISSUER_UID + } + })); + AsnError.assertSchema(asn1, this.className); + this.issuer = new GeneralNames({ schema: asn1.result.issuer }); + this.serialNumber = asn1.result.serialNumber; + if (ISSUER_UID in asn1.result) + this.issuerUID = asn1.result.issuerUID; + } + toSchema() { + const result = new Sequence({ + value: [ + this.issuer.toSchema(), + this.serialNumber + ] + }); + if (this.issuerUID) { + result.valueBlock.value.push(this.issuerUID); + } + return result; + } + toJSON() { + const result = { + issuer: this.issuer.toJSON(), + serialNumber: this.serialNumber.toJSON() + }; + if (this.issuerUID) { + result.issuerUID = this.issuerUID.toJSON(); + } + return result; + } +} IssuerSerial.CLASS_NAME = "IssuerSerial"; -const VERSION$h = "version"; -const BASE_CERTIFICATE_ID$2 = "baseCertificateID"; -const SUBJECT_NAME = "subjectName"; -const ISSUER$4 = "issuer"; -const SIGNATURE$6 = "signature"; -const SERIAL_NUMBER$5 = "serialNumber"; -const ATTR_CERT_VALIDITY_PERIOD$1 = "attrCertValidityPeriod"; -const ATTRIBUTES$3 = "attributes"; -const ISSUER_UNIQUE_ID$2 = "issuerUniqueID"; -const EXTENSIONS$4 = "extensions"; -const CLEAR_PROPS$Z = [ - VERSION$h, - BASE_CERTIFICATE_ID$2, - SUBJECT_NAME, - ISSUER$4, - SIGNATURE$6, - SERIAL_NUMBER$5, - ATTR_CERT_VALIDITY_PERIOD$1, - ATTRIBUTES$3, - ISSUER_UNIQUE_ID$2, - EXTENSIONS$4, -]; -class AttributeCertificateInfoV1 extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$h, AttributeCertificateInfoV1.defaultValues(VERSION$h)); - if (BASE_CERTIFICATE_ID$2 in parameters) { - this.baseCertificateID = getParametersValue(parameters, BASE_CERTIFICATE_ID$2, AttributeCertificateInfoV1.defaultValues(BASE_CERTIFICATE_ID$2)); - } - if (SUBJECT_NAME in parameters) { - this.subjectName = getParametersValue(parameters, SUBJECT_NAME, AttributeCertificateInfoV1.defaultValues(SUBJECT_NAME)); - } - this.issuer = getParametersValue(parameters, ISSUER$4, AttributeCertificateInfoV1.defaultValues(ISSUER$4)); - this.signature = getParametersValue(parameters, SIGNATURE$6, AttributeCertificateInfoV1.defaultValues(SIGNATURE$6)); - this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$5, AttributeCertificateInfoV1.defaultValues(SERIAL_NUMBER$5)); - this.attrCertValidityPeriod = getParametersValue(parameters, ATTR_CERT_VALIDITY_PERIOD$1, AttributeCertificateInfoV1.defaultValues(ATTR_CERT_VALIDITY_PERIOD$1)); - this.attributes = getParametersValue(parameters, ATTRIBUTES$3, AttributeCertificateInfoV1.defaultValues(ATTRIBUTES$3)); - if (ISSUER_UNIQUE_ID$2 in parameters) - this.issuerUniqueID = getParametersValue(parameters, ISSUER_UNIQUE_ID$2, AttributeCertificateInfoV1.defaultValues(ISSUER_UNIQUE_ID$2)); - if (EXTENSIONS$4 in parameters) { - this.extensions = getParametersValue(parameters, EXTENSIONS$4, AttributeCertificateInfoV1.defaultValues(EXTENSIONS$4)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$h: - return 0; - case BASE_CERTIFICATE_ID$2: - return new IssuerSerial(); - case SUBJECT_NAME: - return new GeneralNames(); - case ISSUER$4: - return new GeneralNames(); - case SIGNATURE$6: - return new AlgorithmIdentifier(); - case SERIAL_NUMBER$5: - return new Integer(); - case ATTR_CERT_VALIDITY_PERIOD$1: - return new AttCertValidityPeriod(); - case ATTRIBUTES$3: - return []; - case ISSUER_UNIQUE_ID$2: - return new BitString(); - case EXTENSIONS$4: - return new Extensions(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - new Choice({ - value: [ - new Constructed({ - name: (names.baseCertificateID || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: IssuerSerial.schema().valueBlock.value - }), - new Constructed({ - name: (names.subjectName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: GeneralNames.schema().valueBlock.value - }), - ] - }), - GeneralNames.schema({ - names: { - blockName: (names.issuer || EMPTY_STRING) - } - }), - AlgorithmIdentifier.schema(names.signature || {}), - new Integer({ name: (names.serialNumber || EMPTY_STRING) }), - AttCertValidityPeriod.schema(names.attrCertValidityPeriod || {}), - new Sequence({ - name: (names.attributes || EMPTY_STRING), - value: [ - new Repeated({ - value: Attribute.schema() - }) - ] - }), - new BitString({ - optional: true, - name: (names.issuerUniqueID || EMPTY_STRING) - }), - Extensions.schema(names.extensions || {}, true) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$Z); - const asn1 = compareSchema(schema, schema, AttributeCertificateInfoV1.schema({ - names: { - version: VERSION$h, - baseCertificateID: BASE_CERTIFICATE_ID$2, - subjectName: SUBJECT_NAME, - issuer: ISSUER$4, - signature: { - names: { - blockName: SIGNATURE$6 - } - }, - serialNumber: SERIAL_NUMBER$5, - attrCertValidityPeriod: { - names: { - blockName: ATTR_CERT_VALIDITY_PERIOD$1 - } - }, - attributes: ATTRIBUTES$3, - issuerUniqueID: ISSUER_UNIQUE_ID$2, - extensions: { - names: { - blockName: EXTENSIONS$4 - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - if (BASE_CERTIFICATE_ID$2 in asn1.result) { - this.baseCertificateID = new IssuerSerial({ - schema: new Sequence({ - value: asn1.result.baseCertificateID.valueBlock.value - }) - }); - } - if (SUBJECT_NAME in asn1.result) { - this.subjectName = new GeneralNames({ - schema: new Sequence({ - value: asn1.result.subjectName.valueBlock.value - }) - }); - } - this.issuer = asn1.result.issuer; - this.signature = new AlgorithmIdentifier({ schema: asn1.result.signature }); - this.serialNumber = asn1.result.serialNumber; - this.attrCertValidityPeriod = new AttCertValidityPeriod({ schema: asn1.result.attrCertValidityPeriod }); - this.attributes = Array.from(asn1.result.attributes.valueBlock.value, element => new Attribute({ schema: element })); - if (ISSUER_UNIQUE_ID$2 in asn1.result) { - this.issuerUniqueID = asn1.result.issuerUniqueID; - } - if (EXTENSIONS$4 in asn1.result) { - this.extensions = new Extensions({ schema: asn1.result.extensions }); - } - } - toSchema() { - const result = new Sequence({ - value: [new Integer({ value: this.version })] - }); - if (this.baseCertificateID) { - result.valueBlock.value.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.baseCertificateID.toSchema().valueBlock.value - })); - } - if (this.subjectName) { - result.valueBlock.value.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: this.subjectName.toSchema().valueBlock.value - })); - } - result.valueBlock.value.push(this.issuer.toSchema()); - result.valueBlock.value.push(this.signature.toSchema()); - result.valueBlock.value.push(this.serialNumber); - result.valueBlock.value.push(this.attrCertValidityPeriod.toSchema()); - result.valueBlock.value.push(new Sequence({ - value: Array.from(this.attributes, o => o.toSchema()) - })); - if (this.issuerUniqueID) { - result.valueBlock.value.push(this.issuerUniqueID); - } - if (this.extensions) { - result.valueBlock.value.push(this.extensions.toSchema()); - } - return result; - } - toJSON() { - const result = { - version: this.version - }; - if (this.baseCertificateID) { - result.baseCertificateID = this.baseCertificateID.toJSON(); - } - if (this.subjectName) { - result.subjectName = this.subjectName.toJSON(); - } - result.issuer = this.issuer.toJSON(); - result.signature = this.signature.toJSON(); - result.serialNumber = this.serialNumber.toJSON(); - result.attrCertValidityPeriod = this.attrCertValidityPeriod.toJSON(); - result.attributes = Array.from(this.attributes, o => o.toJSON()); - if (this.issuerUniqueID) { - result.issuerUniqueID = this.issuerUniqueID.toJSON(); - } - if (this.extensions) { - result.extensions = this.extensions.toJSON(); - } - return result; - } -} +const VERSION$h = "version"; +const BASE_CERTIFICATE_ID$2 = "baseCertificateID"; +const SUBJECT_NAME = "subjectName"; +const ISSUER$4 = "issuer"; +const SIGNATURE$6 = "signature"; +const SERIAL_NUMBER$5 = "serialNumber"; +const ATTR_CERT_VALIDITY_PERIOD$1 = "attrCertValidityPeriod"; +const ATTRIBUTES$3 = "attributes"; +const ISSUER_UNIQUE_ID$2 = "issuerUniqueID"; +const EXTENSIONS$4 = "extensions"; +const CLEAR_PROPS$Z = [ + VERSION$h, + BASE_CERTIFICATE_ID$2, + SUBJECT_NAME, + ISSUER$4, + SIGNATURE$6, + SERIAL_NUMBER$5, + ATTR_CERT_VALIDITY_PERIOD$1, + ATTRIBUTES$3, + ISSUER_UNIQUE_ID$2, + EXTENSIONS$4, +]; +class AttributeCertificateInfoV1 extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$h, AttributeCertificateInfoV1.defaultValues(VERSION$h)); + if (BASE_CERTIFICATE_ID$2 in parameters) { + this.baseCertificateID = getParametersValue(parameters, BASE_CERTIFICATE_ID$2, AttributeCertificateInfoV1.defaultValues(BASE_CERTIFICATE_ID$2)); + } + if (SUBJECT_NAME in parameters) { + this.subjectName = getParametersValue(parameters, SUBJECT_NAME, AttributeCertificateInfoV1.defaultValues(SUBJECT_NAME)); + } + this.issuer = getParametersValue(parameters, ISSUER$4, AttributeCertificateInfoV1.defaultValues(ISSUER$4)); + this.signature = getParametersValue(parameters, SIGNATURE$6, AttributeCertificateInfoV1.defaultValues(SIGNATURE$6)); + this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$5, AttributeCertificateInfoV1.defaultValues(SERIAL_NUMBER$5)); + this.attrCertValidityPeriod = getParametersValue(parameters, ATTR_CERT_VALIDITY_PERIOD$1, AttributeCertificateInfoV1.defaultValues(ATTR_CERT_VALIDITY_PERIOD$1)); + this.attributes = getParametersValue(parameters, ATTRIBUTES$3, AttributeCertificateInfoV1.defaultValues(ATTRIBUTES$3)); + if (ISSUER_UNIQUE_ID$2 in parameters) + this.issuerUniqueID = getParametersValue(parameters, ISSUER_UNIQUE_ID$2, AttributeCertificateInfoV1.defaultValues(ISSUER_UNIQUE_ID$2)); + if (EXTENSIONS$4 in parameters) { + this.extensions = getParametersValue(parameters, EXTENSIONS$4, AttributeCertificateInfoV1.defaultValues(EXTENSIONS$4)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$h: + return 0; + case BASE_CERTIFICATE_ID$2: + return new IssuerSerial(); + case SUBJECT_NAME: + return new GeneralNames(); + case ISSUER$4: + return new GeneralNames(); + case SIGNATURE$6: + return new AlgorithmIdentifier(); + case SERIAL_NUMBER$5: + return new Integer(); + case ATTR_CERT_VALIDITY_PERIOD$1: + return new AttCertValidityPeriod(); + case ATTRIBUTES$3: + return []; + case ISSUER_UNIQUE_ID$2: + return new BitString(); + case EXTENSIONS$4: + return new Extensions(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + new Choice({ + value: [ + new Constructed({ + name: (names.baseCertificateID || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: IssuerSerial.schema().valueBlock.value + }), + new Constructed({ + name: (names.subjectName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: GeneralNames.schema().valueBlock.value + }), + ] + }), + GeneralNames.schema({ + names: { + blockName: (names.issuer || EMPTY_STRING) + } + }), + AlgorithmIdentifier.schema(names.signature || {}), + new Integer({ name: (names.serialNumber || EMPTY_STRING) }), + AttCertValidityPeriod.schema(names.attrCertValidityPeriod || {}), + new Sequence({ + name: (names.attributes || EMPTY_STRING), + value: [ + new Repeated({ + value: Attribute.schema() + }) + ] + }), + new BitString({ + optional: true, + name: (names.issuerUniqueID || EMPTY_STRING) + }), + Extensions.schema(names.extensions || {}, true) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$Z); + const asn1 = compareSchema(schema, schema, AttributeCertificateInfoV1.schema({ + names: { + version: VERSION$h, + baseCertificateID: BASE_CERTIFICATE_ID$2, + subjectName: SUBJECT_NAME, + issuer: ISSUER$4, + signature: { + names: { + blockName: SIGNATURE$6 + } + }, + serialNumber: SERIAL_NUMBER$5, + attrCertValidityPeriod: { + names: { + blockName: ATTR_CERT_VALIDITY_PERIOD$1 + } + }, + attributes: ATTRIBUTES$3, + issuerUniqueID: ISSUER_UNIQUE_ID$2, + extensions: { + names: { + blockName: EXTENSIONS$4 + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + if (BASE_CERTIFICATE_ID$2 in asn1.result) { + this.baseCertificateID = new IssuerSerial({ + schema: new Sequence({ + value: asn1.result.baseCertificateID.valueBlock.value + }) + }); + } + if (SUBJECT_NAME in asn1.result) { + this.subjectName = new GeneralNames({ + schema: new Sequence({ + value: asn1.result.subjectName.valueBlock.value + }) + }); + } + this.issuer = asn1.result.issuer; + this.signature = new AlgorithmIdentifier({ schema: asn1.result.signature }); + this.serialNumber = asn1.result.serialNumber; + this.attrCertValidityPeriod = new AttCertValidityPeriod({ schema: asn1.result.attrCertValidityPeriod }); + this.attributes = Array.from(asn1.result.attributes.valueBlock.value, element => new Attribute({ schema: element })); + if (ISSUER_UNIQUE_ID$2 in asn1.result) { + this.issuerUniqueID = asn1.result.issuerUniqueID; + } + if (EXTENSIONS$4 in asn1.result) { + this.extensions = new Extensions({ schema: asn1.result.extensions }); + } + } + toSchema() { + const result = new Sequence({ + value: [new Integer({ value: this.version })] + }); + if (this.baseCertificateID) { + result.valueBlock.value.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.baseCertificateID.toSchema().valueBlock.value + })); + } + if (this.subjectName) { + result.valueBlock.value.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: this.subjectName.toSchema().valueBlock.value + })); + } + result.valueBlock.value.push(this.issuer.toSchema()); + result.valueBlock.value.push(this.signature.toSchema()); + result.valueBlock.value.push(this.serialNumber); + result.valueBlock.value.push(this.attrCertValidityPeriod.toSchema()); + result.valueBlock.value.push(new Sequence({ + value: Array.from(this.attributes, o => o.toSchema()) + })); + if (this.issuerUniqueID) { + result.valueBlock.value.push(this.issuerUniqueID); + } + if (this.extensions) { + result.valueBlock.value.push(this.extensions.toSchema()); + } + return result; + } + toJSON() { + const result = { + version: this.version + }; + if (this.baseCertificateID) { + result.baseCertificateID = this.baseCertificateID.toJSON(); + } + if (this.subjectName) { + result.subjectName = this.subjectName.toJSON(); + } + result.issuer = this.issuer.toJSON(); + result.signature = this.signature.toJSON(); + result.serialNumber = this.serialNumber.toJSON(); + result.attrCertValidityPeriod = this.attrCertValidityPeriod.toJSON(); + result.attributes = Array.from(this.attributes, o => o.toJSON()); + if (this.issuerUniqueID) { + result.issuerUniqueID = this.issuerUniqueID.toJSON(); + } + if (this.extensions) { + result.extensions = this.extensions.toJSON(); + } + return result; + } +} AttributeCertificateInfoV1.CLASS_NAME = "AttributeCertificateInfoV1"; -const ACINFO$1 = "acinfo"; -const SIGNATURE_ALGORITHM$7 = "signatureAlgorithm"; -const SIGNATURE_VALUE$4 = "signatureValue"; -const CLEAR_PROPS$Y = [ - ACINFO$1, - SIGNATURE_VALUE$4, - SIGNATURE_ALGORITHM$7 -]; -class AttributeCertificateV1 extends PkiObject { - constructor(parameters = {}) { - super(); - this.acinfo = getParametersValue(parameters, ACINFO$1, AttributeCertificateV1.defaultValues(ACINFO$1)); - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$7, AttributeCertificateV1.defaultValues(SIGNATURE_ALGORITHM$7)); - this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$4, AttributeCertificateV1.defaultValues(SIGNATURE_VALUE$4)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ACINFO$1: - return new AttributeCertificateInfoV1(); - case SIGNATURE_ALGORITHM$7: - return new AlgorithmIdentifier(); - case SIGNATURE_VALUE$4: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AttributeCertificateInfoV1.schema(names.acinfo || {}), - AlgorithmIdentifier.schema(names.signatureAlgorithm || {}), - new BitString({ name: (names.signatureValue || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$Y); - const asn1 = compareSchema(schema, schema, AttributeCertificateV1.schema({ - names: { - acinfo: { - names: { - blockName: ACINFO$1 - } - }, - signatureAlgorithm: { - names: { - blockName: SIGNATURE_ALGORITHM$7 - } - }, - signatureValue: SIGNATURE_VALUE$4 - } - })); - AsnError.assertSchema(asn1, this.className); - this.acinfo = new AttributeCertificateInfoV1({ schema: asn1.result.acinfo }); - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); - this.signatureValue = asn1.result.signatureValue; - } - toSchema() { - return (new Sequence({ - value: [ - this.acinfo.toSchema(), - this.signatureAlgorithm.toSchema(), - this.signatureValue - ] - })); - } - toJSON() { - return { - acinfo: this.acinfo.toJSON(), - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signatureValue: this.signatureValue.toJSON(), - }; - } -} +const ACINFO$1 = "acinfo"; +const SIGNATURE_ALGORITHM$7 = "signatureAlgorithm"; +const SIGNATURE_VALUE$4 = "signatureValue"; +const CLEAR_PROPS$Y = [ + ACINFO$1, + SIGNATURE_VALUE$4, + SIGNATURE_ALGORITHM$7 +]; +class AttributeCertificateV1 extends PkiObject { + constructor(parameters = {}) { + super(); + this.acinfo = getParametersValue(parameters, ACINFO$1, AttributeCertificateV1.defaultValues(ACINFO$1)); + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$7, AttributeCertificateV1.defaultValues(SIGNATURE_ALGORITHM$7)); + this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$4, AttributeCertificateV1.defaultValues(SIGNATURE_VALUE$4)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ACINFO$1: + return new AttributeCertificateInfoV1(); + case SIGNATURE_ALGORITHM$7: + return new AlgorithmIdentifier(); + case SIGNATURE_VALUE$4: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AttributeCertificateInfoV1.schema(names.acinfo || {}), + AlgorithmIdentifier.schema(names.signatureAlgorithm || {}), + new BitString({ name: (names.signatureValue || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$Y); + const asn1 = compareSchema(schema, schema, AttributeCertificateV1.schema({ + names: { + acinfo: { + names: { + blockName: ACINFO$1 + } + }, + signatureAlgorithm: { + names: { + blockName: SIGNATURE_ALGORITHM$7 + } + }, + signatureValue: SIGNATURE_VALUE$4 + } + })); + AsnError.assertSchema(asn1, this.className); + this.acinfo = new AttributeCertificateInfoV1({ schema: asn1.result.acinfo }); + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); + this.signatureValue = asn1.result.signatureValue; + } + toSchema() { + return (new Sequence({ + value: [ + this.acinfo.toSchema(), + this.signatureAlgorithm.toSchema(), + this.signatureValue + ] + })); + } + toJSON() { + return { + acinfo: this.acinfo.toJSON(), + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signatureValue: this.signatureValue.toJSON(), + }; + } +} AttributeCertificateV1.CLASS_NAME = "AttributeCertificateV1"; -const DIGESTED_OBJECT_TYPE = "digestedObjectType"; -const OTHER_OBJECT_TYPE_ID = "otherObjectTypeID"; -const DIGEST_ALGORITHM$2 = "digestAlgorithm"; -const OBJECT_DIGEST = "objectDigest"; -const CLEAR_PROPS$X = [ - DIGESTED_OBJECT_TYPE, - OTHER_OBJECT_TYPE_ID, - DIGEST_ALGORITHM$2, - OBJECT_DIGEST, -]; -class ObjectDigestInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.digestedObjectType = getParametersValue(parameters, DIGESTED_OBJECT_TYPE, ObjectDigestInfo.defaultValues(DIGESTED_OBJECT_TYPE)); - if (OTHER_OBJECT_TYPE_ID in parameters) { - this.otherObjectTypeID = getParametersValue(parameters, OTHER_OBJECT_TYPE_ID, ObjectDigestInfo.defaultValues(OTHER_OBJECT_TYPE_ID)); - } - this.digestAlgorithm = getParametersValue(parameters, DIGEST_ALGORITHM$2, ObjectDigestInfo.defaultValues(DIGEST_ALGORITHM$2)); - this.objectDigest = getParametersValue(parameters, OBJECT_DIGEST, ObjectDigestInfo.defaultValues(OBJECT_DIGEST)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case DIGESTED_OBJECT_TYPE: - return new Enumerated(); - case OTHER_OBJECT_TYPE_ID: - return new ObjectIdentifier(); - case DIGEST_ALGORITHM$2: - return new AlgorithmIdentifier(); - case OBJECT_DIGEST: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Enumerated({ name: (names.digestedObjectType || EMPTY_STRING) }), - new ObjectIdentifier({ - optional: true, - name: (names.otherObjectTypeID || EMPTY_STRING) - }), - AlgorithmIdentifier.schema(names.digestAlgorithm || {}), - new BitString({ name: (names.objectDigest || EMPTY_STRING) }), - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$X); - const asn1 = compareSchema(schema, schema, ObjectDigestInfo.schema({ - names: { - digestedObjectType: DIGESTED_OBJECT_TYPE, - otherObjectTypeID: OTHER_OBJECT_TYPE_ID, - digestAlgorithm: { - names: { - blockName: DIGEST_ALGORITHM$2 - } - }, - objectDigest: OBJECT_DIGEST - } - })); - AsnError.assertSchema(asn1, this.className); - this.digestedObjectType = asn1.result.digestedObjectType; - if (OTHER_OBJECT_TYPE_ID in asn1.result) { - this.otherObjectTypeID = asn1.result.otherObjectTypeID; - } - this.digestAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.digestAlgorithm }); - this.objectDigest = asn1.result.objectDigest; - } - toSchema() { - const result = new Sequence({ - value: [this.digestedObjectType] - }); - if (this.otherObjectTypeID) { - result.valueBlock.value.push(this.otherObjectTypeID); - } - result.valueBlock.value.push(this.digestAlgorithm.toSchema()); - result.valueBlock.value.push(this.objectDigest); - return result; - } - toJSON() { - const result = { - digestedObjectType: this.digestedObjectType.toJSON(), - digestAlgorithm: this.digestAlgorithm.toJSON(), - objectDigest: this.objectDigest.toJSON(), - }; - if (this.otherObjectTypeID) { - result.otherObjectTypeID = this.otherObjectTypeID.toJSON(); - } - return result; - } -} -ObjectDigestInfo.CLASS_NAME = "ObjectDigestInfo"; - -const ISSUER_NAME = "issuerName"; -const BASE_CERTIFICATE_ID$1 = "baseCertificateID"; -const OBJECT_DIGEST_INFO$1 = "objectDigestInfo"; -const CLEAR_PROPS$W = [ - ISSUER_NAME, - BASE_CERTIFICATE_ID$1, - OBJECT_DIGEST_INFO$1 -]; -class V2Form extends PkiObject { - constructor(parameters = {}) { - super(); - if (ISSUER_NAME in parameters) { - this.issuerName = getParametersValue(parameters, ISSUER_NAME, V2Form.defaultValues(ISSUER_NAME)); - } - if (BASE_CERTIFICATE_ID$1 in parameters) { - this.baseCertificateID = getParametersValue(parameters, BASE_CERTIFICATE_ID$1, V2Form.defaultValues(BASE_CERTIFICATE_ID$1)); - } - if (OBJECT_DIGEST_INFO$1 in parameters) { - this.objectDigestInfo = getParametersValue(parameters, OBJECT_DIGEST_INFO$1, V2Form.defaultValues(OBJECT_DIGEST_INFO$1)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ISSUER_NAME: - return new GeneralNames(); - case BASE_CERTIFICATE_ID$1: - return new IssuerSerial(); - case OBJECT_DIGEST_INFO$1: - return new ObjectDigestInfo(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - GeneralNames.schema({ - names: { - blockName: names.issuerName - } - }, true), - new Constructed({ - optional: true, - name: (names.baseCertificateID || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: IssuerSerial.schema().valueBlock.value - }), - new Constructed({ - optional: true, - name: (names.objectDigestInfo || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: ObjectDigestInfo.schema().valueBlock.value - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$W); - const asn1 = compareSchema(schema, schema, V2Form.schema({ - names: { - issuerName: ISSUER_NAME, - baseCertificateID: BASE_CERTIFICATE_ID$1, - objectDigestInfo: OBJECT_DIGEST_INFO$1 - } - })); - AsnError.assertSchema(asn1, this.className); - if (ISSUER_NAME in asn1.result) - this.issuerName = new GeneralNames({ schema: asn1.result.issuerName }); - if (BASE_CERTIFICATE_ID$1 in asn1.result) { - this.baseCertificateID = new IssuerSerial({ - schema: new Sequence({ - value: asn1.result.baseCertificateID.valueBlock.value - }) - }); - } - if (OBJECT_DIGEST_INFO$1 in asn1.result) { - this.objectDigestInfo = new ObjectDigestInfo({ - schema: new Sequence({ - value: asn1.result.objectDigestInfo.valueBlock.value - }) - }); - } - } - toSchema() { - const result = new Sequence(); - if (this.issuerName) - result.valueBlock.value.push(this.issuerName.toSchema()); - if (this.baseCertificateID) { - result.valueBlock.value.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.baseCertificateID.toSchema().valueBlock.value - })); - } - if (this.objectDigestInfo) { - result.valueBlock.value.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: this.objectDigestInfo.toSchema().valueBlock.value - })); - } - return result; - } - toJSON() { - const result = {}; - if (this.issuerName) { - result.issuerName = this.issuerName.toJSON(); - } - if (this.baseCertificateID) { - result.baseCertificateID = this.baseCertificateID.toJSON(); - } - if (this.objectDigestInfo) { - result.objectDigestInfo = this.objectDigestInfo.toJSON(); - } - return result; - } -} +const DIGESTED_OBJECT_TYPE = "digestedObjectType"; +const OTHER_OBJECT_TYPE_ID = "otherObjectTypeID"; +const DIGEST_ALGORITHM$2 = "digestAlgorithm"; +const OBJECT_DIGEST = "objectDigest"; +const CLEAR_PROPS$X = [ + DIGESTED_OBJECT_TYPE, + OTHER_OBJECT_TYPE_ID, + DIGEST_ALGORITHM$2, + OBJECT_DIGEST, +]; +class ObjectDigestInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.digestedObjectType = getParametersValue(parameters, DIGESTED_OBJECT_TYPE, ObjectDigestInfo.defaultValues(DIGESTED_OBJECT_TYPE)); + if (OTHER_OBJECT_TYPE_ID in parameters) { + this.otherObjectTypeID = getParametersValue(parameters, OTHER_OBJECT_TYPE_ID, ObjectDigestInfo.defaultValues(OTHER_OBJECT_TYPE_ID)); + } + this.digestAlgorithm = getParametersValue(parameters, DIGEST_ALGORITHM$2, ObjectDigestInfo.defaultValues(DIGEST_ALGORITHM$2)); + this.objectDigest = getParametersValue(parameters, OBJECT_DIGEST, ObjectDigestInfo.defaultValues(OBJECT_DIGEST)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case DIGESTED_OBJECT_TYPE: + return new Enumerated(); + case OTHER_OBJECT_TYPE_ID: + return new ObjectIdentifier(); + case DIGEST_ALGORITHM$2: + return new AlgorithmIdentifier(); + case OBJECT_DIGEST: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Enumerated({ name: (names.digestedObjectType || EMPTY_STRING) }), + new ObjectIdentifier({ + optional: true, + name: (names.otherObjectTypeID || EMPTY_STRING) + }), + AlgorithmIdentifier.schema(names.digestAlgorithm || {}), + new BitString({ name: (names.objectDigest || EMPTY_STRING) }), + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$X); + const asn1 = compareSchema(schema, schema, ObjectDigestInfo.schema({ + names: { + digestedObjectType: DIGESTED_OBJECT_TYPE, + otherObjectTypeID: OTHER_OBJECT_TYPE_ID, + digestAlgorithm: { + names: { + blockName: DIGEST_ALGORITHM$2 + } + }, + objectDigest: OBJECT_DIGEST + } + })); + AsnError.assertSchema(asn1, this.className); + this.digestedObjectType = asn1.result.digestedObjectType; + if (OTHER_OBJECT_TYPE_ID in asn1.result) { + this.otherObjectTypeID = asn1.result.otherObjectTypeID; + } + this.digestAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.digestAlgorithm }); + this.objectDigest = asn1.result.objectDigest; + } + toSchema() { + const result = new Sequence({ + value: [this.digestedObjectType] + }); + if (this.otherObjectTypeID) { + result.valueBlock.value.push(this.otherObjectTypeID); + } + result.valueBlock.value.push(this.digestAlgorithm.toSchema()); + result.valueBlock.value.push(this.objectDigest); + return result; + } + toJSON() { + const result = { + digestedObjectType: this.digestedObjectType.toJSON(), + digestAlgorithm: this.digestAlgorithm.toJSON(), + objectDigest: this.objectDigest.toJSON(), + }; + if (this.otherObjectTypeID) { + result.otherObjectTypeID = this.otherObjectTypeID.toJSON(); + } + return result; + } +} +ObjectDigestInfo.CLASS_NAME = "ObjectDigestInfo"; + +const ISSUER_NAME = "issuerName"; +const BASE_CERTIFICATE_ID$1 = "baseCertificateID"; +const OBJECT_DIGEST_INFO$1 = "objectDigestInfo"; +const CLEAR_PROPS$W = [ + ISSUER_NAME, + BASE_CERTIFICATE_ID$1, + OBJECT_DIGEST_INFO$1 +]; +class V2Form extends PkiObject { + constructor(parameters = {}) { + super(); + if (ISSUER_NAME in parameters) { + this.issuerName = getParametersValue(parameters, ISSUER_NAME, V2Form.defaultValues(ISSUER_NAME)); + } + if (BASE_CERTIFICATE_ID$1 in parameters) { + this.baseCertificateID = getParametersValue(parameters, BASE_CERTIFICATE_ID$1, V2Form.defaultValues(BASE_CERTIFICATE_ID$1)); + } + if (OBJECT_DIGEST_INFO$1 in parameters) { + this.objectDigestInfo = getParametersValue(parameters, OBJECT_DIGEST_INFO$1, V2Form.defaultValues(OBJECT_DIGEST_INFO$1)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ISSUER_NAME: + return new GeneralNames(); + case BASE_CERTIFICATE_ID$1: + return new IssuerSerial(); + case OBJECT_DIGEST_INFO$1: + return new ObjectDigestInfo(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + GeneralNames.schema({ + names: { + blockName: names.issuerName + } + }, true), + new Constructed({ + optional: true, + name: (names.baseCertificateID || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: IssuerSerial.schema().valueBlock.value + }), + new Constructed({ + optional: true, + name: (names.objectDigestInfo || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: ObjectDigestInfo.schema().valueBlock.value + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$W); + const asn1 = compareSchema(schema, schema, V2Form.schema({ + names: { + issuerName: ISSUER_NAME, + baseCertificateID: BASE_CERTIFICATE_ID$1, + objectDigestInfo: OBJECT_DIGEST_INFO$1 + } + })); + AsnError.assertSchema(asn1, this.className); + if (ISSUER_NAME in asn1.result) + this.issuerName = new GeneralNames({ schema: asn1.result.issuerName }); + if (BASE_CERTIFICATE_ID$1 in asn1.result) { + this.baseCertificateID = new IssuerSerial({ + schema: new Sequence({ + value: asn1.result.baseCertificateID.valueBlock.value + }) + }); + } + if (OBJECT_DIGEST_INFO$1 in asn1.result) { + this.objectDigestInfo = new ObjectDigestInfo({ + schema: new Sequence({ + value: asn1.result.objectDigestInfo.valueBlock.value + }) + }); + } + } + toSchema() { + const result = new Sequence(); + if (this.issuerName) + result.valueBlock.value.push(this.issuerName.toSchema()); + if (this.baseCertificateID) { + result.valueBlock.value.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.baseCertificateID.toSchema().valueBlock.value + })); + } + if (this.objectDigestInfo) { + result.valueBlock.value.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: this.objectDigestInfo.toSchema().valueBlock.value + })); + } + return result; + } + toJSON() { + const result = {}; + if (this.issuerName) { + result.issuerName = this.issuerName.toJSON(); + } + if (this.baseCertificateID) { + result.baseCertificateID = this.baseCertificateID.toJSON(); + } + if (this.objectDigestInfo) { + result.objectDigestInfo = this.objectDigestInfo.toJSON(); + } + return result; + } +} V2Form.CLASS_NAME = "V2Form"; -const BASE_CERTIFICATE_ID = "baseCertificateID"; -const ENTITY_NAME = "entityName"; -const OBJECT_DIGEST_INFO = "objectDigestInfo"; -const CLEAR_PROPS$V = [ - BASE_CERTIFICATE_ID, - ENTITY_NAME, - OBJECT_DIGEST_INFO -]; -class Holder extends PkiObject { - constructor(parameters = {}) { - super(); - if (BASE_CERTIFICATE_ID in parameters) { - this.baseCertificateID = getParametersValue(parameters, BASE_CERTIFICATE_ID, Holder.defaultValues(BASE_CERTIFICATE_ID)); - } - if (ENTITY_NAME in parameters) { - this.entityName = getParametersValue(parameters, ENTITY_NAME, Holder.defaultValues(ENTITY_NAME)); - } - if (OBJECT_DIGEST_INFO in parameters) { - this.objectDigestInfo = getParametersValue(parameters, OBJECT_DIGEST_INFO, Holder.defaultValues(OBJECT_DIGEST_INFO)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case BASE_CERTIFICATE_ID: - return new IssuerSerial(); - case ENTITY_NAME: - return new GeneralNames(); - case OBJECT_DIGEST_INFO: - return new ObjectDigestInfo(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - optional: true, - name: (names.baseCertificateID || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: IssuerSerial.schema().valueBlock.value - }), - new Constructed({ - optional: true, - name: (names.entityName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: GeneralNames.schema().valueBlock.value - }), - new Constructed({ - optional: true, - name: (names.objectDigestInfo || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: ObjectDigestInfo.schema().valueBlock.value - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$V); - const asn1 = compareSchema(schema, schema, Holder.schema({ - names: { - baseCertificateID: BASE_CERTIFICATE_ID, - entityName: ENTITY_NAME, - objectDigestInfo: OBJECT_DIGEST_INFO - } - })); - AsnError.assertSchema(asn1, this.className); - if (BASE_CERTIFICATE_ID in asn1.result) { - this.baseCertificateID = new IssuerSerial({ - schema: new Sequence({ - value: asn1.result.baseCertificateID.valueBlock.value - }) - }); - } - if (ENTITY_NAME in asn1.result) { - this.entityName = new GeneralNames({ - schema: new Sequence({ - value: asn1.result.entityName.valueBlock.value - }) - }); - } - if (OBJECT_DIGEST_INFO in asn1.result) { - this.objectDigestInfo = new ObjectDigestInfo({ - schema: new Sequence({ - value: asn1.result.objectDigestInfo.valueBlock.value - }) - }); - } - } - toSchema() { - const result = new Sequence(); - if (this.baseCertificateID) { - result.valueBlock.value.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.baseCertificateID.toSchema().valueBlock.value - })); - } - if (this.entityName) { - result.valueBlock.value.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: this.entityName.toSchema().valueBlock.value - })); - } - if (this.objectDigestInfo) { - result.valueBlock.value.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: this.objectDigestInfo.toSchema().valueBlock.value - })); - } - return result; - } - toJSON() { - const result = {}; - if (this.baseCertificateID) { - result.baseCertificateID = this.baseCertificateID.toJSON(); - } - if (this.entityName) { - result.entityName = this.entityName.toJSON(); - } - if (this.objectDigestInfo) { - result.objectDigestInfo = this.objectDigestInfo.toJSON(); - } - return result; - } -} +const BASE_CERTIFICATE_ID = "baseCertificateID"; +const ENTITY_NAME = "entityName"; +const OBJECT_DIGEST_INFO = "objectDigestInfo"; +const CLEAR_PROPS$V = [ + BASE_CERTIFICATE_ID, + ENTITY_NAME, + OBJECT_DIGEST_INFO +]; +class Holder extends PkiObject { + constructor(parameters = {}) { + super(); + if (BASE_CERTIFICATE_ID in parameters) { + this.baseCertificateID = getParametersValue(parameters, BASE_CERTIFICATE_ID, Holder.defaultValues(BASE_CERTIFICATE_ID)); + } + if (ENTITY_NAME in parameters) { + this.entityName = getParametersValue(parameters, ENTITY_NAME, Holder.defaultValues(ENTITY_NAME)); + } + if (OBJECT_DIGEST_INFO in parameters) { + this.objectDigestInfo = getParametersValue(parameters, OBJECT_DIGEST_INFO, Holder.defaultValues(OBJECT_DIGEST_INFO)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case BASE_CERTIFICATE_ID: + return new IssuerSerial(); + case ENTITY_NAME: + return new GeneralNames(); + case OBJECT_DIGEST_INFO: + return new ObjectDigestInfo(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + optional: true, + name: (names.baseCertificateID || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: IssuerSerial.schema().valueBlock.value + }), + new Constructed({ + optional: true, + name: (names.entityName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: GeneralNames.schema().valueBlock.value + }), + new Constructed({ + optional: true, + name: (names.objectDigestInfo || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: ObjectDigestInfo.schema().valueBlock.value + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$V); + const asn1 = compareSchema(schema, schema, Holder.schema({ + names: { + baseCertificateID: BASE_CERTIFICATE_ID, + entityName: ENTITY_NAME, + objectDigestInfo: OBJECT_DIGEST_INFO + } + })); + AsnError.assertSchema(asn1, this.className); + if (BASE_CERTIFICATE_ID in asn1.result) { + this.baseCertificateID = new IssuerSerial({ + schema: new Sequence({ + value: asn1.result.baseCertificateID.valueBlock.value + }) + }); + } + if (ENTITY_NAME in asn1.result) { + this.entityName = new GeneralNames({ + schema: new Sequence({ + value: asn1.result.entityName.valueBlock.value + }) + }); + } + if (OBJECT_DIGEST_INFO in asn1.result) { + this.objectDigestInfo = new ObjectDigestInfo({ + schema: new Sequence({ + value: asn1.result.objectDigestInfo.valueBlock.value + }) + }); + } + } + toSchema() { + const result = new Sequence(); + if (this.baseCertificateID) { + result.valueBlock.value.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.baseCertificateID.toSchema().valueBlock.value + })); + } + if (this.entityName) { + result.valueBlock.value.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: this.entityName.toSchema().valueBlock.value + })); + } + if (this.objectDigestInfo) { + result.valueBlock.value.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: this.objectDigestInfo.toSchema().valueBlock.value + })); + } + return result; + } + toJSON() { + const result = {}; + if (this.baseCertificateID) { + result.baseCertificateID = this.baseCertificateID.toJSON(); + } + if (this.entityName) { + result.entityName = this.entityName.toJSON(); + } + if (this.objectDigestInfo) { + result.objectDigestInfo = this.objectDigestInfo.toJSON(); + } + return result; + } +} Holder.CLASS_NAME = "Holder"; -const VERSION$g = "version"; -const HOLDER = "holder"; -const ISSUER$3 = "issuer"; -const SIGNATURE$5 = "signature"; -const SERIAL_NUMBER$4 = "serialNumber"; -const ATTR_CERT_VALIDITY_PERIOD = "attrCertValidityPeriod"; -const ATTRIBUTES$2 = "attributes"; -const ISSUER_UNIQUE_ID$1 = "issuerUniqueID"; -const EXTENSIONS$3 = "extensions"; -const CLEAR_PROPS$U = [ - VERSION$g, - HOLDER, - ISSUER$3, - SIGNATURE$5, - SERIAL_NUMBER$4, - ATTR_CERT_VALIDITY_PERIOD, - ATTRIBUTES$2, - ISSUER_UNIQUE_ID$1, - EXTENSIONS$3 -]; -class AttributeCertificateInfoV2 extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$g, AttributeCertificateInfoV2.defaultValues(VERSION$g)); - this.holder = getParametersValue(parameters, HOLDER, AttributeCertificateInfoV2.defaultValues(HOLDER)); - this.issuer = getParametersValue(parameters, ISSUER$3, AttributeCertificateInfoV2.defaultValues(ISSUER$3)); - this.signature = getParametersValue(parameters, SIGNATURE$5, AttributeCertificateInfoV2.defaultValues(SIGNATURE$5)); - this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$4, AttributeCertificateInfoV2.defaultValues(SERIAL_NUMBER$4)); - this.attrCertValidityPeriod = getParametersValue(parameters, ATTR_CERT_VALIDITY_PERIOD, AttributeCertificateInfoV2.defaultValues(ATTR_CERT_VALIDITY_PERIOD)); - this.attributes = getParametersValue(parameters, ATTRIBUTES$2, AttributeCertificateInfoV2.defaultValues(ATTRIBUTES$2)); - if (ISSUER_UNIQUE_ID$1 in parameters) { - this.issuerUniqueID = getParametersValue(parameters, ISSUER_UNIQUE_ID$1, AttributeCertificateInfoV2.defaultValues(ISSUER_UNIQUE_ID$1)); - } - if (EXTENSIONS$3 in parameters) { - this.extensions = getParametersValue(parameters, EXTENSIONS$3, AttributeCertificateInfoV2.defaultValues(EXTENSIONS$3)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$g: - return 1; - case HOLDER: - return new Holder(); - case ISSUER$3: - return {}; - case SIGNATURE$5: - return new AlgorithmIdentifier(); - case SERIAL_NUMBER$4: - return new Integer(); - case ATTR_CERT_VALIDITY_PERIOD: - return new AttCertValidityPeriod(); - case ATTRIBUTES$2: - return []; - case ISSUER_UNIQUE_ID$1: - return new BitString(); - case EXTENSIONS$3: - return new Extensions(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - Holder.schema(names.holder || {}), - new Choice({ - value: [ - GeneralNames.schema({ - names: { - blockName: (names.issuer || EMPTY_STRING) - } - }), - new Constructed({ - name: (names.issuer || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: V2Form.schema().valueBlock.value - }) - ] - }), - AlgorithmIdentifier.schema(names.signature || {}), - new Integer({ name: (names.serialNumber || EMPTY_STRING) }), - AttCertValidityPeriod.schema(names.attrCertValidityPeriod || {}), - new Sequence({ - name: (names.attributes || EMPTY_STRING), - value: [ - new Repeated({ - value: Attribute.schema() - }) - ] - }), - new BitString({ - optional: true, - name: (names.issuerUniqueID || EMPTY_STRING) - }), - Extensions.schema(names.extensions || {}, true) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$U); - const asn1 = compareSchema(schema, schema, AttributeCertificateInfoV2.schema({ - names: { - version: VERSION$g, - holder: { - names: { - blockName: HOLDER - } - }, - issuer: ISSUER$3, - signature: { - names: { - blockName: SIGNATURE$5 - } - }, - serialNumber: SERIAL_NUMBER$4, - attrCertValidityPeriod: { - names: { - blockName: ATTR_CERT_VALIDITY_PERIOD - } - }, - attributes: ATTRIBUTES$2, - issuerUniqueID: ISSUER_UNIQUE_ID$1, - extensions: { - names: { - blockName: EXTENSIONS$3 - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.holder = new Holder({ schema: asn1.result.holder }); - switch (asn1.result.issuer.idBlock.tagClass) { - case 3: - this.issuer = new V2Form({ - schema: new Sequence({ - value: asn1.result.issuer.valueBlock.value - }) - }); - break; - case 1: - default: - throw new Error("Incorrect value for 'issuer' in AttributeCertificateInfoV2"); - } - this.signature = new AlgorithmIdentifier({ schema: asn1.result.signature }); - this.serialNumber = asn1.result.serialNumber; - this.attrCertValidityPeriod = new AttCertValidityPeriod({ schema: asn1.result.attrCertValidityPeriod }); - this.attributes = Array.from(asn1.result.attributes.valueBlock.value, element => new Attribute({ schema: element })); - if (ISSUER_UNIQUE_ID$1 in asn1.result) { - this.issuerUniqueID = asn1.result.issuerUniqueID; - } - if (EXTENSIONS$3 in asn1.result) { - this.extensions = new Extensions({ schema: asn1.result.extensions }); - } - } - toSchema() { - const result = new Sequence({ - value: [ - new Integer({ value: this.version }), - this.holder.toSchema(), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.issuer.toSchema().valueBlock.value - }), - this.signature.toSchema(), - this.serialNumber, - this.attrCertValidityPeriod.toSchema(), - new Sequence({ - value: Array.from(this.attributes, o => o.toSchema()) - }) - ] - }); - if (this.issuerUniqueID) { - result.valueBlock.value.push(this.issuerUniqueID); - } - if (this.extensions) { - result.valueBlock.value.push(this.extensions.toSchema()); - } - return result; - } - toJSON() { - const result = { - version: this.version, - holder: this.holder.toJSON(), - issuer: this.issuer.toJSON(), - signature: this.signature.toJSON(), - serialNumber: this.serialNumber.toJSON(), - attrCertValidityPeriod: this.attrCertValidityPeriod.toJSON(), - attributes: Array.from(this.attributes, o => o.toJSON()) - }; - if (this.issuerUniqueID) { - result.issuerUniqueID = this.issuerUniqueID.toJSON(); - } - if (this.extensions) { - result.extensions = this.extensions.toJSON(); - } - return result; - } -} +const VERSION$g = "version"; +const HOLDER = "holder"; +const ISSUER$3 = "issuer"; +const SIGNATURE$5 = "signature"; +const SERIAL_NUMBER$4 = "serialNumber"; +const ATTR_CERT_VALIDITY_PERIOD = "attrCertValidityPeriod"; +const ATTRIBUTES$2 = "attributes"; +const ISSUER_UNIQUE_ID$1 = "issuerUniqueID"; +const EXTENSIONS$3 = "extensions"; +const CLEAR_PROPS$U = [ + VERSION$g, + HOLDER, + ISSUER$3, + SIGNATURE$5, + SERIAL_NUMBER$4, + ATTR_CERT_VALIDITY_PERIOD, + ATTRIBUTES$2, + ISSUER_UNIQUE_ID$1, + EXTENSIONS$3 +]; +class AttributeCertificateInfoV2 extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$g, AttributeCertificateInfoV2.defaultValues(VERSION$g)); + this.holder = getParametersValue(parameters, HOLDER, AttributeCertificateInfoV2.defaultValues(HOLDER)); + this.issuer = getParametersValue(parameters, ISSUER$3, AttributeCertificateInfoV2.defaultValues(ISSUER$3)); + this.signature = getParametersValue(parameters, SIGNATURE$5, AttributeCertificateInfoV2.defaultValues(SIGNATURE$5)); + this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$4, AttributeCertificateInfoV2.defaultValues(SERIAL_NUMBER$4)); + this.attrCertValidityPeriod = getParametersValue(parameters, ATTR_CERT_VALIDITY_PERIOD, AttributeCertificateInfoV2.defaultValues(ATTR_CERT_VALIDITY_PERIOD)); + this.attributes = getParametersValue(parameters, ATTRIBUTES$2, AttributeCertificateInfoV2.defaultValues(ATTRIBUTES$2)); + if (ISSUER_UNIQUE_ID$1 in parameters) { + this.issuerUniqueID = getParametersValue(parameters, ISSUER_UNIQUE_ID$1, AttributeCertificateInfoV2.defaultValues(ISSUER_UNIQUE_ID$1)); + } + if (EXTENSIONS$3 in parameters) { + this.extensions = getParametersValue(parameters, EXTENSIONS$3, AttributeCertificateInfoV2.defaultValues(EXTENSIONS$3)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$g: + return 1; + case HOLDER: + return new Holder(); + case ISSUER$3: + return {}; + case SIGNATURE$5: + return new AlgorithmIdentifier(); + case SERIAL_NUMBER$4: + return new Integer(); + case ATTR_CERT_VALIDITY_PERIOD: + return new AttCertValidityPeriod(); + case ATTRIBUTES$2: + return []; + case ISSUER_UNIQUE_ID$1: + return new BitString(); + case EXTENSIONS$3: + return new Extensions(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + Holder.schema(names.holder || {}), + new Choice({ + value: [ + GeneralNames.schema({ + names: { + blockName: (names.issuer || EMPTY_STRING) + } + }), + new Constructed({ + name: (names.issuer || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: V2Form.schema().valueBlock.value + }) + ] + }), + AlgorithmIdentifier.schema(names.signature || {}), + new Integer({ name: (names.serialNumber || EMPTY_STRING) }), + AttCertValidityPeriod.schema(names.attrCertValidityPeriod || {}), + new Sequence({ + name: (names.attributes || EMPTY_STRING), + value: [ + new Repeated({ + value: Attribute.schema() + }) + ] + }), + new BitString({ + optional: true, + name: (names.issuerUniqueID || EMPTY_STRING) + }), + Extensions.schema(names.extensions || {}, true) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$U); + const asn1 = compareSchema(schema, schema, AttributeCertificateInfoV2.schema({ + names: { + version: VERSION$g, + holder: { + names: { + blockName: HOLDER + } + }, + issuer: ISSUER$3, + signature: { + names: { + blockName: SIGNATURE$5 + } + }, + serialNumber: SERIAL_NUMBER$4, + attrCertValidityPeriod: { + names: { + blockName: ATTR_CERT_VALIDITY_PERIOD + } + }, + attributes: ATTRIBUTES$2, + issuerUniqueID: ISSUER_UNIQUE_ID$1, + extensions: { + names: { + blockName: EXTENSIONS$3 + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.holder = new Holder({ schema: asn1.result.holder }); + switch (asn1.result.issuer.idBlock.tagClass) { + case 3: + this.issuer = new V2Form({ + schema: new Sequence({ + value: asn1.result.issuer.valueBlock.value + }) + }); + break; + case 1: + default: + throw new Error("Incorrect value for 'issuer' in AttributeCertificateInfoV2"); + } + this.signature = new AlgorithmIdentifier({ schema: asn1.result.signature }); + this.serialNumber = asn1.result.serialNumber; + this.attrCertValidityPeriod = new AttCertValidityPeriod({ schema: asn1.result.attrCertValidityPeriod }); + this.attributes = Array.from(asn1.result.attributes.valueBlock.value, element => new Attribute({ schema: element })); + if (ISSUER_UNIQUE_ID$1 in asn1.result) { + this.issuerUniqueID = asn1.result.issuerUniqueID; + } + if (EXTENSIONS$3 in asn1.result) { + this.extensions = new Extensions({ schema: asn1.result.extensions }); + } + } + toSchema() { + const result = new Sequence({ + value: [ + new Integer({ value: this.version }), + this.holder.toSchema(), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.issuer.toSchema().valueBlock.value + }), + this.signature.toSchema(), + this.serialNumber, + this.attrCertValidityPeriod.toSchema(), + new Sequence({ + value: Array.from(this.attributes, o => o.toSchema()) + }) + ] + }); + if (this.issuerUniqueID) { + result.valueBlock.value.push(this.issuerUniqueID); + } + if (this.extensions) { + result.valueBlock.value.push(this.extensions.toSchema()); + } + return result; + } + toJSON() { + const result = { + version: this.version, + holder: this.holder.toJSON(), + issuer: this.issuer.toJSON(), + signature: this.signature.toJSON(), + serialNumber: this.serialNumber.toJSON(), + attrCertValidityPeriod: this.attrCertValidityPeriod.toJSON(), + attributes: Array.from(this.attributes, o => o.toJSON()) + }; + if (this.issuerUniqueID) { + result.issuerUniqueID = this.issuerUniqueID.toJSON(); + } + if (this.extensions) { + result.extensions = this.extensions.toJSON(); + } + return result; + } +} AttributeCertificateInfoV2.CLASS_NAME = "AttributeCertificateInfoV2"; -const ACINFO = "acinfo"; -const SIGNATURE_ALGORITHM$6 = "signatureAlgorithm"; -const SIGNATURE_VALUE$3 = "signatureValue"; -const CLEAR_PROPS$T = [ - ACINFO, - SIGNATURE_ALGORITHM$6, - SIGNATURE_VALUE$3, -]; -class AttributeCertificateV2 extends PkiObject { - constructor(parameters = {}) { - super(); - this.acinfo = getParametersValue(parameters, ACINFO, AttributeCertificateV2.defaultValues(ACINFO)); - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$6, AttributeCertificateV2.defaultValues(SIGNATURE_ALGORITHM$6)); - this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$3, AttributeCertificateV2.defaultValues(SIGNATURE_VALUE$3)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ACINFO: - return new AttributeCertificateInfoV2(); - case SIGNATURE_ALGORITHM$6: - return new AlgorithmIdentifier(); - case SIGNATURE_VALUE$3: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AttributeCertificateInfoV2.schema(names.acinfo || {}), - AlgorithmIdentifier.schema(names.signatureAlgorithm || {}), - new BitString({ name: (names.signatureValue || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$T); - const asn1 = compareSchema(schema, schema, AttributeCertificateV2.schema({ - names: { - acinfo: { - names: { - blockName: ACINFO - } - }, - signatureAlgorithm: { - names: { - blockName: SIGNATURE_ALGORITHM$6 - } - }, - signatureValue: SIGNATURE_VALUE$3 - } - })); - AsnError.assertSchema(asn1, this.className); - this.acinfo = new AttributeCertificateInfoV2({ schema: asn1.result.acinfo }); - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); - this.signatureValue = asn1.result.signatureValue; - } - toSchema() { - return (new Sequence({ - value: [ - this.acinfo.toSchema(), - this.signatureAlgorithm.toSchema(), - this.signatureValue - ] - })); - } - toJSON() { - return { - acinfo: this.acinfo.toJSON(), - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signatureValue: this.signatureValue.toJSON(), - }; - } -} +const ACINFO = "acinfo"; +const SIGNATURE_ALGORITHM$6 = "signatureAlgorithm"; +const SIGNATURE_VALUE$3 = "signatureValue"; +const CLEAR_PROPS$T = [ + ACINFO, + SIGNATURE_ALGORITHM$6, + SIGNATURE_VALUE$3, +]; +class AttributeCertificateV2 extends PkiObject { + constructor(parameters = {}) { + super(); + this.acinfo = getParametersValue(parameters, ACINFO, AttributeCertificateV2.defaultValues(ACINFO)); + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$6, AttributeCertificateV2.defaultValues(SIGNATURE_ALGORITHM$6)); + this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$3, AttributeCertificateV2.defaultValues(SIGNATURE_VALUE$3)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ACINFO: + return new AttributeCertificateInfoV2(); + case SIGNATURE_ALGORITHM$6: + return new AlgorithmIdentifier(); + case SIGNATURE_VALUE$3: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AttributeCertificateInfoV2.schema(names.acinfo || {}), + AlgorithmIdentifier.schema(names.signatureAlgorithm || {}), + new BitString({ name: (names.signatureValue || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$T); + const asn1 = compareSchema(schema, schema, AttributeCertificateV2.schema({ + names: { + acinfo: { + names: { + blockName: ACINFO + } + }, + signatureAlgorithm: { + names: { + blockName: SIGNATURE_ALGORITHM$6 + } + }, + signatureValue: SIGNATURE_VALUE$3 + } + })); + AsnError.assertSchema(asn1, this.className); + this.acinfo = new AttributeCertificateInfoV2({ schema: asn1.result.acinfo }); + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); + this.signatureValue = asn1.result.signatureValue; + } + toSchema() { + return (new Sequence({ + value: [ + this.acinfo.toSchema(), + this.signatureAlgorithm.toSchema(), + this.signatureValue + ] + })); + } + toJSON() { + return { + acinfo: this.acinfo.toJSON(), + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signatureValue: this.signatureValue.toJSON(), + }; + } +} AttributeCertificateV2.CLASS_NAME = "AttributeCertificateV2"; -const CONTENT_TYPE = "contentType"; -const CONTENT = "content"; -const CLEAR_PROPS$S = [CONTENT_TYPE, CONTENT]; -class ContentInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.contentType = getParametersValue(parameters, CONTENT_TYPE, ContentInfo.defaultValues(CONTENT_TYPE)); - this.content = getParametersValue(parameters, CONTENT, ContentInfo.defaultValues(CONTENT)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CONTENT_TYPE: - return EMPTY_STRING; - case CONTENT: - return new Any(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case CONTENT_TYPE: - return (typeof memberValue === "string" && - memberValue === this.defaultValues(CONTENT_TYPE)); - case CONTENT: - return (memberValue instanceof Any); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - if (("optional" in names) === false) { - names.optional = false; - } - return (new Sequence({ - name: (names.blockName || "ContentInfo"), - optional: names.optional, - value: [ - new ObjectIdentifier({ name: (names.contentType || CONTENT_TYPE) }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Any({ name: (names.content || CONTENT) })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$S); - const asn1 = compareSchema(schema, schema, ContentInfo.schema()); - AsnError.assertSchema(asn1, this.className); - this.contentType = asn1.result.contentType.valueBlock.toString(); - this.content = asn1.result.content; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.contentType }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.content] - }) - ] - })); - } - toJSON() { - const object = { - contentType: this.contentType - }; - if (!(this.content instanceof Any)) { - object.content = this.content.toJSON(); - } - return object; - } -} -ContentInfo.CLASS_NAME = "ContentInfo"; -ContentInfo.DATA = id_ContentType_Data; -ContentInfo.SIGNED_DATA = id_ContentType_SignedData; -ContentInfo.ENVELOPED_DATA = id_ContentType_EnvelopedData; -ContentInfo.ENCRYPTED_DATA = id_ContentType_EncryptedData; - -const TYPE$1 = "type"; -const VALUE$4 = "value"; -const UTC_TIME_NAME = "utcTimeName"; -const GENERAL_TIME_NAME = "generalTimeName"; -const CLEAR_PROPS$R = [UTC_TIME_NAME, GENERAL_TIME_NAME]; -var TimeType; -(function (TimeType) { - TimeType[TimeType["UTCTime"] = 0] = "UTCTime"; - TimeType[TimeType["GeneralizedTime"] = 1] = "GeneralizedTime"; - TimeType[TimeType["empty"] = 2] = "empty"; -})(TimeType || (TimeType = {})); -class Time extends PkiObject { - constructor(parameters = {}) { - super(); - this.type = getParametersValue(parameters, TYPE$1, Time.defaultValues(TYPE$1)); - this.value = getParametersValue(parameters, VALUE$4, Time.defaultValues(VALUE$4)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TYPE$1: - return 0; - case VALUE$4: - return new Date(0, 0, 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}, optional = false) { - const names = getParametersValue(parameters, "names", {}); - return (new Choice({ - optional, - value: [ - new UTCTime({ name: (names.utcTimeName || EMPTY_STRING) }), - new GeneralizedTime({ name: (names.generalTimeName || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$R); - const asn1 = compareSchema(schema, schema, Time.schema({ - names: { - utcTimeName: UTC_TIME_NAME, - generalTimeName: GENERAL_TIME_NAME - } - })); - AsnError.assertSchema(asn1, this.className); - if (UTC_TIME_NAME in asn1.result) { - this.type = 0; - this.value = asn1.result.utcTimeName.toDate(); - } - if (GENERAL_TIME_NAME in asn1.result) { - this.type = 1; - this.value = asn1.result.generalTimeName.toDate(); - } - } - toSchema() { - if (this.type === 0) { - return new UTCTime({ valueDate: this.value }); - } - else if (this.type === 1) { - return new GeneralizedTime({ valueDate: this.value }); - } - return {}; - } - toJSON() { - return { - type: this.type, - value: this.value - }; - } -} -Time.CLASS_NAME = "Time"; - -const TBS$4 = "tbs"; -const VERSION$f = "version"; -const SERIAL_NUMBER$3 = "serialNumber"; -const SIGNATURE$4 = "signature"; -const ISSUER$2 = "issuer"; -const NOT_BEFORE = "notBefore"; -const NOT_AFTER = "notAfter"; -const SUBJECT$1 = "subject"; -const SUBJECT_PUBLIC_KEY_INFO = "subjectPublicKeyInfo"; -const ISSUER_UNIQUE_ID = "issuerUniqueID"; -const SUBJECT_UNIQUE_ID = "subjectUniqueID"; -const EXTENSIONS$2 = "extensions"; -const SIGNATURE_ALGORITHM$5 = "signatureAlgorithm"; -const SIGNATURE_VALUE$2 = "signatureValue"; -const TBS_CERTIFICATE = "tbsCertificate"; -const TBS_CERTIFICATE_VERSION = `${TBS_CERTIFICATE}.${VERSION$f}`; -const TBS_CERTIFICATE_SERIAL_NUMBER = `${TBS_CERTIFICATE}.${SERIAL_NUMBER$3}`; -const TBS_CERTIFICATE_SIGNATURE = `${TBS_CERTIFICATE}.${SIGNATURE$4}`; -const TBS_CERTIFICATE_ISSUER = `${TBS_CERTIFICATE}.${ISSUER$2}`; -const TBS_CERTIFICATE_NOT_BEFORE = `${TBS_CERTIFICATE}.${NOT_BEFORE}`; -const TBS_CERTIFICATE_NOT_AFTER = `${TBS_CERTIFICATE}.${NOT_AFTER}`; -const TBS_CERTIFICATE_SUBJECT = `${TBS_CERTIFICATE}.${SUBJECT$1}`; -const TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY = `${TBS_CERTIFICATE}.${SUBJECT_PUBLIC_KEY_INFO}`; -const TBS_CERTIFICATE_ISSUER_UNIQUE_ID = `${TBS_CERTIFICATE}.${ISSUER_UNIQUE_ID}`; -const TBS_CERTIFICATE_SUBJECT_UNIQUE_ID = `${TBS_CERTIFICATE}.${SUBJECT_UNIQUE_ID}`; -const TBS_CERTIFICATE_EXTENSIONS = `${TBS_CERTIFICATE}.${EXTENSIONS$2}`; -const CLEAR_PROPS$Q = [ - TBS_CERTIFICATE, - TBS_CERTIFICATE_VERSION, - TBS_CERTIFICATE_SERIAL_NUMBER, - TBS_CERTIFICATE_SIGNATURE, - TBS_CERTIFICATE_ISSUER, - TBS_CERTIFICATE_NOT_BEFORE, - TBS_CERTIFICATE_NOT_AFTER, - TBS_CERTIFICATE_SUBJECT, - TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY, - TBS_CERTIFICATE_ISSUER_UNIQUE_ID, - TBS_CERTIFICATE_SUBJECT_UNIQUE_ID, - TBS_CERTIFICATE_EXTENSIONS, - SIGNATURE_ALGORITHM$5, - SIGNATURE_VALUE$2 -]; -function tbsCertificate(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || TBS_CERTIFICATE), - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Integer({ name: (names.tbsCertificateVersion || TBS_CERTIFICATE_VERSION) }) - ] - }), - new Integer({ name: (names.tbsCertificateSerialNumber || TBS_CERTIFICATE_SERIAL_NUMBER) }), - AlgorithmIdentifier.schema(names.signature || { - names: { - blockName: TBS_CERTIFICATE_SIGNATURE - } - }), - RelativeDistinguishedNames.schema(names.issuer || { - names: { - blockName: TBS_CERTIFICATE_ISSUER - } - }), - new Sequence({ - name: (names.tbsCertificateValidity || "tbsCertificate.validity"), - value: [ - Time.schema(names.notBefore || { - names: { - utcTimeName: TBS_CERTIFICATE_NOT_BEFORE, - generalTimeName: TBS_CERTIFICATE_NOT_BEFORE - } - }), - Time.schema(names.notAfter || { - names: { - utcTimeName: TBS_CERTIFICATE_NOT_AFTER, - generalTimeName: TBS_CERTIFICATE_NOT_AFTER - } - }) - ] - }), - RelativeDistinguishedNames.schema(names.subject || { - names: { - blockName: TBS_CERTIFICATE_SUBJECT - } - }), - PublicKeyInfo.schema(names.subjectPublicKeyInfo || { - names: { - blockName: TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY - } - }), - new Primitive({ - name: (names.tbsCertificateIssuerUniqueID || TBS_CERTIFICATE_ISSUER_UNIQUE_ID), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - } - }), - new Primitive({ - name: (names.tbsCertificateSubjectUniqueID || TBS_CERTIFICATE_SUBJECT_UNIQUE_ID), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - } - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - value: [Extensions.schema(names.extensions || { - names: { - blockName: TBS_CERTIFICATE_EXTENSIONS - } - })] - }) - ] - })); -} -class Certificate extends PkiObject { - constructor(parameters = {}) { - super(); - this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$4, Certificate.defaultValues(TBS$4))); - this.version = getParametersValue(parameters, VERSION$f, Certificate.defaultValues(VERSION$f)); - this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$3, Certificate.defaultValues(SERIAL_NUMBER$3)); - this.signature = getParametersValue(parameters, SIGNATURE$4, Certificate.defaultValues(SIGNATURE$4)); - this.issuer = getParametersValue(parameters, ISSUER$2, Certificate.defaultValues(ISSUER$2)); - this.notBefore = getParametersValue(parameters, NOT_BEFORE, Certificate.defaultValues(NOT_BEFORE)); - this.notAfter = getParametersValue(parameters, NOT_AFTER, Certificate.defaultValues(NOT_AFTER)); - this.subject = getParametersValue(parameters, SUBJECT$1, Certificate.defaultValues(SUBJECT$1)); - this.subjectPublicKeyInfo = getParametersValue(parameters, SUBJECT_PUBLIC_KEY_INFO, Certificate.defaultValues(SUBJECT_PUBLIC_KEY_INFO)); - if (ISSUER_UNIQUE_ID in parameters) { - this.issuerUniqueID = getParametersValue(parameters, ISSUER_UNIQUE_ID, Certificate.defaultValues(ISSUER_UNIQUE_ID)); - } - if (SUBJECT_UNIQUE_ID in parameters) { - this.subjectUniqueID = getParametersValue(parameters, SUBJECT_UNIQUE_ID, Certificate.defaultValues(SUBJECT_UNIQUE_ID)); - } - if (EXTENSIONS$2 in parameters) { - this.extensions = getParametersValue(parameters, EXTENSIONS$2, Certificate.defaultValues(EXTENSIONS$2)); - } - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$5, Certificate.defaultValues(SIGNATURE_ALGORITHM$5)); - this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$2, Certificate.defaultValues(SIGNATURE_VALUE$2)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - get tbs() { - return BufferSourceConverter.toArrayBuffer(this.tbsView); - } - set tbs(value) { - this.tbsView = new Uint8Array(value); - } - static defaultValues(memberName) { - switch (memberName) { - case TBS$4: - return EMPTY_BUFFER; - case VERSION$f: - return 0; - case SERIAL_NUMBER$3: - return new Integer(); - case SIGNATURE$4: - return new AlgorithmIdentifier(); - case ISSUER$2: - return new RelativeDistinguishedNames(); - case NOT_BEFORE: - return new Time(); - case NOT_AFTER: - return new Time(); - case SUBJECT$1: - return new RelativeDistinguishedNames(); - case SUBJECT_PUBLIC_KEY_INFO: - return new PublicKeyInfo(); - case ISSUER_UNIQUE_ID: - return EMPTY_BUFFER; - case SUBJECT_UNIQUE_ID: - return EMPTY_BUFFER; - case EXTENSIONS$2: - return []; - case SIGNATURE_ALGORITHM$5: - return new AlgorithmIdentifier(); - case SIGNATURE_VALUE$2: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - tbsCertificate(names.tbsCertificate), - AlgorithmIdentifier.schema(names.signatureAlgorithm || { - names: { - blockName: SIGNATURE_ALGORITHM$5 - } - }), - new BitString({ name: (names.signatureValue || SIGNATURE_VALUE$2) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$Q); - const asn1 = compareSchema(schema, schema, Certificate.schema({ - names: { - tbsCertificate: { - names: { - extensions: { - names: { - extensions: TBS_CERTIFICATE_EXTENSIONS - } - } - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.tbsView = asn1.result.tbsCertificate.valueBeforeDecodeView; - if (TBS_CERTIFICATE_VERSION in asn1.result) - this.version = asn1.result[TBS_CERTIFICATE_VERSION].valueBlock.valueDec; - this.serialNumber = asn1.result[TBS_CERTIFICATE_SERIAL_NUMBER]; - this.signature = new AlgorithmIdentifier({ schema: asn1.result[TBS_CERTIFICATE_SIGNATURE] }); - this.issuer = new RelativeDistinguishedNames({ schema: asn1.result[TBS_CERTIFICATE_ISSUER] }); - this.notBefore = new Time({ schema: asn1.result[TBS_CERTIFICATE_NOT_BEFORE] }); - this.notAfter = new Time({ schema: asn1.result[TBS_CERTIFICATE_NOT_AFTER] }); - this.subject = new RelativeDistinguishedNames({ schema: asn1.result[TBS_CERTIFICATE_SUBJECT] }); - this.subjectPublicKeyInfo = new PublicKeyInfo({ schema: asn1.result[TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY] }); - if (TBS_CERTIFICATE_ISSUER_UNIQUE_ID in asn1.result) - this.issuerUniqueID = asn1.result[TBS_CERTIFICATE_ISSUER_UNIQUE_ID].valueBlock.valueHex; - if (TBS_CERTIFICATE_SUBJECT_UNIQUE_ID in asn1.result) - this.subjectUniqueID = asn1.result[TBS_CERTIFICATE_SUBJECT_UNIQUE_ID].valueBlock.valueHex; - if (TBS_CERTIFICATE_EXTENSIONS in asn1.result) - this.extensions = Array.from(asn1.result[TBS_CERTIFICATE_EXTENSIONS], element => new Extension({ schema: element })); - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); - this.signatureValue = asn1.result.signatureValue; - } - encodeTBS() { - const outputArray = []; - if ((VERSION$f in this) && (this.version !== Certificate.defaultValues(VERSION$f))) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Integer({ value: this.version }) - ] - })); - } - outputArray.push(this.serialNumber); - outputArray.push(this.signature.toSchema()); - outputArray.push(this.issuer.toSchema()); - outputArray.push(new Sequence({ - value: [ - this.notBefore.toSchema(), - this.notAfter.toSchema() - ] - })); - outputArray.push(this.subject.toSchema()); - outputArray.push(this.subjectPublicKeyInfo.toSchema()); - if (this.issuerUniqueID) { - outputArray.push(new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - valueHex: this.issuerUniqueID - })); - } - if (this.subjectUniqueID) { - outputArray.push(new Primitive({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - valueHex: this.subjectUniqueID - })); - } - if (this.extensions) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - value: [new Sequence({ - value: Array.from(this.extensions, o => o.toSchema()) - })] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toSchema(encodeFlag = false) { - let tbsSchema; - if (encodeFlag === false) { - if (!this.tbsView.byteLength) { - return Certificate.schema().value[0]; - } - const asn1 = fromBER(this.tbsView); - AsnError.assert(asn1, "TBS Certificate"); - tbsSchema = asn1.result; - } - else { - tbsSchema = this.encodeTBS(); - } - return (new Sequence({ - value: [ - tbsSchema, - this.signatureAlgorithm.toSchema(), - this.signatureValue - ] - })); - } - toJSON() { - const res = { - tbs: Convert.ToHex(this.tbsView), - version: this.version, - serialNumber: this.serialNumber.toJSON(), - signature: this.signature.toJSON(), - issuer: this.issuer.toJSON(), - notBefore: this.notBefore.toJSON(), - notAfter: this.notAfter.toJSON(), - subject: this.subject.toJSON(), - subjectPublicKeyInfo: this.subjectPublicKeyInfo.toJSON(), - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signatureValue: this.signatureValue.toJSON(), - }; - if ((VERSION$f in this) && (this.version !== Certificate.defaultValues(VERSION$f))) { - res.version = this.version; - } - if (this.issuerUniqueID) { - res.issuerUniqueID = Convert.ToHex(this.issuerUniqueID); - } - if (this.subjectUniqueID) { - res.subjectUniqueID = Convert.ToHex(this.subjectUniqueID); - } - if (this.extensions) { - res.extensions = Array.from(this.extensions, o => o.toJSON()); - } - return res; - } - getPublicKey(parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - return crypto.getPublicKey(this.subjectPublicKeyInfo, this.signatureAlgorithm, parameters); - }); - } - getKeyHash(hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - return crypto.digest({ name: hashAlgorithm }, this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); - }); - } - sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - if (!privateKey) { - throw new Error("Need to provide a private key for signing"); - } - const signatureParameters = yield crypto.getSignatureParameters(privateKey, hashAlgorithm); - const parameters = signatureParameters.parameters; - this.signature = signatureParameters.signatureAlgorithm; - this.signatureAlgorithm = signatureParameters.signatureAlgorithm; - this.tbsView = new Uint8Array(this.encodeTBS().toBER()); - const signature = yield crypto.signWithPrivateKey(this.tbsView, privateKey, parameters); - this.signatureValue = new BitString({ valueHex: signature }); - }); - } - verify(issuerCertificate, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - let subjectPublicKeyInfo; - if (issuerCertificate) { - subjectPublicKeyInfo = issuerCertificate.subjectPublicKeyInfo; - } - else if (this.issuer.isEqual(this.subject)) { - subjectPublicKeyInfo = this.subjectPublicKeyInfo; - } - if (!(subjectPublicKeyInfo instanceof PublicKeyInfo)) { - throw new Error("Please provide issuer certificate as a parameter"); - } - return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); - }); - } -} -Certificate.CLASS_NAME = "Certificate"; -function checkCA(cert, signerCert = null) { - if (signerCert && cert.issuer.isEqual(signerCert.issuer) && cert.serialNumber.isEqual(signerCert.serialNumber)) { - return null; - } - let isCA = false; - if (cert.extensions) { - for (const extension of cert.extensions) { - if (extension.extnID === id_BasicConstraints && extension.parsedValue instanceof BasicConstraints) { - if (extension.parsedValue.cA) { - isCA = true; - break; - } - } - } - } - if (isCA) { - return cert; - } - return null; +const CONTENT_TYPE = "contentType"; +const CONTENT = "content"; +const CLEAR_PROPS$S = [CONTENT_TYPE, CONTENT]; +class ContentInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.contentType = getParametersValue(parameters, CONTENT_TYPE, ContentInfo.defaultValues(CONTENT_TYPE)); + this.content = getParametersValue(parameters, CONTENT, ContentInfo.defaultValues(CONTENT)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CONTENT_TYPE: + return EMPTY_STRING; + case CONTENT: + return new Any(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case CONTENT_TYPE: + return (typeof memberValue === "string" && + memberValue === this.defaultValues(CONTENT_TYPE)); + case CONTENT: + return (memberValue instanceof Any); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + if (("optional" in names) === false) { + names.optional = false; + } + return (new Sequence({ + name: (names.blockName || "ContentInfo"), + optional: names.optional, + value: [ + new ObjectIdentifier({ name: (names.contentType || CONTENT_TYPE) }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Any({ name: (names.content || CONTENT) })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$S); + const asn1 = compareSchema(schema, schema, ContentInfo.schema()); + AsnError.assertSchema(asn1, this.className); + this.contentType = asn1.result.contentType.valueBlock.toString(); + this.content = asn1.result.content; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.contentType }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.content] + }) + ] + })); + } + toJSON() { + const object = { + contentType: this.contentType + }; + if (!(this.content instanceof Any)) { + object.content = this.content.toJSON(); + } + return object; + } } +ContentInfo.CLASS_NAME = "ContentInfo"; +ContentInfo.DATA = id_ContentType_Data; +ContentInfo.SIGNED_DATA = id_ContentType_SignedData; +ContentInfo.ENVELOPED_DATA = id_ContentType_EnvelopedData; +ContentInfo.ENCRYPTED_DATA = id_ContentType_EncryptedData; -const CERT_ID$1 = "certId"; -const CERT_VALUE = "certValue"; -const PARSED_VALUE$4 = "parsedValue"; -const CLEAR_PROPS$P = [ - CERT_ID$1, - CERT_VALUE -]; -class CertBag extends PkiObject { - constructor(parameters = {}) { - super(); - this.certId = getParametersValue(parameters, CERT_ID$1, CertBag.defaultValues(CERT_ID$1)); - this.certValue = getParametersValue(parameters, CERT_VALUE, CertBag.defaultValues(CERT_VALUE)); - if (PARSED_VALUE$4 in parameters) { - this.parsedValue = getParametersValue(parameters, PARSED_VALUE$4, CertBag.defaultValues(PARSED_VALUE$4)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CERT_ID$1: - return EMPTY_STRING; - case CERT_VALUE: - return (new Any()); - case PARSED_VALUE$4: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case CERT_ID$1: - return (memberValue === EMPTY_STRING); - case CERT_VALUE: - return (memberValue instanceof Any); - case PARSED_VALUE$4: - return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.id || "id") }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Any({ name: (names.value || "value") })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$P); - const asn1 = compareSchema(schema, schema, CertBag.schema({ - names: { - id: CERT_ID$1, - value: CERT_VALUE - } - })); - AsnError.assertSchema(asn1, this.className); - this.certId = asn1.result.certId.valueBlock.toString(); - this.certValue = asn1.result.certValue; - const certValueHex = this.certValue.valueBlock.valueHexView; - switch (this.certId) { - case id_CertBag_X509Certificate: - { - try { - this.parsedValue = Certificate.fromBER(certValueHex); - } - catch (ex) { - AttributeCertificateV2.fromBER(certValueHex); - } - } - break; - case id_CertBag_AttributeCertificate: - { - this.parsedValue = AttributeCertificateV2.fromBER(certValueHex); - } - break; - case id_CertBag_SDSICertificate: - default: - throw new Error(`Incorrect CERT_ID value in CertBag: ${this.certId}`); - } - } - toSchema() { - if (PARSED_VALUE$4 in this) { - if ("acinfo" in this.parsedValue) { - this.certId = id_CertBag_AttributeCertificate; - } - else { - this.certId = id_CertBag_X509Certificate; - } - this.certValue = new OctetString({ valueHex: this.parsedValue.toSchema().toBER(false) }); - } - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.certId }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [(("toSchema" in this.certValue) ? this.certValue.toSchema() : this.certValue)] - }) - ] - })); - } - toJSON() { - return { - certId: this.certId, - certValue: this.certValue.toJSON() - }; - } -} +const TYPE$1 = "type"; +const VALUE$4 = "value"; +const UTC_TIME_NAME = "utcTimeName"; +const GENERAL_TIME_NAME = "generalTimeName"; +const CLEAR_PROPS$R = [UTC_TIME_NAME, GENERAL_TIME_NAME]; +var TimeType; +(function (TimeType) { + TimeType[TimeType["UTCTime"] = 0] = "UTCTime"; + TimeType[TimeType["GeneralizedTime"] = 1] = "GeneralizedTime"; + TimeType[TimeType["empty"] = 2] = "empty"; +})(TimeType || (TimeType = {})); +class Time extends PkiObject { + constructor(parameters = {}) { + super(); + this.type = getParametersValue(parameters, TYPE$1, Time.defaultValues(TYPE$1)); + this.value = getParametersValue(parameters, VALUE$4, Time.defaultValues(VALUE$4)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TYPE$1: + return 0; + case VALUE$4: + return new Date(0, 0, 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}, optional = false) { + const names = getParametersValue(parameters, "names", {}); + return (new Choice({ + optional, + value: [ + new UTCTime({ name: (names.utcTimeName || EMPTY_STRING) }), + new GeneralizedTime({ name: (names.generalTimeName || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$R); + const asn1 = compareSchema(schema, schema, Time.schema({ + names: { + utcTimeName: UTC_TIME_NAME, + generalTimeName: GENERAL_TIME_NAME + } + })); + AsnError.assertSchema(asn1, this.className); + if (UTC_TIME_NAME in asn1.result) { + this.type = 0; + this.value = asn1.result.utcTimeName.toDate(); + } + if (GENERAL_TIME_NAME in asn1.result) { + this.type = 1; + this.value = asn1.result.generalTimeName.toDate(); + } + } + toSchema() { + if (this.type === 0) { + return new UTCTime({ valueDate: this.value }); + } + else if (this.type === 1) { + return new GeneralizedTime({ valueDate: this.value }); + } + return {}; + } + toJSON() { + return { + type: this.type, + value: this.value + }; + } +} +Time.CLASS_NAME = "Time"; + +const TBS$4 = "tbs"; +const VERSION$f = "version"; +const SERIAL_NUMBER$3 = "serialNumber"; +const SIGNATURE$4 = "signature"; +const ISSUER$2 = "issuer"; +const NOT_BEFORE = "notBefore"; +const NOT_AFTER = "notAfter"; +const SUBJECT$1 = "subject"; +const SUBJECT_PUBLIC_KEY_INFO = "subjectPublicKeyInfo"; +const ISSUER_UNIQUE_ID = "issuerUniqueID"; +const SUBJECT_UNIQUE_ID = "subjectUniqueID"; +const EXTENSIONS$2 = "extensions"; +const SIGNATURE_ALGORITHM$5 = "signatureAlgorithm"; +const SIGNATURE_VALUE$2 = "signatureValue"; +const TBS_CERTIFICATE = "tbsCertificate"; +const TBS_CERTIFICATE_VERSION = `${TBS_CERTIFICATE}.${VERSION$f}`; +const TBS_CERTIFICATE_SERIAL_NUMBER = `${TBS_CERTIFICATE}.${SERIAL_NUMBER$3}`; +const TBS_CERTIFICATE_SIGNATURE = `${TBS_CERTIFICATE}.${SIGNATURE$4}`; +const TBS_CERTIFICATE_ISSUER = `${TBS_CERTIFICATE}.${ISSUER$2}`; +const TBS_CERTIFICATE_NOT_BEFORE = `${TBS_CERTIFICATE}.${NOT_BEFORE}`; +const TBS_CERTIFICATE_NOT_AFTER = `${TBS_CERTIFICATE}.${NOT_AFTER}`; +const TBS_CERTIFICATE_SUBJECT = `${TBS_CERTIFICATE}.${SUBJECT$1}`; +const TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY = `${TBS_CERTIFICATE}.${SUBJECT_PUBLIC_KEY_INFO}`; +const TBS_CERTIFICATE_ISSUER_UNIQUE_ID = `${TBS_CERTIFICATE}.${ISSUER_UNIQUE_ID}`; +const TBS_CERTIFICATE_SUBJECT_UNIQUE_ID = `${TBS_CERTIFICATE}.${SUBJECT_UNIQUE_ID}`; +const TBS_CERTIFICATE_EXTENSIONS = `${TBS_CERTIFICATE}.${EXTENSIONS$2}`; +const CLEAR_PROPS$Q = [ + TBS_CERTIFICATE, + TBS_CERTIFICATE_VERSION, + TBS_CERTIFICATE_SERIAL_NUMBER, + TBS_CERTIFICATE_SIGNATURE, + TBS_CERTIFICATE_ISSUER, + TBS_CERTIFICATE_NOT_BEFORE, + TBS_CERTIFICATE_NOT_AFTER, + TBS_CERTIFICATE_SUBJECT, + TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY, + TBS_CERTIFICATE_ISSUER_UNIQUE_ID, + TBS_CERTIFICATE_SUBJECT_UNIQUE_ID, + TBS_CERTIFICATE_EXTENSIONS, + SIGNATURE_ALGORITHM$5, + SIGNATURE_VALUE$2 +]; +function tbsCertificate(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || TBS_CERTIFICATE), + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Integer({ name: (names.tbsCertificateVersion || TBS_CERTIFICATE_VERSION) }) + ] + }), + new Integer({ name: (names.tbsCertificateSerialNumber || TBS_CERTIFICATE_SERIAL_NUMBER) }), + AlgorithmIdentifier.schema(names.signature || { + names: { + blockName: TBS_CERTIFICATE_SIGNATURE + } + }), + RelativeDistinguishedNames.schema(names.issuer || { + names: { + blockName: TBS_CERTIFICATE_ISSUER + } + }), + new Sequence({ + name: (names.tbsCertificateValidity || "tbsCertificate.validity"), + value: [ + Time.schema(names.notBefore || { + names: { + utcTimeName: TBS_CERTIFICATE_NOT_BEFORE, + generalTimeName: TBS_CERTIFICATE_NOT_BEFORE + } + }), + Time.schema(names.notAfter || { + names: { + utcTimeName: TBS_CERTIFICATE_NOT_AFTER, + generalTimeName: TBS_CERTIFICATE_NOT_AFTER + } + }) + ] + }), + RelativeDistinguishedNames.schema(names.subject || { + names: { + blockName: TBS_CERTIFICATE_SUBJECT + } + }), + PublicKeyInfo.schema(names.subjectPublicKeyInfo || { + names: { + blockName: TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY + } + }), + new Primitive({ + name: (names.tbsCertificateIssuerUniqueID || TBS_CERTIFICATE_ISSUER_UNIQUE_ID), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + } + }), + new Primitive({ + name: (names.tbsCertificateSubjectUniqueID || TBS_CERTIFICATE_SUBJECT_UNIQUE_ID), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + } + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + value: [Extensions.schema(names.extensions || { + names: { + blockName: TBS_CERTIFICATE_EXTENSIONS + } + })] + }) + ] + })); +} +class Certificate extends PkiObject { + get tbs() { + return BufferSourceConverter.toArrayBuffer(this.tbsView); + } + set tbs(value) { + this.tbsView = new Uint8Array(value); + } + constructor(parameters = {}) { + super(); + this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$4, Certificate.defaultValues(TBS$4))); + this.version = getParametersValue(parameters, VERSION$f, Certificate.defaultValues(VERSION$f)); + this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$3, Certificate.defaultValues(SERIAL_NUMBER$3)); + this.signature = getParametersValue(parameters, SIGNATURE$4, Certificate.defaultValues(SIGNATURE$4)); + this.issuer = getParametersValue(parameters, ISSUER$2, Certificate.defaultValues(ISSUER$2)); + this.notBefore = getParametersValue(parameters, NOT_BEFORE, Certificate.defaultValues(NOT_BEFORE)); + this.notAfter = getParametersValue(parameters, NOT_AFTER, Certificate.defaultValues(NOT_AFTER)); + this.subject = getParametersValue(parameters, SUBJECT$1, Certificate.defaultValues(SUBJECT$1)); + this.subjectPublicKeyInfo = getParametersValue(parameters, SUBJECT_PUBLIC_KEY_INFO, Certificate.defaultValues(SUBJECT_PUBLIC_KEY_INFO)); + if (ISSUER_UNIQUE_ID in parameters) { + this.issuerUniqueID = getParametersValue(parameters, ISSUER_UNIQUE_ID, Certificate.defaultValues(ISSUER_UNIQUE_ID)); + } + if (SUBJECT_UNIQUE_ID in parameters) { + this.subjectUniqueID = getParametersValue(parameters, SUBJECT_UNIQUE_ID, Certificate.defaultValues(SUBJECT_UNIQUE_ID)); + } + if (EXTENSIONS$2 in parameters) { + this.extensions = getParametersValue(parameters, EXTENSIONS$2, Certificate.defaultValues(EXTENSIONS$2)); + } + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$5, Certificate.defaultValues(SIGNATURE_ALGORITHM$5)); + this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$2, Certificate.defaultValues(SIGNATURE_VALUE$2)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TBS$4: + return EMPTY_BUFFER; + case VERSION$f: + return 0; + case SERIAL_NUMBER$3: + return new Integer(); + case SIGNATURE$4: + return new AlgorithmIdentifier(); + case ISSUER$2: + return new RelativeDistinguishedNames(); + case NOT_BEFORE: + return new Time(); + case NOT_AFTER: + return new Time(); + case SUBJECT$1: + return new RelativeDistinguishedNames(); + case SUBJECT_PUBLIC_KEY_INFO: + return new PublicKeyInfo(); + case ISSUER_UNIQUE_ID: + return EMPTY_BUFFER; + case SUBJECT_UNIQUE_ID: + return EMPTY_BUFFER; + case EXTENSIONS$2: + return []; + case SIGNATURE_ALGORITHM$5: + return new AlgorithmIdentifier(); + case SIGNATURE_VALUE$2: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + tbsCertificate(names.tbsCertificate), + AlgorithmIdentifier.schema(names.signatureAlgorithm || { + names: { + blockName: SIGNATURE_ALGORITHM$5 + } + }), + new BitString({ name: (names.signatureValue || SIGNATURE_VALUE$2) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$Q); + const asn1 = compareSchema(schema, schema, Certificate.schema({ + names: { + tbsCertificate: { + names: { + extensions: { + names: { + extensions: TBS_CERTIFICATE_EXTENSIONS + } + } + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.tbsView = asn1.result.tbsCertificate.valueBeforeDecodeView; + if (TBS_CERTIFICATE_VERSION in asn1.result) + this.version = asn1.result[TBS_CERTIFICATE_VERSION].valueBlock.valueDec; + this.serialNumber = asn1.result[TBS_CERTIFICATE_SERIAL_NUMBER]; + this.signature = new AlgorithmIdentifier({ schema: asn1.result[TBS_CERTIFICATE_SIGNATURE] }); + this.issuer = new RelativeDistinguishedNames({ schema: asn1.result[TBS_CERTIFICATE_ISSUER] }); + this.notBefore = new Time({ schema: asn1.result[TBS_CERTIFICATE_NOT_BEFORE] }); + this.notAfter = new Time({ schema: asn1.result[TBS_CERTIFICATE_NOT_AFTER] }); + this.subject = new RelativeDistinguishedNames({ schema: asn1.result[TBS_CERTIFICATE_SUBJECT] }); + this.subjectPublicKeyInfo = new PublicKeyInfo({ schema: asn1.result[TBS_CERTIFICATE_SUBJECT_PUBLIC_KEY] }); + if (TBS_CERTIFICATE_ISSUER_UNIQUE_ID in asn1.result) + this.issuerUniqueID = asn1.result[TBS_CERTIFICATE_ISSUER_UNIQUE_ID].valueBlock.valueHex; + if (TBS_CERTIFICATE_SUBJECT_UNIQUE_ID in asn1.result) + this.subjectUniqueID = asn1.result[TBS_CERTIFICATE_SUBJECT_UNIQUE_ID].valueBlock.valueHex; + if (TBS_CERTIFICATE_EXTENSIONS in asn1.result) + this.extensions = Array.from(asn1.result[TBS_CERTIFICATE_EXTENSIONS], element => new Extension({ schema: element })); + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); + this.signatureValue = asn1.result.signatureValue; + } + encodeTBS() { + const outputArray = []; + if ((VERSION$f in this) && (this.version !== Certificate.defaultValues(VERSION$f))) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Integer({ value: this.version }) + ] + })); + } + outputArray.push(this.serialNumber); + outputArray.push(this.signature.toSchema()); + outputArray.push(this.issuer.toSchema()); + outputArray.push(new Sequence({ + value: [ + this.notBefore.toSchema(), + this.notAfter.toSchema() + ] + })); + outputArray.push(this.subject.toSchema()); + outputArray.push(this.subjectPublicKeyInfo.toSchema()); + if (this.issuerUniqueID) { + outputArray.push(new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + valueHex: this.issuerUniqueID + })); + } + if (this.subjectUniqueID) { + outputArray.push(new Primitive({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + valueHex: this.subjectUniqueID + })); + } + if (this.extensions) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + value: [new Sequence({ + value: Array.from(this.extensions, o => o.toSchema()) + })] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toSchema(encodeFlag = false) { + let tbsSchema; + if (encodeFlag === false) { + if (!this.tbsView.byteLength) { + return Certificate.schema().value[0]; + } + const asn1 = fromBER(this.tbsView); + AsnError.assert(asn1, "TBS Certificate"); + tbsSchema = asn1.result; + } + else { + tbsSchema = this.encodeTBS(); + } + return (new Sequence({ + value: [ + tbsSchema, + this.signatureAlgorithm.toSchema(), + this.signatureValue + ] + })); + } + toJSON() { + const res = { + tbs: Convert.ToHex(this.tbsView), + version: this.version, + serialNumber: this.serialNumber.toJSON(), + signature: this.signature.toJSON(), + issuer: this.issuer.toJSON(), + notBefore: this.notBefore.toJSON(), + notAfter: this.notAfter.toJSON(), + subject: this.subject.toJSON(), + subjectPublicKeyInfo: this.subjectPublicKeyInfo.toJSON(), + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signatureValue: this.signatureValue.toJSON(), + }; + if ((VERSION$f in this) && (this.version !== Certificate.defaultValues(VERSION$f))) { + res.version = this.version; + } + if (this.issuerUniqueID) { + res.issuerUniqueID = Convert.ToHex(this.issuerUniqueID); + } + if (this.subjectUniqueID) { + res.subjectUniqueID = Convert.ToHex(this.subjectUniqueID); + } + if (this.extensions) { + res.extensions = Array.from(this.extensions, o => o.toJSON()); + } + return res; + } + async getPublicKey(parameters, crypto = getCrypto(true)) { + return crypto.getPublicKey(this.subjectPublicKeyInfo, this.signatureAlgorithm, parameters); + } + async getKeyHash(hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { + return crypto.digest({ name: hashAlgorithm }, this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); + } + async sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { + if (!privateKey) { + throw new Error("Need to provide a private key for signing"); + } + const signatureParameters = await crypto.getSignatureParameters(privateKey, hashAlgorithm); + const parameters = signatureParameters.parameters; + this.signature = signatureParameters.signatureAlgorithm; + this.signatureAlgorithm = signatureParameters.signatureAlgorithm; + this.tbsView = new Uint8Array(this.encodeTBS().toBER()); + const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters); + this.signatureValue = new BitString({ valueHex: signature }); + } + async verify(issuerCertificate, crypto = getCrypto(true)) { + let subjectPublicKeyInfo; + if (issuerCertificate) { + subjectPublicKeyInfo = issuerCertificate.subjectPublicKeyInfo; + } + else if (this.issuer.isEqual(this.subject)) { + subjectPublicKeyInfo = this.subjectPublicKeyInfo; + } + if (!(subjectPublicKeyInfo instanceof PublicKeyInfo)) { + throw new Error("Please provide issuer certificate as a parameter"); + } + return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); + } +} +Certificate.CLASS_NAME = "Certificate"; +function checkCA(cert, signerCert = null) { + if (signerCert && cert.issuer.isEqual(signerCert.issuer) && cert.serialNumber.isEqual(signerCert.serialNumber)) { + return null; + } + let isCA = false; + if (cert.extensions) { + for (const extension of cert.extensions) { + if (extension.extnID === id_BasicConstraints && extension.parsedValue instanceof BasicConstraints) { + if (extension.parsedValue.cA) { + isCA = true; + break; + } + } + } + } + if (isCA) { + return cert; + } + return null; +} + +const CERT_ID$1 = "certId"; +const CERT_VALUE = "certValue"; +const PARSED_VALUE$4 = "parsedValue"; +const CLEAR_PROPS$P = [ + CERT_ID$1, + CERT_VALUE +]; +class CertBag extends PkiObject { + constructor(parameters = {}) { + super(); + this.certId = getParametersValue(parameters, CERT_ID$1, CertBag.defaultValues(CERT_ID$1)); + this.certValue = getParametersValue(parameters, CERT_VALUE, CertBag.defaultValues(CERT_VALUE)); + if (PARSED_VALUE$4 in parameters) { + this.parsedValue = getParametersValue(parameters, PARSED_VALUE$4, CertBag.defaultValues(PARSED_VALUE$4)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CERT_ID$1: + return EMPTY_STRING; + case CERT_VALUE: + return (new Any()); + case PARSED_VALUE$4: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case CERT_ID$1: + return (memberValue === EMPTY_STRING); + case CERT_VALUE: + return (memberValue instanceof Any); + case PARSED_VALUE$4: + return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.id || "id") }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Any({ name: (names.value || "value") })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$P); + const asn1 = compareSchema(schema, schema, CertBag.schema({ + names: { + id: CERT_ID$1, + value: CERT_VALUE + } + })); + AsnError.assertSchema(asn1, this.className); + this.certId = asn1.result.certId.valueBlock.toString(); + this.certValue = asn1.result.certValue; + const certValueHex = this.certValue.valueBlock.valueHexView; + switch (this.certId) { + case id_CertBag_X509Certificate: + { + try { + this.parsedValue = Certificate.fromBER(certValueHex); + } + catch { + AttributeCertificateV2.fromBER(certValueHex); + } + } + break; + case id_CertBag_AttributeCertificate: + { + this.parsedValue = AttributeCertificateV2.fromBER(certValueHex); + } + break; + case id_CertBag_SDSICertificate: + default: + throw new Error(`Incorrect CERT_ID value in CertBag: ${this.certId}`); + } + } + toSchema() { + if (PARSED_VALUE$4 in this) { + if ("acinfo" in this.parsedValue) { + this.certId = id_CertBag_AttributeCertificate; + } + else { + this.certId = id_CertBag_X509Certificate; + } + this.certValue = new OctetString({ valueHex: this.parsedValue.toSchema().toBER(false) }); + } + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.certId }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [(("toSchema" in this.certValue) ? this.certValue.toSchema() : this.certValue)] + }) + ] + })); + } + toJSON() { + return { + certId: this.certId, + certValue: this.certValue.toJSON() + }; + } +} CertBag.CLASS_NAME = "CertBag"; -const USER_CERTIFICATE = "userCertificate"; -const REVOCATION_DATE = "revocationDate"; -const CRL_ENTRY_EXTENSIONS = "crlEntryExtensions"; -const CLEAR_PROPS$O = [ - USER_CERTIFICATE, - REVOCATION_DATE, - CRL_ENTRY_EXTENSIONS -]; -class RevokedCertificate extends PkiObject { - constructor(parameters = {}) { - super(); - this.userCertificate = getParametersValue(parameters, USER_CERTIFICATE, RevokedCertificate.defaultValues(USER_CERTIFICATE)); - this.revocationDate = getParametersValue(parameters, REVOCATION_DATE, RevokedCertificate.defaultValues(REVOCATION_DATE)); - if (CRL_ENTRY_EXTENSIONS in parameters) { - this.crlEntryExtensions = getParametersValue(parameters, CRL_ENTRY_EXTENSIONS, RevokedCertificate.defaultValues(CRL_ENTRY_EXTENSIONS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case USER_CERTIFICATE: - return new Integer(); - case REVOCATION_DATE: - return new Time(); - case CRL_ENTRY_EXTENSIONS: - return new Extensions(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.userCertificate || USER_CERTIFICATE) }), - Time.schema({ - names: { - utcTimeName: (names.revocationDate || REVOCATION_DATE), - generalTimeName: (names.revocationDate || REVOCATION_DATE) - } - }), - Extensions.schema({ - names: { - blockName: (names.crlEntryExtensions || CRL_ENTRY_EXTENSIONS) - } - }, true) - ] - }); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$O); - const asn1 = compareSchema(schema, schema, RevokedCertificate.schema()); - AsnError.assertSchema(asn1, this.className); - this.userCertificate = asn1.result.userCertificate; - this.revocationDate = new Time({ schema: asn1.result.revocationDate }); - if (CRL_ENTRY_EXTENSIONS in asn1.result) { - this.crlEntryExtensions = new Extensions({ schema: asn1.result.crlEntryExtensions }); - } - } - toSchema() { - const outputArray = [ - this.userCertificate, - this.revocationDate.toSchema() - ]; - if (this.crlEntryExtensions) { - outputArray.push(this.crlEntryExtensions.toSchema()); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - userCertificate: this.userCertificate.toJSON(), - revocationDate: this.revocationDate.toJSON(), - }; - if (this.crlEntryExtensions) { - res.crlEntryExtensions = this.crlEntryExtensions.toJSON(); - } - return res; - } -} +const USER_CERTIFICATE = "userCertificate"; +const REVOCATION_DATE = "revocationDate"; +const CRL_ENTRY_EXTENSIONS = "crlEntryExtensions"; +const CLEAR_PROPS$O = [ + USER_CERTIFICATE, + REVOCATION_DATE, + CRL_ENTRY_EXTENSIONS +]; +class RevokedCertificate extends PkiObject { + constructor(parameters = {}) { + super(); + this.userCertificate = getParametersValue(parameters, USER_CERTIFICATE, RevokedCertificate.defaultValues(USER_CERTIFICATE)); + this.revocationDate = getParametersValue(parameters, REVOCATION_DATE, RevokedCertificate.defaultValues(REVOCATION_DATE)); + if (CRL_ENTRY_EXTENSIONS in parameters) { + this.crlEntryExtensions = getParametersValue(parameters, CRL_ENTRY_EXTENSIONS, RevokedCertificate.defaultValues(CRL_ENTRY_EXTENSIONS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case USER_CERTIFICATE: + return new Integer(); + case REVOCATION_DATE: + return new Time(); + case CRL_ENTRY_EXTENSIONS: + return new Extensions(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.userCertificate || USER_CERTIFICATE) }), + Time.schema({ + names: { + utcTimeName: (names.revocationDate || REVOCATION_DATE), + generalTimeName: (names.revocationDate || REVOCATION_DATE) + } + }), + Extensions.schema({ + names: { + blockName: (names.crlEntryExtensions || CRL_ENTRY_EXTENSIONS) + } + }, true) + ] + }); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$O); + const asn1 = compareSchema(schema, schema, RevokedCertificate.schema()); + AsnError.assertSchema(asn1, this.className); + this.userCertificate = asn1.result.userCertificate; + this.revocationDate = new Time({ schema: asn1.result.revocationDate }); + if (CRL_ENTRY_EXTENSIONS in asn1.result) { + this.crlEntryExtensions = new Extensions({ schema: asn1.result.crlEntryExtensions }); + } + } + toSchema() { + const outputArray = [ + this.userCertificate, + this.revocationDate.toSchema() + ]; + if (this.crlEntryExtensions) { + outputArray.push(this.crlEntryExtensions.toSchema()); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + userCertificate: this.userCertificate.toJSON(), + revocationDate: this.revocationDate.toJSON(), + }; + if (this.crlEntryExtensions) { + res.crlEntryExtensions = this.crlEntryExtensions.toJSON(); + } + return res; + } +} RevokedCertificate.CLASS_NAME = "RevokedCertificate"; -const TBS$3 = "tbs"; -const VERSION$e = "version"; -const SIGNATURE$3 = "signature"; -const ISSUER$1 = "issuer"; -const THIS_UPDATE$1 = "thisUpdate"; -const NEXT_UPDATE$1 = "nextUpdate"; -const REVOKED_CERTIFICATES = "revokedCertificates"; -const CRL_EXTENSIONS = "crlExtensions"; -const SIGNATURE_ALGORITHM$4 = "signatureAlgorithm"; -const SIGNATURE_VALUE$1 = "signatureValue"; -const TBS_CERT_LIST = "tbsCertList"; -const TBS_CERT_LIST_VERSION = `${TBS_CERT_LIST}.version`; -const TBS_CERT_LIST_SIGNATURE = `${TBS_CERT_LIST}.signature`; -const TBS_CERT_LIST_ISSUER = `${TBS_CERT_LIST}.issuer`; -const TBS_CERT_LIST_THIS_UPDATE = `${TBS_CERT_LIST}.thisUpdate`; -const TBS_CERT_LIST_NEXT_UPDATE = `${TBS_CERT_LIST}.nextUpdate`; -const TBS_CERT_LIST_REVOKED_CERTIFICATES = `${TBS_CERT_LIST}.revokedCertificates`; -const TBS_CERT_LIST_EXTENSIONS = `${TBS_CERT_LIST}.extensions`; -const CLEAR_PROPS$N = [ - TBS_CERT_LIST, - TBS_CERT_LIST_VERSION, - TBS_CERT_LIST_SIGNATURE, - TBS_CERT_LIST_ISSUER, - TBS_CERT_LIST_THIS_UPDATE, - TBS_CERT_LIST_NEXT_UPDATE, - TBS_CERT_LIST_REVOKED_CERTIFICATES, - TBS_CERT_LIST_EXTENSIONS, - SIGNATURE_ALGORITHM$4, - SIGNATURE_VALUE$1 -]; -function tbsCertList(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || TBS_CERT_LIST), - value: [ - new Integer({ - optional: true, - name: (names.tbsCertListVersion || TBS_CERT_LIST_VERSION), - value: 2 - }), - AlgorithmIdentifier.schema(names.signature || { - names: { - blockName: TBS_CERT_LIST_SIGNATURE - } - }), - RelativeDistinguishedNames.schema(names.issuer || { - names: { - blockName: TBS_CERT_LIST_ISSUER - } - }), - Time.schema(names.tbsCertListThisUpdate || { - names: { - utcTimeName: TBS_CERT_LIST_THIS_UPDATE, - generalTimeName: TBS_CERT_LIST_THIS_UPDATE - } - }), - Time.schema(names.tbsCertListNextUpdate || { - names: { - utcTimeName: TBS_CERT_LIST_NEXT_UPDATE, - generalTimeName: TBS_CERT_LIST_NEXT_UPDATE - } - }, true), - new Sequence({ - optional: true, - value: [ - new Repeated({ - name: (names.tbsCertListRevokedCertificates || TBS_CERT_LIST_REVOKED_CERTIFICATES), - value: new Sequence({ - value: [ - new Integer(), - Time.schema(), - Extensions.schema({}, true) - ] - }) - }) - ] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [Extensions.schema(names.crlExtensions || { - names: { - blockName: TBS_CERT_LIST_EXTENSIONS - } - })] - }) - ] - })); -} -const WELL_KNOWN_EXTENSIONS = [ - id_AuthorityKeyIdentifier, - id_IssuerAltName, - id_CRLNumber, - id_BaseCRLNumber, - id_IssuingDistributionPoint, - id_FreshestCRL, - id_AuthorityInfoAccess, - id_CRLReason, - id_InvalidityDate, - id_CertificateIssuer, -]; -class CertificateRevocationList extends PkiObject { - constructor(parameters = {}) { - super(); - this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$3, CertificateRevocationList.defaultValues(TBS$3))); - this.version = getParametersValue(parameters, VERSION$e, CertificateRevocationList.defaultValues(VERSION$e)); - this.signature = getParametersValue(parameters, SIGNATURE$3, CertificateRevocationList.defaultValues(SIGNATURE$3)); - this.issuer = getParametersValue(parameters, ISSUER$1, CertificateRevocationList.defaultValues(ISSUER$1)); - this.thisUpdate = getParametersValue(parameters, THIS_UPDATE$1, CertificateRevocationList.defaultValues(THIS_UPDATE$1)); - if (NEXT_UPDATE$1 in parameters) { - this.nextUpdate = getParametersValue(parameters, NEXT_UPDATE$1, CertificateRevocationList.defaultValues(NEXT_UPDATE$1)); - } - if (REVOKED_CERTIFICATES in parameters) { - this.revokedCertificates = getParametersValue(parameters, REVOKED_CERTIFICATES, CertificateRevocationList.defaultValues(REVOKED_CERTIFICATES)); - } - if (CRL_EXTENSIONS in parameters) { - this.crlExtensions = getParametersValue(parameters, CRL_EXTENSIONS, CertificateRevocationList.defaultValues(CRL_EXTENSIONS)); - } - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$4, CertificateRevocationList.defaultValues(SIGNATURE_ALGORITHM$4)); - this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$1, CertificateRevocationList.defaultValues(SIGNATURE_VALUE$1)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - get tbs() { - return BufferSourceConverter.toArrayBuffer(this.tbsView); - } - set tbs(value) { - this.tbsView = new Uint8Array(value); - } - static defaultValues(memberName) { - switch (memberName) { - case TBS$3: - return EMPTY_BUFFER; - case VERSION$e: - return 0; - case SIGNATURE$3: - return new AlgorithmIdentifier(); - case ISSUER$1: - return new RelativeDistinguishedNames(); - case THIS_UPDATE$1: - return new Time(); - case NEXT_UPDATE$1: - return new Time(); - case REVOKED_CERTIFICATES: - return []; - case CRL_EXTENSIONS: - return new Extensions(); - case SIGNATURE_ALGORITHM$4: - return new AlgorithmIdentifier(); - case SIGNATURE_VALUE$1: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || "CertificateList"), - value: [ - tbsCertList(parameters), - AlgorithmIdentifier.schema(names.signatureAlgorithm || { - names: { - blockName: SIGNATURE_ALGORITHM$4 - } - }), - new BitString({ name: (names.signatureValue || SIGNATURE_VALUE$1) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$N); - const asn1 = compareSchema(schema, schema, CertificateRevocationList.schema()); - AsnError.assertSchema(asn1, this.className); - this.tbsView = asn1.result.tbsCertList.valueBeforeDecodeView; - if (TBS_CERT_LIST_VERSION in asn1.result) { - this.version = asn1.result[TBS_CERT_LIST_VERSION].valueBlock.valueDec; - } - this.signature = new AlgorithmIdentifier({ schema: asn1.result[TBS_CERT_LIST_SIGNATURE] }); - this.issuer = new RelativeDistinguishedNames({ schema: asn1.result[TBS_CERT_LIST_ISSUER] }); - this.thisUpdate = new Time({ schema: asn1.result[TBS_CERT_LIST_THIS_UPDATE] }); - if (TBS_CERT_LIST_NEXT_UPDATE in asn1.result) { - this.nextUpdate = new Time({ schema: asn1.result[TBS_CERT_LIST_NEXT_UPDATE] }); - } - if (TBS_CERT_LIST_REVOKED_CERTIFICATES in asn1.result) { - this.revokedCertificates = Array.from(asn1.result[TBS_CERT_LIST_REVOKED_CERTIFICATES], element => new RevokedCertificate({ schema: element })); - } - if (TBS_CERT_LIST_EXTENSIONS in asn1.result) { - this.crlExtensions = new Extensions({ schema: asn1.result[TBS_CERT_LIST_EXTENSIONS] }); - } - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); - this.signatureValue = asn1.result.signatureValue; - } - encodeTBS() { - const outputArray = []; - if (this.version !== CertificateRevocationList.defaultValues(VERSION$e)) { - outputArray.push(new Integer({ value: this.version })); - } - outputArray.push(this.signature.toSchema()); - outputArray.push(this.issuer.toSchema()); - outputArray.push(this.thisUpdate.toSchema()); - if (this.nextUpdate) { - outputArray.push(this.nextUpdate.toSchema()); - } - if (this.revokedCertificates) { - outputArray.push(new Sequence({ - value: Array.from(this.revokedCertificates, o => o.toSchema()) - })); - } - if (this.crlExtensions) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - this.crlExtensions.toSchema() - ] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toSchema(encodeFlag = false) { - let tbsSchema; - if (!encodeFlag) { - if (!this.tbsView.byteLength) { - return CertificateRevocationList.schema(); - } - const asn1 = fromBER(this.tbsView); - AsnError.assert(asn1, "TBS Certificate Revocation List"); - tbsSchema = asn1.result; - } - else { - tbsSchema = this.encodeTBS(); - } - return (new Sequence({ - value: [ - tbsSchema, - this.signatureAlgorithm.toSchema(), - this.signatureValue - ] - })); - } - toJSON() { - const res = { - tbs: Convert.ToHex(this.tbsView), - version: this.version, - signature: this.signature.toJSON(), - issuer: this.issuer.toJSON(), - thisUpdate: this.thisUpdate.toJSON(), - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signatureValue: this.signatureValue.toJSON() - }; - if (this.version !== CertificateRevocationList.defaultValues(VERSION$e)) - res.version = this.version; - if (this.nextUpdate) { - res.nextUpdate = this.nextUpdate.toJSON(); - } - if (this.revokedCertificates) { - res.revokedCertificates = Array.from(this.revokedCertificates, o => o.toJSON()); - } - if (this.crlExtensions) { - res.crlExtensions = this.crlExtensions.toJSON(); - } - return res; - } - isCertificateRevoked(certificate) { - if (!this.issuer.isEqual(certificate.issuer)) { - return false; - } - if (!this.revokedCertificates) { - return false; - } - for (const revokedCertificate of this.revokedCertificates) { - if (revokedCertificate.userCertificate.isEqual(certificate.serialNumber)) { - return true; - } - } - return false; - } - sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - if (!privateKey) { - throw new Error("Need to provide a private key for signing"); - } - const signatureParameters = yield crypto.getSignatureParameters(privateKey, hashAlgorithm); - const { parameters } = signatureParameters; - this.signature = signatureParameters.signatureAlgorithm; - this.signatureAlgorithm = signatureParameters.signatureAlgorithm; - this.tbsView = new Uint8Array(this.encodeTBS().toBER()); - const signature = yield crypto.signWithPrivateKey(this.tbsView, privateKey, parameters); - this.signatureValue = new BitString({ valueHex: signature }); - }); - } - verify(parameters = {}, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - let subjectPublicKeyInfo; - if (parameters.issuerCertificate) { - subjectPublicKeyInfo = parameters.issuerCertificate.subjectPublicKeyInfo; - if (!this.issuer.isEqual(parameters.issuerCertificate.subject)) { - return false; - } - } - if (parameters.publicKeyInfo) { - subjectPublicKeyInfo = parameters.publicKeyInfo; - } - if (!subjectPublicKeyInfo) { - throw new Error("Issuer's certificate must be provided as an input parameter"); - } - if (this.crlExtensions) { - for (const extension of this.crlExtensions.extensions) { - if (extension.critical) { - if (!WELL_KNOWN_EXTENSIONS.includes(extension.extnID)) - return false; - } - } - } - return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); - }); - } -} +const TBS$3 = "tbs"; +const VERSION$e = "version"; +const SIGNATURE$3 = "signature"; +const ISSUER$1 = "issuer"; +const THIS_UPDATE$1 = "thisUpdate"; +const NEXT_UPDATE$1 = "nextUpdate"; +const REVOKED_CERTIFICATES = "revokedCertificates"; +const CRL_EXTENSIONS = "crlExtensions"; +const SIGNATURE_ALGORITHM$4 = "signatureAlgorithm"; +const SIGNATURE_VALUE$1 = "signatureValue"; +const TBS_CERT_LIST = "tbsCertList"; +const TBS_CERT_LIST_VERSION = `${TBS_CERT_LIST}.version`; +const TBS_CERT_LIST_SIGNATURE = `${TBS_CERT_LIST}.signature`; +const TBS_CERT_LIST_ISSUER = `${TBS_CERT_LIST}.issuer`; +const TBS_CERT_LIST_THIS_UPDATE = `${TBS_CERT_LIST}.thisUpdate`; +const TBS_CERT_LIST_NEXT_UPDATE = `${TBS_CERT_LIST}.nextUpdate`; +const TBS_CERT_LIST_REVOKED_CERTIFICATES = `${TBS_CERT_LIST}.revokedCertificates`; +const TBS_CERT_LIST_EXTENSIONS = `${TBS_CERT_LIST}.extensions`; +const CLEAR_PROPS$N = [ + TBS_CERT_LIST, + TBS_CERT_LIST_VERSION, + TBS_CERT_LIST_SIGNATURE, + TBS_CERT_LIST_ISSUER, + TBS_CERT_LIST_THIS_UPDATE, + TBS_CERT_LIST_NEXT_UPDATE, + TBS_CERT_LIST_REVOKED_CERTIFICATES, + TBS_CERT_LIST_EXTENSIONS, + SIGNATURE_ALGORITHM$4, + SIGNATURE_VALUE$1 +]; +function tbsCertList(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || TBS_CERT_LIST), + value: [ + new Integer({ + optional: true, + name: (names.tbsCertListVersion || TBS_CERT_LIST_VERSION), + value: 2 + }), + AlgorithmIdentifier.schema(names.signature || { + names: { + blockName: TBS_CERT_LIST_SIGNATURE + } + }), + RelativeDistinguishedNames.schema(names.issuer || { + names: { + blockName: TBS_CERT_LIST_ISSUER + } + }), + Time.schema(names.tbsCertListThisUpdate || { + names: { + utcTimeName: TBS_CERT_LIST_THIS_UPDATE, + generalTimeName: TBS_CERT_LIST_THIS_UPDATE + } + }), + Time.schema(names.tbsCertListNextUpdate || { + names: { + utcTimeName: TBS_CERT_LIST_NEXT_UPDATE, + generalTimeName: TBS_CERT_LIST_NEXT_UPDATE + } + }, true), + new Sequence({ + optional: true, + value: [ + new Repeated({ + name: (names.tbsCertListRevokedCertificates || TBS_CERT_LIST_REVOKED_CERTIFICATES), + value: new Sequence({ + value: [ + new Integer(), + Time.schema(), + Extensions.schema({}, true) + ] + }) + }) + ] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [Extensions.schema(names.crlExtensions || { + names: { + blockName: TBS_CERT_LIST_EXTENSIONS + } + })] + }) + ] + })); +} +const WELL_KNOWN_EXTENSIONS = [ + id_AuthorityKeyIdentifier, + id_IssuerAltName, + id_CRLNumber, + id_BaseCRLNumber, + id_IssuingDistributionPoint, + id_FreshestCRL, + id_AuthorityInfoAccess, + id_CRLReason, + id_InvalidityDate, + id_CertificateIssuer, +]; +class CertificateRevocationList extends PkiObject { + get tbs() { + return BufferSourceConverter.toArrayBuffer(this.tbsView); + } + set tbs(value) { + this.tbsView = new Uint8Array(value); + } + constructor(parameters = {}) { + super(); + this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$3, CertificateRevocationList.defaultValues(TBS$3))); + this.version = getParametersValue(parameters, VERSION$e, CertificateRevocationList.defaultValues(VERSION$e)); + this.signature = getParametersValue(parameters, SIGNATURE$3, CertificateRevocationList.defaultValues(SIGNATURE$3)); + this.issuer = getParametersValue(parameters, ISSUER$1, CertificateRevocationList.defaultValues(ISSUER$1)); + this.thisUpdate = getParametersValue(parameters, THIS_UPDATE$1, CertificateRevocationList.defaultValues(THIS_UPDATE$1)); + if (NEXT_UPDATE$1 in parameters) { + this.nextUpdate = getParametersValue(parameters, NEXT_UPDATE$1, CertificateRevocationList.defaultValues(NEXT_UPDATE$1)); + } + if (REVOKED_CERTIFICATES in parameters) { + this.revokedCertificates = getParametersValue(parameters, REVOKED_CERTIFICATES, CertificateRevocationList.defaultValues(REVOKED_CERTIFICATES)); + } + if (CRL_EXTENSIONS in parameters) { + this.crlExtensions = getParametersValue(parameters, CRL_EXTENSIONS, CertificateRevocationList.defaultValues(CRL_EXTENSIONS)); + } + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$4, CertificateRevocationList.defaultValues(SIGNATURE_ALGORITHM$4)); + this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE$1, CertificateRevocationList.defaultValues(SIGNATURE_VALUE$1)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TBS$3: + return EMPTY_BUFFER; + case VERSION$e: + return 0; + case SIGNATURE$3: + return new AlgorithmIdentifier(); + case ISSUER$1: + return new RelativeDistinguishedNames(); + case THIS_UPDATE$1: + return new Time(); + case NEXT_UPDATE$1: + return new Time(); + case REVOKED_CERTIFICATES: + return []; + case CRL_EXTENSIONS: + return new Extensions(); + case SIGNATURE_ALGORITHM$4: + return new AlgorithmIdentifier(); + case SIGNATURE_VALUE$1: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || "CertificateList"), + value: [ + tbsCertList(parameters), + AlgorithmIdentifier.schema(names.signatureAlgorithm || { + names: { + blockName: SIGNATURE_ALGORITHM$4 + } + }), + new BitString({ name: (names.signatureValue || SIGNATURE_VALUE$1) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$N); + const asn1 = compareSchema(schema, schema, CertificateRevocationList.schema()); + AsnError.assertSchema(asn1, this.className); + this.tbsView = asn1.result.tbsCertList.valueBeforeDecodeView; + if (TBS_CERT_LIST_VERSION in asn1.result) { + this.version = asn1.result[TBS_CERT_LIST_VERSION].valueBlock.valueDec; + } + this.signature = new AlgorithmIdentifier({ schema: asn1.result[TBS_CERT_LIST_SIGNATURE] }); + this.issuer = new RelativeDistinguishedNames({ schema: asn1.result[TBS_CERT_LIST_ISSUER] }); + this.thisUpdate = new Time({ schema: asn1.result[TBS_CERT_LIST_THIS_UPDATE] }); + if (TBS_CERT_LIST_NEXT_UPDATE in asn1.result) { + this.nextUpdate = new Time({ schema: asn1.result[TBS_CERT_LIST_NEXT_UPDATE] }); + } + if (TBS_CERT_LIST_REVOKED_CERTIFICATES in asn1.result) { + this.revokedCertificates = Array.from(asn1.result[TBS_CERT_LIST_REVOKED_CERTIFICATES], element => new RevokedCertificate({ schema: element })); + } + if (TBS_CERT_LIST_EXTENSIONS in asn1.result) { + this.crlExtensions = new Extensions({ schema: asn1.result[TBS_CERT_LIST_EXTENSIONS] }); + } + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); + this.signatureValue = asn1.result.signatureValue; + } + encodeTBS() { + const outputArray = []; + if (this.version !== CertificateRevocationList.defaultValues(VERSION$e)) { + outputArray.push(new Integer({ value: this.version })); + } + outputArray.push(this.signature.toSchema()); + outputArray.push(this.issuer.toSchema()); + outputArray.push(this.thisUpdate.toSchema()); + if (this.nextUpdate) { + outputArray.push(this.nextUpdate.toSchema()); + } + if (this.revokedCertificates) { + outputArray.push(new Sequence({ + value: Array.from(this.revokedCertificates, o => o.toSchema()) + })); + } + if (this.crlExtensions) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + this.crlExtensions.toSchema() + ] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toSchema(encodeFlag = false) { + let tbsSchema; + if (!encodeFlag) { + if (!this.tbsView.byteLength) { + return CertificateRevocationList.schema(); + } + const asn1 = fromBER(this.tbsView); + AsnError.assert(asn1, "TBS Certificate Revocation List"); + tbsSchema = asn1.result; + } + else { + tbsSchema = this.encodeTBS(); + } + return (new Sequence({ + value: [ + tbsSchema, + this.signatureAlgorithm.toSchema(), + this.signatureValue + ] + })); + } + toJSON() { + const res = { + tbs: Convert.ToHex(this.tbsView), + version: this.version, + signature: this.signature.toJSON(), + issuer: this.issuer.toJSON(), + thisUpdate: this.thisUpdate.toJSON(), + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signatureValue: this.signatureValue.toJSON() + }; + if (this.version !== CertificateRevocationList.defaultValues(VERSION$e)) + res.version = this.version; + if (this.nextUpdate) { + res.nextUpdate = this.nextUpdate.toJSON(); + } + if (this.revokedCertificates) { + res.revokedCertificates = Array.from(this.revokedCertificates, o => o.toJSON()); + } + if (this.crlExtensions) { + res.crlExtensions = this.crlExtensions.toJSON(); + } + return res; + } + isCertificateRevoked(certificate) { + if (!this.issuer.isEqual(certificate.issuer)) { + return false; + } + if (!this.revokedCertificates) { + return false; + } + for (const revokedCertificate of this.revokedCertificates) { + if (revokedCertificate.userCertificate.isEqual(certificate.serialNumber)) { + return true; + } + } + return false; + } + async sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { + if (!privateKey) { + throw new Error("Need to provide a private key for signing"); + } + const signatureParameters = await crypto.getSignatureParameters(privateKey, hashAlgorithm); + const { parameters } = signatureParameters; + this.signature = signatureParameters.signatureAlgorithm; + this.signatureAlgorithm = signatureParameters.signatureAlgorithm; + this.tbsView = new Uint8Array(this.encodeTBS().toBER()); + const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters); + this.signatureValue = new BitString({ valueHex: signature }); + } + async verify(parameters = {}, crypto = getCrypto(true)) { + let subjectPublicKeyInfo; + if (parameters.issuerCertificate) { + subjectPublicKeyInfo = parameters.issuerCertificate.subjectPublicKeyInfo; + if (!this.issuer.isEqual(parameters.issuerCertificate.subject)) { + return false; + } + } + if (parameters.publicKeyInfo) { + subjectPublicKeyInfo = parameters.publicKeyInfo; + } + if (!subjectPublicKeyInfo) { + throw new Error("Issuer's certificate must be provided as an input parameter"); + } + if (this.crlExtensions) { + for (const extension of this.crlExtensions.extensions) { + if (extension.critical) { + if (!WELL_KNOWN_EXTENSIONS.includes(extension.extnID)) + return false; + } + } + } + return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm); + } +} CertificateRevocationList.CLASS_NAME = "CertificateRevocationList"; -const CRL_ID = "crlId"; -const CRL_VALUE = "crlValue"; -const PARSED_VALUE$3 = "parsedValue"; -const CLEAR_PROPS$M = [ - CRL_ID, - CRL_VALUE, -]; -class CRLBag extends PkiObject { - constructor(parameters = {}) { - super(); - this.crlId = getParametersValue(parameters, CRL_ID, CRLBag.defaultValues(CRL_ID)); - this.crlValue = getParametersValue(parameters, CRL_VALUE, CRLBag.defaultValues(CRL_VALUE)); - if (PARSED_VALUE$3 in parameters) { - this.parsedValue = getParametersValue(parameters, PARSED_VALUE$3, CRLBag.defaultValues(PARSED_VALUE$3)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CRL_ID: - return EMPTY_STRING; - case CRL_VALUE: - return (new Any()); - case PARSED_VALUE$3: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case CRL_ID: - return (memberValue === EMPTY_STRING); - case CRL_VALUE: - return (memberValue instanceof Any); - case PARSED_VALUE$3: - return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.id || "id") }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Any({ name: (names.value || "value") })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$M); - const asn1 = compareSchema(schema, schema, CRLBag.schema({ - names: { - id: CRL_ID, - value: CRL_VALUE - } - })); - AsnError.assertSchema(asn1, this.className); - this.crlId = asn1.result.crlId.valueBlock.toString(); - this.crlValue = asn1.result.crlValue; - switch (this.crlId) { - case id_CRLBag_X509CRL: - { - this.parsedValue = CertificateRevocationList.fromBER(this.certValue.valueBlock.valueHex); - } - break; - default: - throw new Error(`Incorrect CRL_ID value in CRLBag: ${this.crlId}`); - } - } - toSchema() { - if (this.parsedValue) { - this.crlId = id_CRLBag_X509CRL; - this.crlValue = new OctetString({ valueHex: this.parsedValue.toSchema().toBER(false) }); - } - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.crlId }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.crlValue.toSchema()] - }) - ] - })); - } - toJSON() { - return { - crlId: this.crlId, - crlValue: this.crlValue.toJSON() - }; - } -} +const CRL_ID = "crlId"; +const CRL_VALUE = "crlValue"; +const PARSED_VALUE$3 = "parsedValue"; +const CLEAR_PROPS$M = [ + CRL_ID, + CRL_VALUE, +]; +class CRLBag extends PkiObject { + constructor(parameters = {}) { + super(); + this.crlId = getParametersValue(parameters, CRL_ID, CRLBag.defaultValues(CRL_ID)); + this.crlValue = getParametersValue(parameters, CRL_VALUE, CRLBag.defaultValues(CRL_VALUE)); + if (PARSED_VALUE$3 in parameters) { + this.parsedValue = getParametersValue(parameters, PARSED_VALUE$3, CRLBag.defaultValues(PARSED_VALUE$3)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CRL_ID: + return EMPTY_STRING; + case CRL_VALUE: + return (new Any()); + case PARSED_VALUE$3: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case CRL_ID: + return (memberValue === EMPTY_STRING); + case CRL_VALUE: + return (memberValue instanceof Any); + case PARSED_VALUE$3: + return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.id || "id") }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Any({ name: (names.value || "value") })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$M); + const asn1 = compareSchema(schema, schema, CRLBag.schema({ + names: { + id: CRL_ID, + value: CRL_VALUE + } + })); + AsnError.assertSchema(asn1, this.className); + this.crlId = asn1.result.crlId.valueBlock.toString(); + this.crlValue = asn1.result.crlValue; + switch (this.crlId) { + case id_CRLBag_X509CRL: + { + this.parsedValue = CertificateRevocationList.fromBER(this.certValue.valueBlock.valueHex); + } + break; + default: + throw new Error(`Incorrect CRL_ID value in CRLBag: ${this.crlId}`); + } + } + toSchema() { + if (this.parsedValue) { + this.crlId = id_CRLBag_X509CRL; + this.crlValue = new OctetString({ valueHex: this.parsedValue.toSchema().toBER(false) }); + } + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.crlId }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.crlValue.toSchema()] + }) + ] + })); + } + toJSON() { + return { + crlId: this.crlId, + crlValue: this.crlValue.toJSON() + }; + } +} CRLBag.CLASS_NAME = "CRLBag"; -const VERSION$d = "version"; -const ENCRYPTED_CONTENT_INFO$1 = "encryptedContentInfo"; -const UNPROTECTED_ATTRS$1 = "unprotectedAttrs"; -const CLEAR_PROPS$L = [ - VERSION$d, - ENCRYPTED_CONTENT_INFO$1, - UNPROTECTED_ATTRS$1, -]; -class EncryptedData extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$d, EncryptedData.defaultValues(VERSION$d)); - this.encryptedContentInfo = getParametersValue(parameters, ENCRYPTED_CONTENT_INFO$1, EncryptedData.defaultValues(ENCRYPTED_CONTENT_INFO$1)); - if (UNPROTECTED_ATTRS$1 in parameters) { - this.unprotectedAttrs = getParametersValue(parameters, UNPROTECTED_ATTRS$1, EncryptedData.defaultValues(UNPROTECTED_ATTRS$1)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$d: - return 0; - case ENCRYPTED_CONTENT_INFO$1: - return new EncryptedContentInfo(); - case UNPROTECTED_ATTRS$1: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$d: - return (memberValue === 0); - case ENCRYPTED_CONTENT_INFO$1: - return ((EncryptedContentInfo.compareWithDefault("contentType", memberValue.contentType)) && - (EncryptedContentInfo.compareWithDefault("contentEncryptionAlgorithm", memberValue.contentEncryptionAlgorithm)) && - (EncryptedContentInfo.compareWithDefault("encryptedContent", memberValue.encryptedContent))); - case UNPROTECTED_ATTRS$1: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - EncryptedContentInfo.schema(names.encryptedContentInfo || {}), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new Repeated({ - name: (names.unprotectedAttrs || EMPTY_STRING), - value: Attribute.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$L); - const asn1 = compareSchema(schema, schema, EncryptedData.schema({ - names: { - version: VERSION$d, - encryptedContentInfo: { - names: { - blockName: ENCRYPTED_CONTENT_INFO$1 - } - }, - unprotectedAttrs: UNPROTECTED_ATTRS$1 - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.encryptedContentInfo = new EncryptedContentInfo({ schema: asn1.result.encryptedContentInfo }); - if (UNPROTECTED_ATTRS$1 in asn1.result) - this.unprotectedAttrs = Array.from(asn1.result.unprotectedAttrs, element => new Attribute({ schema: element })); - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - outputArray.push(this.encryptedContentInfo.toSchema()); - if (this.unprotectedAttrs) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: Array.from(this.unprotectedAttrs, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - version: this.version, - encryptedContentInfo: this.encryptedContentInfo.toJSON() - }; - if (this.unprotectedAttrs) - res.unprotectedAttrs = Array.from(this.unprotectedAttrs, o => o.toJSON()); - return res; - } - encrypt(parameters) { - return __awaiter(this, void 0, void 0, function* () { - ArgumentError.assert(parameters, "parameters", "object"); - const encryptParams = Object.assign(Object.assign({}, parameters), { contentType: "1.2.840.113549.1.7.1" }); - this.encryptedContentInfo = yield getCrypto(true).encryptEncryptedContentInfo(encryptParams); - }); - } - decrypt(parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - ArgumentError.assert(parameters, "parameters", "object"); - const decryptParams = Object.assign(Object.assign({}, parameters), { encryptedContentInfo: this.encryptedContentInfo }); - return crypto.decryptEncryptedContentInfo(decryptParams); - }); - } -} +const VERSION$d = "version"; +const ENCRYPTED_CONTENT_INFO$1 = "encryptedContentInfo"; +const UNPROTECTED_ATTRS$1 = "unprotectedAttrs"; +const CLEAR_PROPS$L = [ + VERSION$d, + ENCRYPTED_CONTENT_INFO$1, + UNPROTECTED_ATTRS$1, +]; +class EncryptedData extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$d, EncryptedData.defaultValues(VERSION$d)); + this.encryptedContentInfo = getParametersValue(parameters, ENCRYPTED_CONTENT_INFO$1, EncryptedData.defaultValues(ENCRYPTED_CONTENT_INFO$1)); + if (UNPROTECTED_ATTRS$1 in parameters) { + this.unprotectedAttrs = getParametersValue(parameters, UNPROTECTED_ATTRS$1, EncryptedData.defaultValues(UNPROTECTED_ATTRS$1)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$d: + return 0; + case ENCRYPTED_CONTENT_INFO$1: + return new EncryptedContentInfo(); + case UNPROTECTED_ATTRS$1: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$d: + return (memberValue === 0); + case ENCRYPTED_CONTENT_INFO$1: + return ((EncryptedContentInfo.compareWithDefault("contentType", memberValue.contentType)) && + (EncryptedContentInfo.compareWithDefault("contentEncryptionAlgorithm", memberValue.contentEncryptionAlgorithm)) && + (EncryptedContentInfo.compareWithDefault("encryptedContent", memberValue.encryptedContent))); + case UNPROTECTED_ATTRS$1: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + EncryptedContentInfo.schema(names.encryptedContentInfo || {}), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new Repeated({ + name: (names.unprotectedAttrs || EMPTY_STRING), + value: Attribute.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$L); + const asn1 = compareSchema(schema, schema, EncryptedData.schema({ + names: { + version: VERSION$d, + encryptedContentInfo: { + names: { + blockName: ENCRYPTED_CONTENT_INFO$1 + } + }, + unprotectedAttrs: UNPROTECTED_ATTRS$1 + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.encryptedContentInfo = new EncryptedContentInfo({ schema: asn1.result.encryptedContentInfo }); + if (UNPROTECTED_ATTRS$1 in asn1.result) + this.unprotectedAttrs = Array.from(asn1.result.unprotectedAttrs, element => new Attribute({ schema: element })); + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + outputArray.push(this.encryptedContentInfo.toSchema()); + if (this.unprotectedAttrs) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: Array.from(this.unprotectedAttrs, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + version: this.version, + encryptedContentInfo: this.encryptedContentInfo.toJSON() + }; + if (this.unprotectedAttrs) + res.unprotectedAttrs = Array.from(this.unprotectedAttrs, o => o.toJSON()); + return res; + } + async encrypt(parameters, crypto = getCrypto(true)) { + ArgumentError.assert(parameters, "parameters", "object"); + const encryptParams = { + ...parameters, + contentType: "1.2.840.113549.1.7.1", + }; + this.encryptedContentInfo = await crypto.encryptEncryptedContentInfo(encryptParams); + } + async decrypt(parameters, crypto = getCrypto(true)) { + ArgumentError.assert(parameters, "parameters", "object"); + const decryptParams = { + ...parameters, + encryptedContentInfo: this.encryptedContentInfo, + }; + return crypto.decryptEncryptedContentInfo(decryptParams); + } +} EncryptedData.CLASS_NAME = "EncryptedData"; -const ENCRYPTION_ALGORITHM = "encryptionAlgorithm"; -const ENCRYPTED_DATA = "encryptedData"; -const PARSED_VALUE$2 = "parsedValue"; -const CLEAR_PROPS$K = [ - ENCRYPTION_ALGORITHM, - ENCRYPTED_DATA, -]; -class PKCS8ShroudedKeyBag extends PkiObject { - constructor(parameters = {}) { - super(); - this.encryptionAlgorithm = getParametersValue(parameters, ENCRYPTION_ALGORITHM, PKCS8ShroudedKeyBag.defaultValues(ENCRYPTION_ALGORITHM)); - this.encryptedData = getParametersValue(parameters, ENCRYPTED_DATA, PKCS8ShroudedKeyBag.defaultValues(ENCRYPTED_DATA)); - if (PARSED_VALUE$2 in parameters) { - this.parsedValue = getParametersValue(parameters, PARSED_VALUE$2, PKCS8ShroudedKeyBag.defaultValues(PARSED_VALUE$2)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ENCRYPTION_ALGORITHM: - return (new AlgorithmIdentifier()); - case ENCRYPTED_DATA: - return (new OctetString()); - case PARSED_VALUE$2: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case ENCRYPTION_ALGORITHM: - return ((AlgorithmIdentifier.compareWithDefault("algorithmId", memberValue.algorithmId)) && - (("algorithmParams" in memberValue) === false)); - case ENCRYPTED_DATA: - return (memberValue.isEqual(PKCS8ShroudedKeyBag.defaultValues(memberName))); - case PARSED_VALUE$2: - return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.encryptionAlgorithm || { - names: { - blockName: ENCRYPTION_ALGORITHM - } - }), - new Choice({ - value: [ - new OctetString({ name: (names.encryptedData || ENCRYPTED_DATA) }), - new OctetString({ - idBlock: { - isConstructed: true - }, - name: (names.encryptedData || ENCRYPTED_DATA) - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$K); - const asn1 = compareSchema(schema, schema, PKCS8ShroudedKeyBag.schema({ - names: { - encryptionAlgorithm: { - names: { - blockName: ENCRYPTION_ALGORITHM - } - }, - encryptedData: ENCRYPTED_DATA - } - })); - AsnError.assertSchema(asn1, this.className); - this.encryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.encryptionAlgorithm }); - this.encryptedData = asn1.result.encryptedData; - } - toSchema() { - return (new Sequence({ - value: [ - this.encryptionAlgorithm.toSchema(), - this.encryptedData - ] - })); - } - toJSON() { - return { - encryptionAlgorithm: this.encryptionAlgorithm.toJSON(), - encryptedData: this.encryptedData.toJSON(), - }; - } - parseInternalValues(parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const cmsEncrypted = new EncryptedData({ - encryptedContentInfo: new EncryptedContentInfo({ - contentEncryptionAlgorithm: this.encryptionAlgorithm, - encryptedContent: this.encryptedData - }) - }); - const decryptedData = yield cmsEncrypted.decrypt(parameters, crypto); - this.parsedValue = PrivateKeyInfo.fromBER(decryptedData); - }); - } - makeInternalValues(parameters) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.parsedValue) { - throw new Error("Please initialize \"parsedValue\" first"); - } - const cmsEncrypted = new EncryptedData(); - const encryptParams = Object.assign(Object.assign({}, parameters), { contentToEncrypt: this.parsedValue.toSchema().toBER(false) }); - yield cmsEncrypted.encrypt(encryptParams); - if (!cmsEncrypted.encryptedContentInfo.encryptedContent) { - throw new Error("The filed `encryptedContent` in EncryptedContentInfo is empty"); - } - this.encryptionAlgorithm = cmsEncrypted.encryptedContentInfo.contentEncryptionAlgorithm; - this.encryptedData = cmsEncrypted.encryptedContentInfo.encryptedContent; - }); - } -} +const ENCRYPTION_ALGORITHM = "encryptionAlgorithm"; +const ENCRYPTED_DATA = "encryptedData"; +const PARSED_VALUE$2 = "parsedValue"; +const CLEAR_PROPS$K = [ + ENCRYPTION_ALGORITHM, + ENCRYPTED_DATA, +]; +class PKCS8ShroudedKeyBag extends PkiObject { + constructor(parameters = {}) { + super(); + this.encryptionAlgorithm = getParametersValue(parameters, ENCRYPTION_ALGORITHM, PKCS8ShroudedKeyBag.defaultValues(ENCRYPTION_ALGORITHM)); + this.encryptedData = getParametersValue(parameters, ENCRYPTED_DATA, PKCS8ShroudedKeyBag.defaultValues(ENCRYPTED_DATA)); + if (PARSED_VALUE$2 in parameters) { + this.parsedValue = getParametersValue(parameters, PARSED_VALUE$2, PKCS8ShroudedKeyBag.defaultValues(PARSED_VALUE$2)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ENCRYPTION_ALGORITHM: + return (new AlgorithmIdentifier()); + case ENCRYPTED_DATA: + return (new OctetString()); + case PARSED_VALUE$2: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case ENCRYPTION_ALGORITHM: + return ((AlgorithmIdentifier.compareWithDefault("algorithmId", memberValue.algorithmId)) && + (("algorithmParams" in memberValue) === false)); + case ENCRYPTED_DATA: + return (memberValue.isEqual(PKCS8ShroudedKeyBag.defaultValues(memberName))); + case PARSED_VALUE$2: + return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.encryptionAlgorithm || { + names: { + blockName: ENCRYPTION_ALGORITHM + } + }), + new Choice({ + value: [ + new OctetString({ name: (names.encryptedData || ENCRYPTED_DATA) }), + new OctetString({ + idBlock: { + isConstructed: true + }, + name: (names.encryptedData || ENCRYPTED_DATA) + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$K); + const asn1 = compareSchema(schema, schema, PKCS8ShroudedKeyBag.schema({ + names: { + encryptionAlgorithm: { + names: { + blockName: ENCRYPTION_ALGORITHM + } + }, + encryptedData: ENCRYPTED_DATA + } + })); + AsnError.assertSchema(asn1, this.className); + this.encryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.encryptionAlgorithm }); + this.encryptedData = asn1.result.encryptedData; + } + toSchema() { + return (new Sequence({ + value: [ + this.encryptionAlgorithm.toSchema(), + this.encryptedData + ] + })); + } + toJSON() { + return { + encryptionAlgorithm: this.encryptionAlgorithm.toJSON(), + encryptedData: this.encryptedData.toJSON(), + }; + } + async parseInternalValues(parameters, crypto = getCrypto(true)) { + const cmsEncrypted = new EncryptedData({ + encryptedContentInfo: new EncryptedContentInfo({ + contentEncryptionAlgorithm: this.encryptionAlgorithm, + encryptedContent: this.encryptedData + }) + }); + const decryptedData = await cmsEncrypted.decrypt(parameters, crypto); + this.parsedValue = PrivateKeyInfo.fromBER(decryptedData); + } + async makeInternalValues(parameters, crypto = getCrypto(true)) { + if (!this.parsedValue) { + throw new Error("Please initialize \"parsedValue\" first"); + } + const cmsEncrypted = new EncryptedData(); + const encryptParams = { + ...parameters, + contentToEncrypt: this.parsedValue.toSchema().toBER(false), + }; + await cmsEncrypted.encrypt(encryptParams, crypto); + if (!cmsEncrypted.encryptedContentInfo.encryptedContent) { + throw new Error("The filed `encryptedContent` in EncryptedContentInfo is empty"); + } + this.encryptionAlgorithm = cmsEncrypted.encryptedContentInfo.contentEncryptionAlgorithm; + this.encryptedData = cmsEncrypted.encryptedContentInfo.encryptedContent; + } +} PKCS8ShroudedKeyBag.CLASS_NAME = "PKCS8ShroudedKeyBag"; -const SECRET_TYPE_ID = "secretTypeId"; -const SECRET_VALUE = "secretValue"; -const CLEAR_PROPS$J = [ - SECRET_TYPE_ID, - SECRET_VALUE, -]; -class SecretBag extends PkiObject { - constructor(parameters = {}) { - super(); - this.secretTypeId = getParametersValue(parameters, SECRET_TYPE_ID, SecretBag.defaultValues(SECRET_TYPE_ID)); - this.secretValue = getParametersValue(parameters, SECRET_VALUE, SecretBag.defaultValues(SECRET_VALUE)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case SECRET_TYPE_ID: - return EMPTY_STRING; - case SECRET_VALUE: - return (new Any()); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case SECRET_TYPE_ID: - return (memberValue === EMPTY_STRING); - case SECRET_VALUE: - return (memberValue instanceof Any); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.id || "id") }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Any({ name: (names.value || "value") })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$J); - const asn1 = compareSchema(schema, schema, SecretBag.schema({ - names: { - id: SECRET_TYPE_ID, - value: SECRET_VALUE - } - })); - AsnError.assertSchema(asn1, this.className); - this.secretTypeId = asn1.result.secretTypeId.valueBlock.toString(); - this.secretValue = asn1.result.secretValue; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.secretTypeId }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.secretValue.toSchema()] - }) - ] - })); - } - toJSON() { - return { - secretTypeId: this.secretTypeId, - secretValue: this.secretValue.toJSON() - }; - } -} +const SECRET_TYPE_ID = "secretTypeId"; +const SECRET_VALUE = "secretValue"; +const CLEAR_PROPS$J = [ + SECRET_TYPE_ID, + SECRET_VALUE, +]; +class SecretBag extends PkiObject { + constructor(parameters = {}) { + super(); + this.secretTypeId = getParametersValue(parameters, SECRET_TYPE_ID, SecretBag.defaultValues(SECRET_TYPE_ID)); + this.secretValue = getParametersValue(parameters, SECRET_VALUE, SecretBag.defaultValues(SECRET_VALUE)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case SECRET_TYPE_ID: + return EMPTY_STRING; + case SECRET_VALUE: + return (new Any()); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case SECRET_TYPE_ID: + return (memberValue === EMPTY_STRING); + case SECRET_VALUE: + return (memberValue instanceof Any); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.id || "id") }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Any({ name: (names.value || "value") })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$J); + const asn1 = compareSchema(schema, schema, SecretBag.schema({ + names: { + id: SECRET_TYPE_ID, + value: SECRET_VALUE + } + })); + AsnError.assertSchema(asn1, this.className); + this.secretTypeId = asn1.result.secretTypeId.valueBlock.toString(); + this.secretValue = asn1.result.secretValue; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.secretTypeId }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.secretValue.toSchema()] + }) + ] + })); + } + toJSON() { + return { + secretTypeId: this.secretTypeId, + secretValue: this.secretValue.toJSON() + }; + } +} SecretBag.CLASS_NAME = "SecretBag"; -class SafeBagValueFactory { - static getItems() { - if (!this.items) { - this.items = {}; - SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.1", PrivateKeyInfo); - SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.2", PKCS8ShroudedKeyBag); - SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.3", CertBag); - SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.4", CRLBag); - SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.5", SecretBag); - SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.6", SafeContents); - } - return this.items; - } - static register(id, type) { - this.getItems()[id] = type; - } - static find(id) { - return this.getItems()[id] || null; - } +class SafeBagValueFactory { + static getItems() { + if (!this.items) { + this.items = {}; + SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.1", PrivateKeyInfo); + SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.2", PKCS8ShroudedKeyBag); + SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.3", CertBag); + SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.4", CRLBag); + SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.5", SecretBag); + SafeBagValueFactory.register("1.2.840.113549.1.12.10.1.6", SafeContents); + } + return this.items; + } + static register(id, type) { + this.getItems()[id] = type; + } + static find(id) { + return this.getItems()[id] || null; + } } -const BAG_ID = "bagId"; -const BAG_VALUE = "bagValue"; -const BAG_ATTRIBUTES = "bagAttributes"; -const CLEAR_PROPS$I = [ - BAG_ID, - BAG_VALUE, - BAG_ATTRIBUTES -]; -class SafeBag extends PkiObject { - constructor(parameters = {}) { - super(); - this.bagId = getParametersValue(parameters, BAG_ID, SafeBag.defaultValues(BAG_ID)); - this.bagValue = getParametersValue(parameters, BAG_VALUE, SafeBag.defaultValues(BAG_VALUE)); - if (BAG_ATTRIBUTES in parameters) { - this.bagAttributes = getParametersValue(parameters, BAG_ATTRIBUTES, SafeBag.defaultValues(BAG_ATTRIBUTES)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case BAG_ID: - return EMPTY_STRING; - case BAG_VALUE: - return (new Any()); - case BAG_ATTRIBUTES: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case BAG_ID: - return (memberValue === EMPTY_STRING); - case BAG_VALUE: - return (memberValue instanceof Any); - case BAG_ATTRIBUTES: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.bagId || BAG_ID) }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Any({ name: (names.bagValue || BAG_VALUE) })] - }), - new Set({ - optional: true, - value: [ - new Repeated({ - name: (names.bagAttributes || BAG_ATTRIBUTES), - value: Attribute.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$I); - const asn1 = compareSchema(schema, schema, SafeBag.schema({ - names: { - bagId: BAG_ID, - bagValue: BAG_VALUE, - bagAttributes: BAG_ATTRIBUTES - } - })); - AsnError.assertSchema(asn1, this.className); - this.bagId = asn1.result.bagId.valueBlock.toString(); - const bagType = SafeBagValueFactory.find(this.bagId); - if (!bagType) { - throw new Error(`Invalid BAG_ID for SafeBag: ${this.bagId}`); - } - this.bagValue = new bagType({ schema: asn1.result.bagValue }); - if (BAG_ATTRIBUTES in asn1.result) { - this.bagAttributes = Array.from(asn1.result.bagAttributes, element => new Attribute({ schema: element })); - } - } - toSchema() { - const outputArray = [ - new ObjectIdentifier({ value: this.bagId }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.bagValue.toSchema()] - }) - ]; - if (this.bagAttributes) { - outputArray.push(new Set({ - value: Array.from(this.bagAttributes, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const output = { - bagId: this.bagId, - bagValue: this.bagValue.toJSON() - }; - if (this.bagAttributes) { - output.bagAttributes = Array.from(this.bagAttributes, o => o.toJSON()); - } - return output; - } -} +const BAG_ID = "bagId"; +const BAG_VALUE = "bagValue"; +const BAG_ATTRIBUTES = "bagAttributes"; +const CLEAR_PROPS$I = [ + BAG_ID, + BAG_VALUE, + BAG_ATTRIBUTES +]; +class SafeBag extends PkiObject { + constructor(parameters = {}) { + super(); + this.bagId = getParametersValue(parameters, BAG_ID, SafeBag.defaultValues(BAG_ID)); + this.bagValue = getParametersValue(parameters, BAG_VALUE, SafeBag.defaultValues(BAG_VALUE)); + if (BAG_ATTRIBUTES in parameters) { + this.bagAttributes = getParametersValue(parameters, BAG_ATTRIBUTES, SafeBag.defaultValues(BAG_ATTRIBUTES)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case BAG_ID: + return EMPTY_STRING; + case BAG_VALUE: + return (new Any()); + case BAG_ATTRIBUTES: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case BAG_ID: + return (memberValue === EMPTY_STRING); + case BAG_VALUE: + return (memberValue instanceof Any); + case BAG_ATTRIBUTES: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.bagId || BAG_ID) }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Any({ name: (names.bagValue || BAG_VALUE) })] + }), + new Set({ + optional: true, + value: [ + new Repeated({ + name: (names.bagAttributes || BAG_ATTRIBUTES), + value: Attribute.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$I); + const asn1 = compareSchema(schema, schema, SafeBag.schema({ + names: { + bagId: BAG_ID, + bagValue: BAG_VALUE, + bagAttributes: BAG_ATTRIBUTES + } + })); + AsnError.assertSchema(asn1, this.className); + this.bagId = asn1.result.bagId.valueBlock.toString(); + const bagType = SafeBagValueFactory.find(this.bagId); + if (!bagType) { + throw new Error(`Invalid BAG_ID for SafeBag: ${this.bagId}`); + } + this.bagValue = new bagType({ schema: asn1.result.bagValue }); + if (BAG_ATTRIBUTES in asn1.result) { + this.bagAttributes = Array.from(asn1.result.bagAttributes, element => new Attribute({ schema: element })); + } + } + toSchema() { + const outputArray = [ + new ObjectIdentifier({ value: this.bagId }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.bagValue.toSchema()] + }) + ]; + if (this.bagAttributes) { + outputArray.push(new Set({ + value: Array.from(this.bagAttributes, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const output = { + bagId: this.bagId, + bagValue: this.bagValue.toJSON() + }; + if (this.bagAttributes) { + output.bagAttributes = Array.from(this.bagAttributes, o => o.toJSON()); + } + return output; + } +} SafeBag.CLASS_NAME = "SafeBag"; -const SAFE_BUGS = "safeBags"; -class SafeContents extends PkiObject { - constructor(parameters = {}) { - super(); - this.safeBags = getParametersValue(parameters, SAFE_BUGS, SafeContents.defaultValues(SAFE_BUGS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case SAFE_BUGS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case SAFE_BUGS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.safeBags || EMPTY_STRING), - value: SafeBag.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - SAFE_BUGS - ]); - const asn1 = compareSchema(schema, schema, SafeContents.schema({ - names: { - safeBags: SAFE_BUGS - } - })); - AsnError.assertSchema(asn1, this.className); - this.safeBags = Array.from(asn1.result.safeBags, element => new SafeBag({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.safeBags, o => o.toSchema()) - })); - } - toJSON() { - return { - safeBags: Array.from(this.safeBags, o => o.toJSON()) - }; - } -} -SafeContents.CLASS_NAME = "SafeContents"; - -const OTHER_CERT_FORMAT = "otherCertFormat"; -const OTHER_CERT = "otherCert"; -const CLEAR_PROPS$H = [ - OTHER_CERT_FORMAT, - OTHER_CERT -]; -class OtherCertificateFormat extends PkiObject { - constructor(parameters = {}) { - super(); - this.otherCertFormat = getParametersValue(parameters, OTHER_CERT_FORMAT, OtherCertificateFormat.defaultValues(OTHER_CERT_FORMAT)); - this.otherCert = getParametersValue(parameters, OTHER_CERT, OtherCertificateFormat.defaultValues(OTHER_CERT)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case OTHER_CERT_FORMAT: - return EMPTY_STRING; - case OTHER_CERT: - return new Any(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.otherCertFormat || OTHER_CERT_FORMAT) }), - new Any({ name: (names.otherCert || OTHER_CERT) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$H); - const asn1 = compareSchema(schema, schema, OtherCertificateFormat.schema()); - AsnError.assertSchema(asn1, this.className); - this.otherCertFormat = asn1.result.otherCertFormat.valueBlock.toString(); - this.otherCert = asn1.result.otherCert; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.otherCertFormat }), - this.otherCert - ] - })); - } - toJSON() { - const res = { - otherCertFormat: this.otherCertFormat - }; - if (!(this.otherCert instanceof Any)) { - res.otherCert = this.otherCert.toJSON(); - } - return res; - } +const SAFE_BUGS = "safeBags"; +class SafeContents extends PkiObject { + constructor(parameters = {}) { + super(); + this.safeBags = getParametersValue(parameters, SAFE_BUGS, SafeContents.defaultValues(SAFE_BUGS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case SAFE_BUGS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case SAFE_BUGS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.safeBags || EMPTY_STRING), + value: SafeBag.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + SAFE_BUGS + ]); + const asn1 = compareSchema(schema, schema, SafeContents.schema({ + names: { + safeBags: SAFE_BUGS + } + })); + AsnError.assertSchema(asn1, this.className); + this.safeBags = Array.from(asn1.result.safeBags, element => new SafeBag({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.safeBags, o => o.toSchema()) + })); + } + toJSON() { + return { + safeBags: Array.from(this.safeBags, o => o.toJSON()) + }; + } } +SafeContents.CLASS_NAME = "SafeContents"; -const CERTIFICATES$1 = "certificates"; -const CLEAR_PROPS$G = [ - CERTIFICATES$1, -]; -class CertificateSet extends PkiObject { - constructor(parameters = {}) { - super(); - this.certificates = getParametersValue(parameters, CERTIFICATES$1, CertificateSet.defaultValues(CERTIFICATES$1)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CERTIFICATES$1: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Set({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.certificates || CERTIFICATES$1), - value: new Choice({ - value: [ - Certificate.schema(), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Any() - ] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new Sequence - ] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: AttributeCertificateV2.schema().valueBlock.value - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - value: OtherCertificateFormat.schema().valueBlock.value - }) - ] - }) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$G); - const asn1 = compareSchema(schema, schema, CertificateSet.schema()); - AsnError.assertSchema(asn1, this.className); - this.certificates = Array.from(asn1.result.certificates || [], (element) => { - const initialTagNumber = element.idBlock.tagNumber; - if (element.idBlock.tagClass === 1) - return new Certificate({ schema: element }); - const elementSequence = new Sequence({ - value: element.valueBlock.value - }); - switch (initialTagNumber) { - case 1: - if (elementSequence.valueBlock.value[0].valueBlock.value[0].valueBlock.valueDec === 1) { - return new AttributeCertificateV2({ schema: elementSequence }); - } - else { - return new AttributeCertificateV1({ schema: elementSequence }); - } - case 2: - return new AttributeCertificateV2({ schema: elementSequence }); - case 3: - return new OtherCertificateFormat({ schema: elementSequence }); - } - return element; - }); - } - toSchema() { - return (new Set({ - value: Array.from(this.certificates, element => { - switch (true) { - case (element instanceof Certificate): - return element.toSchema(); - case (element instanceof AttributeCertificateV1): - return new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: element.toSchema().valueBlock.value - }); - case (element instanceof AttributeCertificateV2): - return new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: element.toSchema().valueBlock.value - }); - case (element instanceof OtherCertificateFormat): - return new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - value: element.toSchema().valueBlock.value - }); - } - return element.toSchema(); - }) - })); - } - toJSON() { - return { - certificates: Array.from(this.certificates, o => o.toJSON()) - }; - } -} +const OTHER_CERT_FORMAT = "otherCertFormat"; +const OTHER_CERT = "otherCert"; +const CLEAR_PROPS$H = [ + OTHER_CERT_FORMAT, + OTHER_CERT +]; +class OtherCertificateFormat extends PkiObject { + constructor(parameters = {}) { + super(); + this.otherCertFormat = getParametersValue(parameters, OTHER_CERT_FORMAT, OtherCertificateFormat.defaultValues(OTHER_CERT_FORMAT)); + this.otherCert = getParametersValue(parameters, OTHER_CERT, OtherCertificateFormat.defaultValues(OTHER_CERT)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case OTHER_CERT_FORMAT: + return EMPTY_STRING; + case OTHER_CERT: + return new Any(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.otherCertFormat || OTHER_CERT_FORMAT) }), + new Any({ name: (names.otherCert || OTHER_CERT) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$H); + const asn1 = compareSchema(schema, schema, OtherCertificateFormat.schema()); + AsnError.assertSchema(asn1, this.className); + this.otherCertFormat = asn1.result.otherCertFormat.valueBlock.toString(); + this.otherCert = asn1.result.otherCert; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.otherCertFormat }), + this.otherCert + ] + })); + } + toJSON() { + const res = { + otherCertFormat: this.otherCertFormat + }; + if (!(this.otherCert instanceof Any)) { + res.otherCert = this.otherCert.toJSON(); + } + return res; + } +} + +const CERTIFICATES$1 = "certificates"; +const CLEAR_PROPS$G = [ + CERTIFICATES$1, +]; +class CertificateSet extends PkiObject { + constructor(parameters = {}) { + super(); + this.certificates = getParametersValue(parameters, CERTIFICATES$1, CertificateSet.defaultValues(CERTIFICATES$1)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CERTIFICATES$1: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Set({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.certificates || CERTIFICATES$1), + value: new Choice({ + value: [ + Certificate.schema(), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Any() + ] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new Sequence + ] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: AttributeCertificateV2.schema().valueBlock.value + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + value: OtherCertificateFormat.schema().valueBlock.value + }) + ] + }) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$G); + const asn1 = compareSchema(schema, schema, CertificateSet.schema()); + AsnError.assertSchema(asn1, this.className); + this.certificates = Array.from(asn1.result.certificates || [], (element) => { + const initialTagNumber = element.idBlock.tagNumber; + if (element.idBlock.tagClass === 1) + return new Certificate({ schema: element }); + const elementSequence = new Sequence({ + value: element.valueBlock.value + }); + switch (initialTagNumber) { + case 1: + if (elementSequence.valueBlock.value[0].valueBlock.value[0].valueBlock.valueDec === 1) { + return new AttributeCertificateV2({ schema: elementSequence }); + } + else { + return new AttributeCertificateV1({ schema: elementSequence }); + } + case 2: + return new AttributeCertificateV2({ schema: elementSequence }); + case 3: + return new OtherCertificateFormat({ schema: elementSequence }); + } + return element; + }); + } + toSchema() { + return (new Set({ + value: Array.from(this.certificates, element => { + switch (true) { + case (element instanceof Certificate): + return element.toSchema(); + case (element instanceof AttributeCertificateV1): + return new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: element.toSchema().valueBlock.value + }); + case (element instanceof AttributeCertificateV2): + return new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: element.toSchema().valueBlock.value + }); + case (element instanceof OtherCertificateFormat): + return new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + value: element.toSchema().valueBlock.value + }); + } + return element.toSchema(); + }) + })); + } + toJSON() { + return { + certificates: Array.from(this.certificates, o => o.toJSON()) + }; + } +} CertificateSet.CLASS_NAME = "CertificateSet"; -const OTHER_REV_INFO_FORMAT = "otherRevInfoFormat"; -const OTHER_REV_INFO = "otherRevInfo"; -const CLEAR_PROPS$F = [ - OTHER_REV_INFO_FORMAT, - OTHER_REV_INFO -]; -class OtherRevocationInfoFormat extends PkiObject { - constructor(parameters = {}) { - super(); - this.otherRevInfoFormat = getParametersValue(parameters, OTHER_REV_INFO_FORMAT, OtherRevocationInfoFormat.defaultValues(OTHER_REV_INFO_FORMAT)); - this.otherRevInfo = getParametersValue(parameters, OTHER_REV_INFO, OtherRevocationInfoFormat.defaultValues(OTHER_REV_INFO)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case OTHER_REV_INFO_FORMAT: - return EMPTY_STRING; - case OTHER_REV_INFO: - return new Any(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.otherRevInfoFormat || OTHER_REV_INFO_FORMAT) }), - new Any({ name: (names.otherRevInfo || OTHER_REV_INFO) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$F); - const asn1 = compareSchema(schema, schema, OtherRevocationInfoFormat.schema()); - AsnError.assertSchema(asn1, this.className); - this.otherRevInfoFormat = asn1.result.otherRevInfoFormat.valueBlock.toString(); - this.otherRevInfo = asn1.result.otherRevInfo; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.otherRevInfoFormat }), - this.otherRevInfo - ] - })); - } - toJSON() { - const res = { - otherRevInfoFormat: this.otherRevInfoFormat - }; - if (!(this.otherRevInfo instanceof Any)) { - res.otherRevInfo = this.otherRevInfo.toJSON(); - } - return res; - } -} +const OTHER_REV_INFO_FORMAT = "otherRevInfoFormat"; +const OTHER_REV_INFO = "otherRevInfo"; +const CLEAR_PROPS$F = [ + OTHER_REV_INFO_FORMAT, + OTHER_REV_INFO +]; +class OtherRevocationInfoFormat extends PkiObject { + constructor(parameters = {}) { + super(); + this.otherRevInfoFormat = getParametersValue(parameters, OTHER_REV_INFO_FORMAT, OtherRevocationInfoFormat.defaultValues(OTHER_REV_INFO_FORMAT)); + this.otherRevInfo = getParametersValue(parameters, OTHER_REV_INFO, OtherRevocationInfoFormat.defaultValues(OTHER_REV_INFO)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case OTHER_REV_INFO_FORMAT: + return EMPTY_STRING; + case OTHER_REV_INFO: + return new Any(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.otherRevInfoFormat || OTHER_REV_INFO_FORMAT) }), + new Any({ name: (names.otherRevInfo || OTHER_REV_INFO) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$F); + const asn1 = compareSchema(schema, schema, OtherRevocationInfoFormat.schema()); + AsnError.assertSchema(asn1, this.className); + this.otherRevInfoFormat = asn1.result.otherRevInfoFormat.valueBlock.toString(); + this.otherRevInfo = asn1.result.otherRevInfo; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.otherRevInfoFormat }), + this.otherRevInfo + ] + })); + } + toJSON() { + const res = { + otherRevInfoFormat: this.otherRevInfoFormat + }; + if (!(this.otherRevInfo instanceof Any)) { + res.otherRevInfo = this.otherRevInfo.toJSON(); + } + return res; + } +} OtherRevocationInfoFormat.CLASS_NAME = "OtherRevocationInfoFormat"; -const CRLS$3 = "crls"; -const OTHER_REVOCATION_INFOS = "otherRevocationInfos"; -const CLEAR_PROPS$E = [ - CRLS$3 -]; -class RevocationInfoChoices extends PkiObject { - constructor(parameters = {}) { - super(); - this.crls = getParametersValue(parameters, CRLS$3, RevocationInfoChoices.defaultValues(CRLS$3)); - this.otherRevocationInfos = getParametersValue(parameters, OTHER_REVOCATION_INFOS, RevocationInfoChoices.defaultValues(OTHER_REVOCATION_INFOS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CRLS$3: - return []; - case OTHER_REVOCATION_INFOS: - return []; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Set({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.crls || EMPTY_STRING), - value: new Choice({ - value: [ - CertificateRevocationList.schema(), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new ObjectIdentifier(), - new Any() - ] - }) - ] - }) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$E); - const asn1 = compareSchema(schema, schema, RevocationInfoChoices.schema({ - names: { - crls: CRLS$3 - } - })); - AsnError.assertSchema(asn1, this.className); - if (asn1.result.crls) { - for (const element of asn1.result.crls) { - if (element.idBlock.tagClass === 1) - this.crls.push(new CertificateRevocationList({ schema: element })); - else - this.otherRevocationInfos.push(new OtherRevocationInfoFormat({ schema: element })); - } - } - } - toSchema() { - const outputArray = []; - outputArray.push(...Array.from(this.crls, o => o.toSchema())); - outputArray.push(...Array.from(this.otherRevocationInfos, element => { - const schema = element.toSchema(); - schema.idBlock.tagClass = 3; - schema.idBlock.tagNumber = 1; - return schema; - })); - return (new Set({ - value: outputArray - })); - } - toJSON() { - return { - crls: Array.from(this.crls, o => o.toJSON()), - otherRevocationInfos: Array.from(this.otherRevocationInfos, o => o.toJSON()) - }; - } -} +const CRLS$3 = "crls"; +const OTHER_REVOCATION_INFOS = "otherRevocationInfos"; +const CLEAR_PROPS$E = [ + CRLS$3 +]; +class RevocationInfoChoices extends PkiObject { + constructor(parameters = {}) { + super(); + this.crls = getParametersValue(parameters, CRLS$3, RevocationInfoChoices.defaultValues(CRLS$3)); + this.otherRevocationInfos = getParametersValue(parameters, OTHER_REVOCATION_INFOS, RevocationInfoChoices.defaultValues(OTHER_REVOCATION_INFOS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CRLS$3: + return []; + case OTHER_REVOCATION_INFOS: + return []; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Set({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.crls || EMPTY_STRING), + value: new Choice({ + value: [ + CertificateRevocationList.schema(), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new ObjectIdentifier(), + new Any() + ] + }) + ] + }) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$E); + const asn1 = compareSchema(schema, schema, RevocationInfoChoices.schema({ + names: { + crls: CRLS$3 + } + })); + AsnError.assertSchema(asn1, this.className); + if (asn1.result.crls) { + for (const element of asn1.result.crls) { + if (element.idBlock.tagClass === 1) + this.crls.push(new CertificateRevocationList({ schema: element })); + else + this.otherRevocationInfos.push(new OtherRevocationInfoFormat({ schema: element })); + } + } + } + toSchema() { + const outputArray = []; + outputArray.push(...Array.from(this.crls, o => o.toSchema())); + outputArray.push(...Array.from(this.otherRevocationInfos, element => { + const schema = element.toSchema(); + schema.idBlock.tagClass = 3; + schema.idBlock.tagNumber = 1; + return schema; + })); + return (new Set({ + value: outputArray + })); + } + toJSON() { + return { + crls: Array.from(this.crls, o => o.toJSON()), + otherRevocationInfos: Array.from(this.otherRevocationInfos, o => o.toJSON()) + }; + } +} RevocationInfoChoices.CLASS_NAME = "RevocationInfoChoices"; -const CERTS$3 = "certs"; -const CRLS$2 = "crls"; -const CLEAR_PROPS$D = [ - CERTS$3, - CRLS$2, -]; -class OriginatorInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.crls = getParametersValue(parameters, CRLS$2, OriginatorInfo.defaultValues(CRLS$2)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CERTS$3: - return new CertificateSet(); - case CRLS$2: - return new RevocationInfoChoices(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case CERTS$3: - return (memberValue.certificates.length === 0); - case CRLS$2: - return ((memberValue.crls.length === 0) && (memberValue.otherRevocationInfos.length === 0)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - name: (names.certs || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: CertificateSet.schema().valueBlock.value - }), - new Constructed({ - name: (names.crls || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: RevocationInfoChoices.schema().valueBlock.value - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$D); - const asn1 = compareSchema(schema, schema, OriginatorInfo.schema({ - names: { - certs: CERTS$3, - crls: CRLS$2 - } - })); - AsnError.assertSchema(asn1, this.className); - if (CERTS$3 in asn1.result) { - this.certs = new CertificateSet({ - schema: new Set({ - value: asn1.result.certs.valueBlock.value - }) - }); - } - if (CRLS$2 in asn1.result) { - this.crls = new RevocationInfoChoices({ - schema: new Set({ - value: asn1.result.crls.valueBlock.value - }) - }); - } - } - toSchema() { - const sequenceValue = []; - if (this.certs) { - sequenceValue.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.certs.toSchema().valueBlock.value - })); - } - if (this.crls) { - sequenceValue.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: this.crls.toSchema().valueBlock.value - })); - } - return (new Sequence({ - value: sequenceValue - })); - } - toJSON() { - const res = {}; - if (this.certs) { - res.certs = this.certs.toJSON(); - } - if (this.crls) { - res.crls = this.crls.toJSON(); - } - return res; - } -} +const CERTS$3 = "certs"; +const CRLS$2 = "crls"; +const CLEAR_PROPS$D = [ + CERTS$3, + CRLS$2, +]; +class OriginatorInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.crls = getParametersValue(parameters, CRLS$2, OriginatorInfo.defaultValues(CRLS$2)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CERTS$3: + return new CertificateSet(); + case CRLS$2: + return new RevocationInfoChoices(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case CERTS$3: + return (memberValue.certificates.length === 0); + case CRLS$2: + return ((memberValue.crls.length === 0) && (memberValue.otherRevocationInfos.length === 0)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + name: (names.certs || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: CertificateSet.schema().valueBlock.value + }), + new Constructed({ + name: (names.crls || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: RevocationInfoChoices.schema().valueBlock.value + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$D); + const asn1 = compareSchema(schema, schema, OriginatorInfo.schema({ + names: { + certs: CERTS$3, + crls: CRLS$2 + } + })); + AsnError.assertSchema(asn1, this.className); + if (CERTS$3 in asn1.result) { + this.certs = new CertificateSet({ + schema: new Set({ + value: asn1.result.certs.valueBlock.value + }) + }); + } + if (CRLS$2 in asn1.result) { + this.crls = new RevocationInfoChoices({ + schema: new Set({ + value: asn1.result.crls.valueBlock.value + }) + }); + } + } + toSchema() { + const sequenceValue = []; + if (this.certs) { + sequenceValue.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.certs.toSchema().valueBlock.value + })); + } + if (this.crls) { + sequenceValue.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: this.crls.toSchema().valueBlock.value + })); + } + return (new Sequence({ + value: sequenceValue + })); + } + toJSON() { + const res = {}; + if (this.certs) { + res.certs = this.certs.toJSON(); + } + if (this.crls) { + res.crls = this.crls.toJSON(); + } + return res; + } +} OriginatorInfo.CLASS_NAME = "OriginatorInfo"; -const ISSUER = "issuer"; -const SERIAL_NUMBER$2 = "serialNumber"; -const CLEAR_PROPS$C = [ - ISSUER, - SERIAL_NUMBER$2, -]; -class IssuerAndSerialNumber extends PkiObject { - constructor(parameters = {}) { - super(); - this.issuer = getParametersValue(parameters, ISSUER, IssuerAndSerialNumber.defaultValues(ISSUER)); - this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$2, IssuerAndSerialNumber.defaultValues(SERIAL_NUMBER$2)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ISSUER: - return new RelativeDistinguishedNames(); - case SERIAL_NUMBER$2: - return new Integer(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - RelativeDistinguishedNames.schema(names.issuer || {}), - new Integer({ name: (names.serialNumber || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$C); - const asn1 = compareSchema(schema, schema, IssuerAndSerialNumber.schema({ - names: { - issuer: { - names: { - blockName: ISSUER - } - }, - serialNumber: SERIAL_NUMBER$2 - } - })); - AsnError.assertSchema(asn1, this.className); - this.issuer = new RelativeDistinguishedNames({ schema: asn1.result.issuer }); - this.serialNumber = asn1.result.serialNumber; - } - toSchema() { - return (new Sequence({ - value: [ - this.issuer.toSchema(), - this.serialNumber - ] - })); - } - toJSON() { - return { - issuer: this.issuer.toJSON(), - serialNumber: this.serialNumber.toJSON(), - }; - } -} +const ISSUER = "issuer"; +const SERIAL_NUMBER$2 = "serialNumber"; +const CLEAR_PROPS$C = [ + ISSUER, + SERIAL_NUMBER$2, +]; +class IssuerAndSerialNumber extends PkiObject { + constructor(parameters = {}) { + super(); + this.issuer = getParametersValue(parameters, ISSUER, IssuerAndSerialNumber.defaultValues(ISSUER)); + this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$2, IssuerAndSerialNumber.defaultValues(SERIAL_NUMBER$2)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ISSUER: + return new RelativeDistinguishedNames(); + case SERIAL_NUMBER$2: + return new Integer(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + RelativeDistinguishedNames.schema(names.issuer || {}), + new Integer({ name: (names.serialNumber || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$C); + const asn1 = compareSchema(schema, schema, IssuerAndSerialNumber.schema({ + names: { + issuer: { + names: { + blockName: ISSUER + } + }, + serialNumber: SERIAL_NUMBER$2 + } + })); + AsnError.assertSchema(asn1, this.className); + this.issuer = new RelativeDistinguishedNames({ schema: asn1.result.issuer }); + this.serialNumber = asn1.result.serialNumber; + } + toSchema() { + return (new Sequence({ + value: [ + this.issuer.toSchema(), + this.serialNumber + ] + })); + } + toJSON() { + return { + issuer: this.issuer.toJSON(), + serialNumber: this.serialNumber.toJSON(), + }; + } +} IssuerAndSerialNumber.CLASS_NAME = "IssuerAndSerialNumber"; -const VARIANT$3 = "variant"; -const VALUE$3 = "value"; -const CLEAR_PROPS$B = [ - "blockName" -]; -class RecipientIdentifier extends PkiObject { - constructor(parameters = {}) { - super(); - this.variant = getParametersValue(parameters, VARIANT$3, RecipientIdentifier.defaultValues(VARIANT$3)); - if (VALUE$3 in parameters) { - this.value = getParametersValue(parameters, VALUE$3, RecipientIdentifier.defaultValues(VALUE$3)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VARIANT$3: - return (-1); - case VALUE$3: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VARIANT$3: - return (memberValue === (-1)); - case VALUE$3: - return (Object.keys(memberValue).length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Choice({ - value: [ - IssuerAndSerialNumber.schema({ - names: { - blockName: (names.blockName || EMPTY_STRING) - } - }), - new Primitive({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$B); - const asn1 = compareSchema(schema, schema, RecipientIdentifier.schema({ - names: { - blockName: "blockName" - } - })); - AsnError.assertSchema(asn1, this.className); - if (asn1.result.blockName.idBlock.tagClass === 1) { - this.variant = 1; - this.value = new IssuerAndSerialNumber({ schema: asn1.result.blockName }); - } - else { - this.variant = 2; - this.value = new OctetString({ valueHex: asn1.result.blockName.valueBlock.valueHex }); - } - } - toSchema() { - switch (this.variant) { - case 1: - if (!(this.value instanceof IssuerAndSerialNumber)) { - throw new Error("Incorrect type of RecipientIdentifier.value. It should be IssuerAndSerialNumber."); - } - return this.value.toSchema(); - case 2: - if (!(this.value instanceof OctetString)) { - throw new Error("Incorrect type of RecipientIdentifier.value. It should be ASN.1 OctetString."); - } - return new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - valueHex: this.value.valueBlock.valueHexView - }); - default: - return new Any(); - } - } - toJSON() { - const res = { - variant: this.variant - }; - if ((this.variant === 1 || this.variant === 2) && this.value) { - res.value = this.value.toJSON(); - } - return res; - } -} +const VARIANT$3 = "variant"; +const VALUE$3 = "value"; +const CLEAR_PROPS$B = [ + "blockName" +]; +class RecipientIdentifier extends PkiObject { + constructor(parameters = {}) { + super(); + this.variant = getParametersValue(parameters, VARIANT$3, RecipientIdentifier.defaultValues(VARIANT$3)); + if (VALUE$3 in parameters) { + this.value = getParametersValue(parameters, VALUE$3, RecipientIdentifier.defaultValues(VALUE$3)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VARIANT$3: + return (-1); + case VALUE$3: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VARIANT$3: + return (memberValue === (-1)); + case VALUE$3: + return (Object.keys(memberValue).length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Choice({ + value: [ + IssuerAndSerialNumber.schema({ + names: { + blockName: (names.blockName || EMPTY_STRING) + } + }), + new Primitive({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$B); + const asn1 = compareSchema(schema, schema, RecipientIdentifier.schema({ + names: { + blockName: "blockName" + } + })); + AsnError.assertSchema(asn1, this.className); + if (asn1.result.blockName.idBlock.tagClass === 1) { + this.variant = 1; + this.value = new IssuerAndSerialNumber({ schema: asn1.result.blockName }); + } + else { + this.variant = 2; + this.value = new OctetString({ valueHex: asn1.result.blockName.valueBlock.valueHex }); + } + } + toSchema() { + switch (this.variant) { + case 1: + if (!(this.value instanceof IssuerAndSerialNumber)) { + throw new Error("Incorrect type of RecipientIdentifier.value. It should be IssuerAndSerialNumber."); + } + return this.value.toSchema(); + case 2: + if (!(this.value instanceof OctetString)) { + throw new Error("Incorrect type of RecipientIdentifier.value. It should be ASN.1 OctetString."); + } + return new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + valueHex: this.value.valueBlock.valueHexView + }); + default: + return new Any(); + } + } + toJSON() { + const res = { + variant: this.variant + }; + if ((this.variant === 1 || this.variant === 2) && this.value) { + res.value = this.value.toJSON(); + } + return res; + } +} RecipientIdentifier.CLASS_NAME = "RecipientIdentifier"; -const VERSION$c = "version"; -const RID$1 = "rid"; -const KEY_ENCRYPTION_ALGORITHM$3 = "keyEncryptionAlgorithm"; -const ENCRYPTED_KEY$3 = "encryptedKey"; -const RECIPIENT_CERTIFICATE$1 = "recipientCertificate"; -const CLEAR_PROPS$A = [ - VERSION$c, - RID$1, - KEY_ENCRYPTION_ALGORITHM$3, - ENCRYPTED_KEY$3, -]; -class KeyTransRecipientInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$c, KeyTransRecipientInfo.defaultValues(VERSION$c)); - this.rid = getParametersValue(parameters, RID$1, KeyTransRecipientInfo.defaultValues(RID$1)); - this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM$3, KeyTransRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM$3)); - this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY$3, KeyTransRecipientInfo.defaultValues(ENCRYPTED_KEY$3)); - this.recipientCertificate = getParametersValue(parameters, RECIPIENT_CERTIFICATE$1, KeyTransRecipientInfo.defaultValues(RECIPIENT_CERTIFICATE$1)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$c: - return (-1); - case RID$1: - return {}; - case KEY_ENCRYPTION_ALGORITHM$3: - return new AlgorithmIdentifier(); - case ENCRYPTED_KEY$3: - return new OctetString(); - case RECIPIENT_CERTIFICATE$1: - return new Certificate(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$c: - return (memberValue === KeyTransRecipientInfo.defaultValues(VERSION$c)); - case RID$1: - return (Object.keys(memberValue).length === 0); - case KEY_ENCRYPTION_ALGORITHM$3: - case ENCRYPTED_KEY$3: - return memberValue.isEqual(KeyTransRecipientInfo.defaultValues(memberName)); - case RECIPIENT_CERTIFICATE$1: - return false; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - RecipientIdentifier.schema(names.rid || {}), - AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), - new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$A); - const asn1 = compareSchema(schema, schema, KeyTransRecipientInfo.schema({ - names: { - version: VERSION$c, - rid: { - names: { - blockName: RID$1 - } - }, - keyEncryptionAlgorithm: { - names: { - blockName: KEY_ENCRYPTION_ALGORITHM$3 - } - }, - encryptedKey: ENCRYPTED_KEY$3 - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - if (asn1.result.rid.idBlock.tagClass === 3) { - this.rid = new OctetString({ valueHex: asn1.result.rid.valueBlock.valueHex }); - } - else { - this.rid = new IssuerAndSerialNumber({ schema: asn1.result.rid }); - } - this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); - this.encryptedKey = asn1.result.encryptedKey; - } - toSchema() { - const outputArray = []; - if (this.rid instanceof IssuerAndSerialNumber) { - this.version = 0; - outputArray.push(new Integer({ value: this.version })); - outputArray.push(this.rid.toSchema()); - } - else { - this.version = 2; - outputArray.push(new Integer({ value: this.version })); - outputArray.push(new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - valueHex: this.rid.valueBlock.valueHexView - })); - } - outputArray.push(this.keyEncryptionAlgorithm.toSchema()); - outputArray.push(this.encryptedKey); - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - return { - version: this.version, - rid: this.rid.toJSON(), - keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), - encryptedKey: this.encryptedKey.toJSON(), - }; - } -} -KeyTransRecipientInfo.CLASS_NAME = "KeyTransRecipientInfo"; - -const ALGORITHM = "algorithm"; -const PUBLIC_KEY = "publicKey"; -const CLEAR_PROPS$z = [ - ALGORITHM, - PUBLIC_KEY -]; -class OriginatorPublicKey extends PkiObject { - constructor(parameters = {}) { - super(); - this.algorithm = getParametersValue(parameters, ALGORITHM, OriginatorPublicKey.defaultValues(ALGORITHM)); - this.publicKey = getParametersValue(parameters, PUBLIC_KEY, OriginatorPublicKey.defaultValues(PUBLIC_KEY)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ALGORITHM: - return new AlgorithmIdentifier(); - case PUBLIC_KEY: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case ALGORITHM: - case PUBLIC_KEY: - return (memberValue.isEqual(OriginatorPublicKey.defaultValues(memberName))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.algorithm || {}), - new BitString({ name: (names.publicKey || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$z); - const asn1 = compareSchema(schema, schema, OriginatorPublicKey.schema({ - names: { - algorithm: { - names: { - blockName: ALGORITHM - } - }, - publicKey: PUBLIC_KEY - } - })); - AsnError.assertSchema(asn1, this.className); - this.algorithm = new AlgorithmIdentifier({ schema: asn1.result.algorithm }); - this.publicKey = asn1.result.publicKey; - } - toSchema() { - return (new Sequence({ - value: [ - this.algorithm.toSchema(), - this.publicKey - ] - })); - } - toJSON() { - return { - algorithm: this.algorithm.toJSON(), - publicKey: this.publicKey.toJSON(), - }; - } -} +const VERSION$c = "version"; +const RID$1 = "rid"; +const KEY_ENCRYPTION_ALGORITHM$3 = "keyEncryptionAlgorithm"; +const ENCRYPTED_KEY$3 = "encryptedKey"; +const RECIPIENT_CERTIFICATE$1 = "recipientCertificate"; +const CLEAR_PROPS$A = [ + VERSION$c, + RID$1, + KEY_ENCRYPTION_ALGORITHM$3, + ENCRYPTED_KEY$3, +]; +class KeyTransRecipientInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$c, KeyTransRecipientInfo.defaultValues(VERSION$c)); + this.rid = getParametersValue(parameters, RID$1, KeyTransRecipientInfo.defaultValues(RID$1)); + this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM$3, KeyTransRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM$3)); + this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY$3, KeyTransRecipientInfo.defaultValues(ENCRYPTED_KEY$3)); + this.recipientCertificate = getParametersValue(parameters, RECIPIENT_CERTIFICATE$1, KeyTransRecipientInfo.defaultValues(RECIPIENT_CERTIFICATE$1)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$c: + return (-1); + case RID$1: + return {}; + case KEY_ENCRYPTION_ALGORITHM$3: + return new AlgorithmIdentifier(); + case ENCRYPTED_KEY$3: + return new OctetString(); + case RECIPIENT_CERTIFICATE$1: + return new Certificate(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$c: + return (memberValue === KeyTransRecipientInfo.defaultValues(VERSION$c)); + case RID$1: + return (Object.keys(memberValue).length === 0); + case KEY_ENCRYPTION_ALGORITHM$3: + case ENCRYPTED_KEY$3: + return memberValue.isEqual(KeyTransRecipientInfo.defaultValues(memberName)); + case RECIPIENT_CERTIFICATE$1: + return false; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + RecipientIdentifier.schema(names.rid || {}), + AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), + new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$A); + const asn1 = compareSchema(schema, schema, KeyTransRecipientInfo.schema({ + names: { + version: VERSION$c, + rid: { + names: { + blockName: RID$1 + } + }, + keyEncryptionAlgorithm: { + names: { + blockName: KEY_ENCRYPTION_ALGORITHM$3 + } + }, + encryptedKey: ENCRYPTED_KEY$3 + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + if (asn1.result.rid.idBlock.tagClass === 3) { + this.rid = new OctetString({ valueHex: asn1.result.rid.valueBlock.valueHex }); + } + else { + this.rid = new IssuerAndSerialNumber({ schema: asn1.result.rid }); + } + this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); + this.encryptedKey = asn1.result.encryptedKey; + } + toSchema() { + const outputArray = []; + if (this.rid instanceof IssuerAndSerialNumber) { + this.version = 0; + outputArray.push(new Integer({ value: this.version })); + outputArray.push(this.rid.toSchema()); + } + else { + this.version = 2; + outputArray.push(new Integer({ value: this.version })); + outputArray.push(new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + valueHex: this.rid.valueBlock.valueHexView + })); + } + outputArray.push(this.keyEncryptionAlgorithm.toSchema()); + outputArray.push(this.encryptedKey); + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + return { + version: this.version, + rid: this.rid.toJSON(), + keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), + encryptedKey: this.encryptedKey.toJSON(), + }; + } +} +KeyTransRecipientInfo.CLASS_NAME = "KeyTransRecipientInfo"; + +const ALGORITHM = "algorithm"; +const PUBLIC_KEY = "publicKey"; +const CLEAR_PROPS$z = [ + ALGORITHM, + PUBLIC_KEY +]; +class OriginatorPublicKey extends PkiObject { + constructor(parameters = {}) { + super(); + this.algorithm = getParametersValue(parameters, ALGORITHM, OriginatorPublicKey.defaultValues(ALGORITHM)); + this.publicKey = getParametersValue(parameters, PUBLIC_KEY, OriginatorPublicKey.defaultValues(PUBLIC_KEY)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ALGORITHM: + return new AlgorithmIdentifier(); + case PUBLIC_KEY: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case ALGORITHM: + case PUBLIC_KEY: + return (memberValue.isEqual(OriginatorPublicKey.defaultValues(memberName))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.algorithm || {}), + new BitString({ name: (names.publicKey || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$z); + const asn1 = compareSchema(schema, schema, OriginatorPublicKey.schema({ + names: { + algorithm: { + names: { + blockName: ALGORITHM + } + }, + publicKey: PUBLIC_KEY + } + })); + AsnError.assertSchema(asn1, this.className); + this.algorithm = new AlgorithmIdentifier({ schema: asn1.result.algorithm }); + this.publicKey = asn1.result.publicKey; + } + toSchema() { + return (new Sequence({ + value: [ + this.algorithm.toSchema(), + this.publicKey + ] + })); + } + toJSON() { + return { + algorithm: this.algorithm.toJSON(), + publicKey: this.publicKey.toJSON(), + }; + } +} OriginatorPublicKey.CLASS_NAME = "OriginatorPublicKey"; -const VARIANT$2 = "variant"; -const VALUE$2 = "value"; -const CLEAR_PROPS$y = [ - "blockName", -]; -class OriginatorIdentifierOrKey extends PkiObject { - constructor(parameters = {}) { - super(); - this.variant = getParametersValue(parameters, VARIANT$2, OriginatorIdentifierOrKey.defaultValues(VARIANT$2)); - if (VALUE$2 in parameters) { - this.value = getParametersValue(parameters, VALUE$2, OriginatorIdentifierOrKey.defaultValues(VALUE$2)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VARIANT$2: - return (-1); - case VALUE$2: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VARIANT$2: - return (memberValue === (-1)); - case VALUE$2: - return (Object.keys(memberValue).length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Choice({ - value: [ - IssuerAndSerialNumber.schema({ - names: { - blockName: (names.blockName || EMPTY_STRING) - } - }), - new Primitive({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - name: (names.blockName || EMPTY_STRING) - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - name: (names.blockName || EMPTY_STRING), - value: OriginatorPublicKey.schema().valueBlock.value - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$y); - const asn1 = compareSchema(schema, schema, OriginatorIdentifierOrKey.schema({ - names: { - blockName: "blockName" - } - })); - AsnError.assertSchema(asn1, this.className); - if (asn1.result.blockName.idBlock.tagClass === 1) { - this.variant = 1; - this.value = new IssuerAndSerialNumber({ schema: asn1.result.blockName }); - } - else { - if (asn1.result.blockName.idBlock.tagNumber === 0) { - asn1.result.blockName.idBlock.tagClass = 1; - asn1.result.blockName.idBlock.tagNumber = 4; - this.variant = 2; - this.value = asn1.result.blockName; - } - else { - this.variant = 3; - this.value = new OriginatorPublicKey({ - schema: new Sequence({ - value: asn1.result.blockName.valueBlock.value - }) - }); - } - } - } - toSchema() { - switch (this.variant) { - case 1: - return this.value.toSchema(); - case 2: - this.value.idBlock.tagClass = 3; - this.value.idBlock.tagNumber = 0; - return this.value; - case 3: - { - const _schema = this.value.toSchema(); - _schema.idBlock.tagClass = 3; - _schema.idBlock.tagNumber = 1; - return _schema; - } - default: - return new Any(); - } - } - toJSON() { - const res = { - variant: this.variant - }; - if ((this.variant === 1) || (this.variant === 2) || (this.variant === 3)) { - res.value = this.value.toJSON(); - } - return res; - } -} +const VARIANT$2 = "variant"; +const VALUE$2 = "value"; +const CLEAR_PROPS$y = [ + "blockName", +]; +class OriginatorIdentifierOrKey extends PkiObject { + constructor(parameters = {}) { + super(); + this.variant = getParametersValue(parameters, VARIANT$2, OriginatorIdentifierOrKey.defaultValues(VARIANT$2)); + if (VALUE$2 in parameters) { + this.value = getParametersValue(parameters, VALUE$2, OriginatorIdentifierOrKey.defaultValues(VALUE$2)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VARIANT$2: + return (-1); + case VALUE$2: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VARIANT$2: + return (memberValue === (-1)); + case VALUE$2: + return (Object.keys(memberValue).length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Choice({ + value: [ + IssuerAndSerialNumber.schema({ + names: { + blockName: (names.blockName || EMPTY_STRING) + } + }), + new Primitive({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + name: (names.blockName || EMPTY_STRING) + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + name: (names.blockName || EMPTY_STRING), + value: OriginatorPublicKey.schema().valueBlock.value + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$y); + const asn1 = compareSchema(schema, schema, OriginatorIdentifierOrKey.schema({ + names: { + blockName: "blockName" + } + })); + AsnError.assertSchema(asn1, this.className); + if (asn1.result.blockName.idBlock.tagClass === 1) { + this.variant = 1; + this.value = new IssuerAndSerialNumber({ schema: asn1.result.blockName }); + } + else { + if (asn1.result.blockName.idBlock.tagNumber === 0) { + asn1.result.blockName.idBlock.tagClass = 1; + asn1.result.blockName.idBlock.tagNumber = 4; + this.variant = 2; + this.value = asn1.result.blockName; + } + else { + this.variant = 3; + this.value = new OriginatorPublicKey({ + schema: new Sequence({ + value: asn1.result.blockName.valueBlock.value + }) + }); + } + } + } + toSchema() { + switch (this.variant) { + case 1: + return this.value.toSchema(); + case 2: + this.value.idBlock.tagClass = 3; + this.value.idBlock.tagNumber = 0; + return this.value; + case 3: + { + const _schema = this.value.toSchema(); + _schema.idBlock.tagClass = 3; + _schema.idBlock.tagNumber = 1; + return _schema; + } + default: + return new Any(); + } + } + toJSON() { + const res = { + variant: this.variant + }; + if ((this.variant === 1) || (this.variant === 2) || (this.variant === 3)) { + res.value = this.value.toJSON(); + } + return res; + } +} OriginatorIdentifierOrKey.CLASS_NAME = "OriginatorIdentifierOrKey"; -const KEY_ATTR_ID = "keyAttrId"; -const KEY_ATTR = "keyAttr"; -const CLEAR_PROPS$x = [ - KEY_ATTR_ID, - KEY_ATTR, -]; -class OtherKeyAttribute extends PkiObject { - constructor(parameters = {}) { - super(); - this.keyAttrId = getParametersValue(parameters, KEY_ATTR_ID, OtherKeyAttribute.defaultValues(KEY_ATTR_ID)); - if (KEY_ATTR in parameters) { - this.keyAttr = getParametersValue(parameters, KEY_ATTR, OtherKeyAttribute.defaultValues(KEY_ATTR)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case KEY_ATTR_ID: - return EMPTY_STRING; - case KEY_ATTR: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case KEY_ATTR_ID: - return (typeof memberValue === "string" && memberValue === EMPTY_STRING); - case KEY_ATTR: - return (Object.keys(memberValue).length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - optional: (names.optional || true), - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.keyAttrId || EMPTY_STRING) }), - new Any({ - optional: true, - name: (names.keyAttr || EMPTY_STRING) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$x); - const asn1 = compareSchema(schema, schema, OtherKeyAttribute.schema({ - names: { - keyAttrId: KEY_ATTR_ID, - keyAttr: KEY_ATTR - } - })); - AsnError.assertSchema(asn1, this.className); - this.keyAttrId = asn1.result.keyAttrId.valueBlock.toString(); - if (KEY_ATTR in asn1.result) { - this.keyAttr = asn1.result.keyAttr; - } - } - toSchema() { - const outputArray = []; - outputArray.push(new ObjectIdentifier({ value: this.keyAttrId })); - if (KEY_ATTR in this) { - outputArray.push(this.keyAttr); - } - return (new Sequence({ - value: outputArray, - })); - } - toJSON() { - const res = { - keyAttrId: this.keyAttrId - }; - if (KEY_ATTR in this) { - res.keyAttr = this.keyAttr.toJSON(); - } - return res; - } -} +const KEY_ATTR_ID = "keyAttrId"; +const KEY_ATTR = "keyAttr"; +const CLEAR_PROPS$x = [ + KEY_ATTR_ID, + KEY_ATTR, +]; +class OtherKeyAttribute extends PkiObject { + constructor(parameters = {}) { + super(); + this.keyAttrId = getParametersValue(parameters, KEY_ATTR_ID, OtherKeyAttribute.defaultValues(KEY_ATTR_ID)); + if (KEY_ATTR in parameters) { + this.keyAttr = getParametersValue(parameters, KEY_ATTR, OtherKeyAttribute.defaultValues(KEY_ATTR)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case KEY_ATTR_ID: + return EMPTY_STRING; + case KEY_ATTR: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case KEY_ATTR_ID: + return (typeof memberValue === "string" && memberValue === EMPTY_STRING); + case KEY_ATTR: + return (Object.keys(memberValue).length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + optional: (names.optional || true), + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.keyAttrId || EMPTY_STRING) }), + new Any({ + optional: true, + name: (names.keyAttr || EMPTY_STRING) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$x); + const asn1 = compareSchema(schema, schema, OtherKeyAttribute.schema({ + names: { + keyAttrId: KEY_ATTR_ID, + keyAttr: KEY_ATTR + } + })); + AsnError.assertSchema(asn1, this.className); + this.keyAttrId = asn1.result.keyAttrId.valueBlock.toString(); + if (KEY_ATTR in asn1.result) { + this.keyAttr = asn1.result.keyAttr; + } + } + toSchema() { + const outputArray = []; + outputArray.push(new ObjectIdentifier({ value: this.keyAttrId })); + if (KEY_ATTR in this) { + outputArray.push(this.keyAttr); + } + return (new Sequence({ + value: outputArray, + })); + } + toJSON() { + const res = { + keyAttrId: this.keyAttrId + }; + if (KEY_ATTR in this) { + res.keyAttr = this.keyAttr.toJSON(); + } + return res; + } +} OtherKeyAttribute.CLASS_NAME = "OtherKeyAttribute"; -const SUBJECT_KEY_IDENTIFIER = "subjectKeyIdentifier"; -const DATE$1 = "date"; -const OTHER$1 = "other"; -const CLEAR_PROPS$w = [ - SUBJECT_KEY_IDENTIFIER, - DATE$1, - OTHER$1, -]; -class RecipientKeyIdentifier extends PkiObject { - constructor(parameters = {}) { - super(); - this.subjectKeyIdentifier = getParametersValue(parameters, SUBJECT_KEY_IDENTIFIER, RecipientKeyIdentifier.defaultValues(SUBJECT_KEY_IDENTIFIER)); - if (DATE$1 in parameters) { - this.date = getParametersValue(parameters, DATE$1, RecipientKeyIdentifier.defaultValues(DATE$1)); - } - if (OTHER$1 in parameters) { - this.other = getParametersValue(parameters, OTHER$1, RecipientKeyIdentifier.defaultValues(OTHER$1)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case SUBJECT_KEY_IDENTIFIER: - return new OctetString(); - case DATE$1: - return new GeneralizedTime(); - case OTHER$1: - return new OtherKeyAttribute(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case SUBJECT_KEY_IDENTIFIER: - return (memberValue.isEqual(RecipientKeyIdentifier.defaultValues(SUBJECT_KEY_IDENTIFIER))); - case DATE$1: - return ((memberValue.year === 0) && - (memberValue.month === 0) && - (memberValue.day === 0) && - (memberValue.hour === 0) && - (memberValue.minute === 0) && - (memberValue.second === 0) && - (memberValue.millisecond === 0)); - case OTHER$1: - return ((memberValue.keyAttrId === EMPTY_STRING) && (("keyAttr" in memberValue) === false)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new OctetString({ name: (names.subjectKeyIdentifier || EMPTY_STRING) }), - new GeneralizedTime({ - optional: true, - name: (names.date || EMPTY_STRING) - }), - OtherKeyAttribute.schema(names.other || {}) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$w); - const asn1 = compareSchema(schema, schema, RecipientKeyIdentifier.schema({ - names: { - subjectKeyIdentifier: SUBJECT_KEY_IDENTIFIER, - date: DATE$1, - other: { - names: { - blockName: OTHER$1 - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.subjectKeyIdentifier = asn1.result.subjectKeyIdentifier; - if (DATE$1 in asn1.result) - this.date = asn1.result.date; - if (OTHER$1 in asn1.result) - this.other = new OtherKeyAttribute({ schema: asn1.result.other }); - } - toSchema() { - const outputArray = []; - outputArray.push(this.subjectKeyIdentifier); - if (this.date) { - outputArray.push(this.date); - } - if (this.other) { - outputArray.push(this.other.toSchema()); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - subjectKeyIdentifier: this.subjectKeyIdentifier.toJSON() - }; - if (this.date) { - res.date = this.date.toJSON(); - } - if (this.other) { - res.other = this.other.toJSON(); - } - return res; - } -} +const SUBJECT_KEY_IDENTIFIER = "subjectKeyIdentifier"; +const DATE$1 = "date"; +const OTHER$1 = "other"; +const CLEAR_PROPS$w = [ + SUBJECT_KEY_IDENTIFIER, + DATE$1, + OTHER$1, +]; +class RecipientKeyIdentifier extends PkiObject { + constructor(parameters = {}) { + super(); + this.subjectKeyIdentifier = getParametersValue(parameters, SUBJECT_KEY_IDENTIFIER, RecipientKeyIdentifier.defaultValues(SUBJECT_KEY_IDENTIFIER)); + if (DATE$1 in parameters) { + this.date = getParametersValue(parameters, DATE$1, RecipientKeyIdentifier.defaultValues(DATE$1)); + } + if (OTHER$1 in parameters) { + this.other = getParametersValue(parameters, OTHER$1, RecipientKeyIdentifier.defaultValues(OTHER$1)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case SUBJECT_KEY_IDENTIFIER: + return new OctetString(); + case DATE$1: + return new GeneralizedTime(); + case OTHER$1: + return new OtherKeyAttribute(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case SUBJECT_KEY_IDENTIFIER: + return (memberValue.isEqual(RecipientKeyIdentifier.defaultValues(SUBJECT_KEY_IDENTIFIER))); + case DATE$1: + return ((memberValue.year === 0) && + (memberValue.month === 0) && + (memberValue.day === 0) && + (memberValue.hour === 0) && + (memberValue.minute === 0) && + (memberValue.second === 0) && + (memberValue.millisecond === 0)); + case OTHER$1: + return ((memberValue.keyAttrId === EMPTY_STRING) && (("keyAttr" in memberValue) === false)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new OctetString({ name: (names.subjectKeyIdentifier || EMPTY_STRING) }), + new GeneralizedTime({ + optional: true, + name: (names.date || EMPTY_STRING) + }), + OtherKeyAttribute.schema(names.other || {}) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$w); + const asn1 = compareSchema(schema, schema, RecipientKeyIdentifier.schema({ + names: { + subjectKeyIdentifier: SUBJECT_KEY_IDENTIFIER, + date: DATE$1, + other: { + names: { + blockName: OTHER$1 + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.subjectKeyIdentifier = asn1.result.subjectKeyIdentifier; + if (DATE$1 in asn1.result) + this.date = asn1.result.date; + if (OTHER$1 in asn1.result) + this.other = new OtherKeyAttribute({ schema: asn1.result.other }); + } + toSchema() { + const outputArray = []; + outputArray.push(this.subjectKeyIdentifier); + if (this.date) { + outputArray.push(this.date); + } + if (this.other) { + outputArray.push(this.other.toSchema()); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + subjectKeyIdentifier: this.subjectKeyIdentifier.toJSON() + }; + if (this.date) { + res.date = this.date.toJSON(); + } + if (this.other) { + res.other = this.other.toJSON(); + } + return res; + } +} RecipientKeyIdentifier.CLASS_NAME = "RecipientKeyIdentifier"; -const VARIANT$1 = "variant"; -const VALUE$1 = "value"; -const CLEAR_PROPS$v = [ - "blockName", -]; -class KeyAgreeRecipientIdentifier extends PkiObject { - constructor(parameters = {}) { - super(); - this.variant = getParametersValue(parameters, VARIANT$1, KeyAgreeRecipientIdentifier.defaultValues(VARIANT$1)); - this.value = getParametersValue(parameters, VALUE$1, KeyAgreeRecipientIdentifier.defaultValues(VALUE$1)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VARIANT$1: - return (-1); - case VALUE$1: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VARIANT$1: - return (memberValue === (-1)); - case VALUE$1: - return (Object.keys(memberValue).length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Choice({ - value: [ - IssuerAndSerialNumber.schema(names.issuerAndSerialNumber || { - names: { - blockName: (names.blockName || EMPTY_STRING) - } - }), - new Constructed({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: RecipientKeyIdentifier.schema(names.rKeyId || { - names: { - blockName: (names.blockName || EMPTY_STRING) - } - }).valueBlock.value - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$v); - const asn1 = compareSchema(schema, schema, KeyAgreeRecipientIdentifier.schema({ - names: { - blockName: "blockName" - } - })); - AsnError.assertSchema(asn1, this.className); - if (asn1.result.blockName.idBlock.tagClass === 1) { - this.variant = 1; - this.value = new IssuerAndSerialNumber({ schema: asn1.result.blockName }); - } - else { - this.variant = 2; - this.value = new RecipientKeyIdentifier({ - schema: new Sequence({ - value: asn1.result.blockName.valueBlock.value - }) - }); - } - } - toSchema() { - switch (this.variant) { - case 1: - return this.value.toSchema(); - case 2: - return new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.value.toSchema().valueBlock.value - }); - default: - return new Any(); - } - } - toJSON() { - const res = { - variant: this.variant, - }; - if ((this.variant === 1) || (this.variant === 2)) { - res.value = this.value.toJSON(); - } - return res; - } -} +const VARIANT$1 = "variant"; +const VALUE$1 = "value"; +const CLEAR_PROPS$v = [ + "blockName", +]; +class KeyAgreeRecipientIdentifier extends PkiObject { + constructor(parameters = {}) { + super(); + this.variant = getParametersValue(parameters, VARIANT$1, KeyAgreeRecipientIdentifier.defaultValues(VARIANT$1)); + this.value = getParametersValue(parameters, VALUE$1, KeyAgreeRecipientIdentifier.defaultValues(VALUE$1)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VARIANT$1: + return (-1); + case VALUE$1: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VARIANT$1: + return (memberValue === (-1)); + case VALUE$1: + return (Object.keys(memberValue).length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Choice({ + value: [ + IssuerAndSerialNumber.schema(names.issuerAndSerialNumber || { + names: { + blockName: (names.blockName || EMPTY_STRING) + } + }), + new Constructed({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: RecipientKeyIdentifier.schema(names.rKeyId || { + names: { + blockName: (names.blockName || EMPTY_STRING) + } + }).valueBlock.value + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$v); + const asn1 = compareSchema(schema, schema, KeyAgreeRecipientIdentifier.schema({ + names: { + blockName: "blockName" + } + })); + AsnError.assertSchema(asn1, this.className); + if (asn1.result.blockName.idBlock.tagClass === 1) { + this.variant = 1; + this.value = new IssuerAndSerialNumber({ schema: asn1.result.blockName }); + } + else { + this.variant = 2; + this.value = new RecipientKeyIdentifier({ + schema: new Sequence({ + value: asn1.result.blockName.valueBlock.value + }) + }); + } + } + toSchema() { + switch (this.variant) { + case 1: + return this.value.toSchema(); + case 2: + return new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.value.toSchema().valueBlock.value + }); + default: + return new Any(); + } + } + toJSON() { + const res = { + variant: this.variant, + }; + if ((this.variant === 1) || (this.variant === 2)) { + res.value = this.value.toJSON(); + } + return res; + } +} KeyAgreeRecipientIdentifier.CLASS_NAME = "KeyAgreeRecipientIdentifier"; -const RID = "rid"; -const ENCRYPTED_KEY$2 = "encryptedKey"; -const CLEAR_PROPS$u = [ - RID, - ENCRYPTED_KEY$2, -]; -class RecipientEncryptedKey extends PkiObject { - constructor(parameters = {}) { - super(); - this.rid = getParametersValue(parameters, RID, RecipientEncryptedKey.defaultValues(RID)); - this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY$2, RecipientEncryptedKey.defaultValues(ENCRYPTED_KEY$2)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case RID: - return new KeyAgreeRecipientIdentifier(); - case ENCRYPTED_KEY$2: - return new OctetString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case RID: - return ((memberValue.variant === (-1)) && (("value" in memberValue) === false)); - case ENCRYPTED_KEY$2: - return (memberValue.isEqual(RecipientEncryptedKey.defaultValues(ENCRYPTED_KEY$2))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - KeyAgreeRecipientIdentifier.schema(names.rid || {}), - new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$u); - const asn1 = compareSchema(schema, schema, RecipientEncryptedKey.schema({ - names: { - rid: { - names: { - blockName: RID - } - }, - encryptedKey: ENCRYPTED_KEY$2 - } - })); - AsnError.assertSchema(asn1, this.className); - this.rid = new KeyAgreeRecipientIdentifier({ schema: asn1.result.rid }); - this.encryptedKey = asn1.result.encryptedKey; - } - toSchema() { - return (new Sequence({ - value: [ - this.rid.toSchema(), - this.encryptedKey - ] - })); - } - toJSON() { - return { - rid: this.rid.toJSON(), - encryptedKey: this.encryptedKey.toJSON(), - }; - } -} +const RID = "rid"; +const ENCRYPTED_KEY$2 = "encryptedKey"; +const CLEAR_PROPS$u = [ + RID, + ENCRYPTED_KEY$2, +]; +class RecipientEncryptedKey extends PkiObject { + constructor(parameters = {}) { + super(); + this.rid = getParametersValue(parameters, RID, RecipientEncryptedKey.defaultValues(RID)); + this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY$2, RecipientEncryptedKey.defaultValues(ENCRYPTED_KEY$2)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case RID: + return new KeyAgreeRecipientIdentifier(); + case ENCRYPTED_KEY$2: + return new OctetString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case RID: + return ((memberValue.variant === (-1)) && (("value" in memberValue) === false)); + case ENCRYPTED_KEY$2: + return (memberValue.isEqual(RecipientEncryptedKey.defaultValues(ENCRYPTED_KEY$2))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + KeyAgreeRecipientIdentifier.schema(names.rid || {}), + new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$u); + const asn1 = compareSchema(schema, schema, RecipientEncryptedKey.schema({ + names: { + rid: { + names: { + blockName: RID + } + }, + encryptedKey: ENCRYPTED_KEY$2 + } + })); + AsnError.assertSchema(asn1, this.className); + this.rid = new KeyAgreeRecipientIdentifier({ schema: asn1.result.rid }); + this.encryptedKey = asn1.result.encryptedKey; + } + toSchema() { + return (new Sequence({ + value: [ + this.rid.toSchema(), + this.encryptedKey + ] + })); + } + toJSON() { + return { + rid: this.rid.toJSON(), + encryptedKey: this.encryptedKey.toJSON(), + }; + } +} RecipientEncryptedKey.CLASS_NAME = "RecipientEncryptedKey"; -const ENCRYPTED_KEYS = "encryptedKeys"; -const RECIPIENT_ENCRYPTED_KEYS = "RecipientEncryptedKeys"; -const CLEAR_PROPS$t = [ - RECIPIENT_ENCRYPTED_KEYS, -]; -class RecipientEncryptedKeys extends PkiObject { - constructor(parameters = {}) { - super(); - this.encryptedKeys = getParametersValue(parameters, ENCRYPTED_KEYS, RecipientEncryptedKeys.defaultValues(ENCRYPTED_KEYS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ENCRYPTED_KEYS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case ENCRYPTED_KEYS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.RecipientEncryptedKeys || EMPTY_STRING), - value: RecipientEncryptedKey.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$t); - const asn1 = compareSchema(schema, schema, RecipientEncryptedKeys.schema({ - names: { - RecipientEncryptedKeys: RECIPIENT_ENCRYPTED_KEYS - } - })); - AsnError.assertSchema(asn1, this.className); - this.encryptedKeys = Array.from(asn1.result.RecipientEncryptedKeys, element => new RecipientEncryptedKey({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.encryptedKeys, o => o.toSchema()) - })); - } - toJSON() { - return { - encryptedKeys: Array.from(this.encryptedKeys, o => o.toJSON()) - }; - } -} -RecipientEncryptedKeys.CLASS_NAME = "RecipientEncryptedKeys"; - -const VERSION$b = "version"; -const ORIGINATOR = "originator"; -const UKM = "ukm"; -const KEY_ENCRYPTION_ALGORITHM$2 = "keyEncryptionAlgorithm"; -const RECIPIENT_ENCRYPTED_KEY = "recipientEncryptedKeys"; -const RECIPIENT_CERTIFICATE = "recipientCertificate"; -const RECIPIENT_PUBLIC_KEY = "recipientPublicKey"; -const CLEAR_PROPS$s = [ - VERSION$b, - ORIGINATOR, - UKM, - KEY_ENCRYPTION_ALGORITHM$2, - RECIPIENT_ENCRYPTED_KEY, -]; -class KeyAgreeRecipientInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$b, KeyAgreeRecipientInfo.defaultValues(VERSION$b)); - this.originator = getParametersValue(parameters, ORIGINATOR, KeyAgreeRecipientInfo.defaultValues(ORIGINATOR)); - if (UKM in parameters) { - this.ukm = getParametersValue(parameters, UKM, KeyAgreeRecipientInfo.defaultValues(UKM)); - } - this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM$2, KeyAgreeRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM$2)); - this.recipientEncryptedKeys = getParametersValue(parameters, RECIPIENT_ENCRYPTED_KEY, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_ENCRYPTED_KEY)); - this.recipientCertificate = getParametersValue(parameters, RECIPIENT_CERTIFICATE, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_CERTIFICATE)); - this.recipientPublicKey = getParametersValue(parameters, RECIPIENT_PUBLIC_KEY, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_PUBLIC_KEY)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$b: - return 0; - case ORIGINATOR: - return new OriginatorIdentifierOrKey(); - case UKM: - return new OctetString(); - case KEY_ENCRYPTION_ALGORITHM$2: - return new AlgorithmIdentifier(); - case RECIPIENT_ENCRYPTED_KEY: - return new RecipientEncryptedKeys(); - case RECIPIENT_CERTIFICATE: - return new Certificate(); - case RECIPIENT_PUBLIC_KEY: - return null; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$b: - return (memberValue === 0); - case ORIGINATOR: - return ((memberValue.variant === (-1)) && (("value" in memberValue) === false)); - case UKM: - return (memberValue.isEqual(KeyAgreeRecipientInfo.defaultValues(UKM))); - case KEY_ENCRYPTION_ALGORITHM$2: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case RECIPIENT_ENCRYPTED_KEY: - return (memberValue.encryptedKeys.length === 0); - case RECIPIENT_CERTIFICATE: - return false; - case RECIPIENT_PUBLIC_KEY: - return false; - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: names.blockName || EMPTY_STRING, - value: [ - new Integer({ name: names.version || EMPTY_STRING }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - OriginatorIdentifierOrKey.schema(names.originator || {}) - ] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [new OctetString({ name: names.ukm || EMPTY_STRING })] - }), - AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), - RecipientEncryptedKeys.schema(names.recipientEncryptedKeys || {}) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$s); - const asn1 = compareSchema(schema, schema, KeyAgreeRecipientInfo.schema({ - names: { - version: VERSION$b, - originator: { - names: { - blockName: ORIGINATOR - } - }, - ukm: UKM, - keyEncryptionAlgorithm: { - names: { - blockName: KEY_ENCRYPTION_ALGORITHM$2 - } - }, - recipientEncryptedKeys: { - names: { - blockName: RECIPIENT_ENCRYPTED_KEY - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.originator = new OriginatorIdentifierOrKey({ schema: asn1.result.originator }); - if (UKM in asn1.result) - this.ukm = asn1.result.ukm; - this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); - this.recipientEncryptedKeys = new RecipientEncryptedKeys({ schema: asn1.result.recipientEncryptedKeys }); - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.originator.toSchema()] - })); - if (this.ukm) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [this.ukm] - })); - } - outputArray.push(this.keyEncryptionAlgorithm.toSchema()); - outputArray.push(this.recipientEncryptedKeys.toSchema()); - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - version: this.version, - originator: this.originator.toJSON(), - keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), - recipientEncryptedKeys: this.recipientEncryptedKeys.toJSON(), - }; - if (this.ukm) { - res.ukm = this.ukm.toJSON(); - } - return res; - } -} +const ENCRYPTED_KEYS = "encryptedKeys"; +const RECIPIENT_ENCRYPTED_KEYS = "RecipientEncryptedKeys"; +const CLEAR_PROPS$t = [ + RECIPIENT_ENCRYPTED_KEYS, +]; +class RecipientEncryptedKeys extends PkiObject { + constructor(parameters = {}) { + super(); + this.encryptedKeys = getParametersValue(parameters, ENCRYPTED_KEYS, RecipientEncryptedKeys.defaultValues(ENCRYPTED_KEYS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ENCRYPTED_KEYS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case ENCRYPTED_KEYS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.RecipientEncryptedKeys || EMPTY_STRING), + value: RecipientEncryptedKey.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$t); + const asn1 = compareSchema(schema, schema, RecipientEncryptedKeys.schema({ + names: { + RecipientEncryptedKeys: RECIPIENT_ENCRYPTED_KEYS + } + })); + AsnError.assertSchema(asn1, this.className); + this.encryptedKeys = Array.from(asn1.result.RecipientEncryptedKeys, element => new RecipientEncryptedKey({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.encryptedKeys, o => o.toSchema()) + })); + } + toJSON() { + return { + encryptedKeys: Array.from(this.encryptedKeys, o => o.toJSON()) + }; + } +} +RecipientEncryptedKeys.CLASS_NAME = "RecipientEncryptedKeys"; + +const VERSION$b = "version"; +const ORIGINATOR = "originator"; +const UKM = "ukm"; +const KEY_ENCRYPTION_ALGORITHM$2 = "keyEncryptionAlgorithm"; +const RECIPIENT_ENCRYPTED_KEY = "recipientEncryptedKeys"; +const RECIPIENT_CERTIFICATE = "recipientCertificate"; +const RECIPIENT_PUBLIC_KEY = "recipientPublicKey"; +const CLEAR_PROPS$s = [ + VERSION$b, + ORIGINATOR, + UKM, + KEY_ENCRYPTION_ALGORITHM$2, + RECIPIENT_ENCRYPTED_KEY, +]; +class KeyAgreeRecipientInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$b, KeyAgreeRecipientInfo.defaultValues(VERSION$b)); + this.originator = getParametersValue(parameters, ORIGINATOR, KeyAgreeRecipientInfo.defaultValues(ORIGINATOR)); + if (UKM in parameters) { + this.ukm = getParametersValue(parameters, UKM, KeyAgreeRecipientInfo.defaultValues(UKM)); + } + this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM$2, KeyAgreeRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM$2)); + this.recipientEncryptedKeys = getParametersValue(parameters, RECIPIENT_ENCRYPTED_KEY, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_ENCRYPTED_KEY)); + this.recipientCertificate = getParametersValue(parameters, RECIPIENT_CERTIFICATE, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_CERTIFICATE)); + this.recipientPublicKey = getParametersValue(parameters, RECIPIENT_PUBLIC_KEY, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_PUBLIC_KEY)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$b: + return 0; + case ORIGINATOR: + return new OriginatorIdentifierOrKey(); + case UKM: + return new OctetString(); + case KEY_ENCRYPTION_ALGORITHM$2: + return new AlgorithmIdentifier(); + case RECIPIENT_ENCRYPTED_KEY: + return new RecipientEncryptedKeys(); + case RECIPIENT_CERTIFICATE: + return new Certificate(); + case RECIPIENT_PUBLIC_KEY: + return null; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$b: + return (memberValue === 0); + case ORIGINATOR: + return ((memberValue.variant === (-1)) && (("value" in memberValue) === false)); + case UKM: + return (memberValue.isEqual(KeyAgreeRecipientInfo.defaultValues(UKM))); + case KEY_ENCRYPTION_ALGORITHM$2: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case RECIPIENT_ENCRYPTED_KEY: + return (memberValue.encryptedKeys.length === 0); + case RECIPIENT_CERTIFICATE: + return false; + case RECIPIENT_PUBLIC_KEY: + return false; + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: names.blockName || EMPTY_STRING, + value: [ + new Integer({ name: names.version || EMPTY_STRING }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + OriginatorIdentifierOrKey.schema(names.originator || {}) + ] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [new OctetString({ name: names.ukm || EMPTY_STRING })] + }), + AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), + RecipientEncryptedKeys.schema(names.recipientEncryptedKeys || {}) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$s); + const asn1 = compareSchema(schema, schema, KeyAgreeRecipientInfo.schema({ + names: { + version: VERSION$b, + originator: { + names: { + blockName: ORIGINATOR + } + }, + ukm: UKM, + keyEncryptionAlgorithm: { + names: { + blockName: KEY_ENCRYPTION_ALGORITHM$2 + } + }, + recipientEncryptedKeys: { + names: { + blockName: RECIPIENT_ENCRYPTED_KEY + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.originator = new OriginatorIdentifierOrKey({ schema: asn1.result.originator }); + if (UKM in asn1.result) + this.ukm = asn1.result.ukm; + this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); + this.recipientEncryptedKeys = new RecipientEncryptedKeys({ schema: asn1.result.recipientEncryptedKeys }); + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.originator.toSchema()] + })); + if (this.ukm) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [this.ukm] + })); + } + outputArray.push(this.keyEncryptionAlgorithm.toSchema()); + outputArray.push(this.recipientEncryptedKeys.toSchema()); + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + version: this.version, + originator: this.originator.toJSON(), + keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), + recipientEncryptedKeys: this.recipientEncryptedKeys.toJSON(), + }; + if (this.ukm) { + res.ukm = this.ukm.toJSON(); + } + return res; + } +} KeyAgreeRecipientInfo.CLASS_NAME = "KeyAgreeRecipientInfo"; -const KEY_IDENTIFIER = "keyIdentifier"; -const DATE = "date"; -const OTHER = "other"; -const CLEAR_PROPS$r = [ - KEY_IDENTIFIER, - DATE, - OTHER, -]; -class KEKIdentifier extends PkiObject { - constructor(parameters = {}) { - super(); - this.keyIdentifier = getParametersValue(parameters, KEY_IDENTIFIER, KEKIdentifier.defaultValues(KEY_IDENTIFIER)); - if (DATE in parameters) { - this.date = getParametersValue(parameters, DATE, KEKIdentifier.defaultValues(DATE)); - } - if (OTHER in parameters) { - this.other = getParametersValue(parameters, OTHER, KEKIdentifier.defaultValues(OTHER)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case KEY_IDENTIFIER: - return new OctetString(); - case DATE: - return new GeneralizedTime(); - case OTHER: - return new OtherKeyAttribute(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case KEY_IDENTIFIER: - return (memberValue.isEqual(KEKIdentifier.defaultValues(KEY_IDENTIFIER))); - case DATE: - return ((memberValue.year === 0) && - (memberValue.month === 0) && - (memberValue.day === 0) && - (memberValue.hour === 0) && - (memberValue.minute === 0) && - (memberValue.second === 0) && - (memberValue.millisecond === 0)); - case OTHER: - return ((memberValue.compareWithDefault("keyAttrId", memberValue.keyAttrId)) && - (("keyAttr" in memberValue) === false)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new OctetString({ name: (names.keyIdentifier || EMPTY_STRING) }), - new GeneralizedTime({ - optional: true, - name: (names.date || EMPTY_STRING) - }), - OtherKeyAttribute.schema(names.other || {}) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$r); - const asn1 = compareSchema(schema, schema, KEKIdentifier.schema({ - names: { - keyIdentifier: KEY_IDENTIFIER, - date: DATE, - other: { - names: { - blockName: OTHER - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.keyIdentifier = asn1.result.keyIdentifier; - if (DATE in asn1.result) - this.date = asn1.result.date; - if (OTHER in asn1.result) - this.other = new OtherKeyAttribute({ schema: asn1.result.other }); - } - toSchema() { - const outputArray = []; - outputArray.push(this.keyIdentifier); - if (this.date) { - outputArray.push(this.date); - } - if (this.other) { - outputArray.push(this.other.toSchema()); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - keyIdentifier: this.keyIdentifier.toJSON() - }; - if (this.date) { - res.date = this.date; - } - if (this.other) { - res.other = this.other.toJSON(); - } - return res; - } -} +const KEY_IDENTIFIER = "keyIdentifier"; +const DATE = "date"; +const OTHER = "other"; +const CLEAR_PROPS$r = [ + KEY_IDENTIFIER, + DATE, + OTHER, +]; +class KEKIdentifier extends PkiObject { + constructor(parameters = {}) { + super(); + this.keyIdentifier = getParametersValue(parameters, KEY_IDENTIFIER, KEKIdentifier.defaultValues(KEY_IDENTIFIER)); + if (DATE in parameters) { + this.date = getParametersValue(parameters, DATE, KEKIdentifier.defaultValues(DATE)); + } + if (OTHER in parameters) { + this.other = getParametersValue(parameters, OTHER, KEKIdentifier.defaultValues(OTHER)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case KEY_IDENTIFIER: + return new OctetString(); + case DATE: + return new GeneralizedTime(); + case OTHER: + return new OtherKeyAttribute(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case KEY_IDENTIFIER: + return (memberValue.isEqual(KEKIdentifier.defaultValues(KEY_IDENTIFIER))); + case DATE: + return ((memberValue.year === 0) && + (memberValue.month === 0) && + (memberValue.day === 0) && + (memberValue.hour === 0) && + (memberValue.minute === 0) && + (memberValue.second === 0) && + (memberValue.millisecond === 0)); + case OTHER: + return ((memberValue.compareWithDefault("keyAttrId", memberValue.keyAttrId)) && + (("keyAttr" in memberValue) === false)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new OctetString({ name: (names.keyIdentifier || EMPTY_STRING) }), + new GeneralizedTime({ + optional: true, + name: (names.date || EMPTY_STRING) + }), + OtherKeyAttribute.schema(names.other || {}) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$r); + const asn1 = compareSchema(schema, schema, KEKIdentifier.schema({ + names: { + keyIdentifier: KEY_IDENTIFIER, + date: DATE, + other: { + names: { + blockName: OTHER + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.keyIdentifier = asn1.result.keyIdentifier; + if (DATE in asn1.result) + this.date = asn1.result.date; + if (OTHER in asn1.result) + this.other = new OtherKeyAttribute({ schema: asn1.result.other }); + } + toSchema() { + const outputArray = []; + outputArray.push(this.keyIdentifier); + if (this.date) { + outputArray.push(this.date); + } + if (this.other) { + outputArray.push(this.other.toSchema()); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + keyIdentifier: this.keyIdentifier.toJSON() + }; + if (this.date) { + res.date = this.date; + } + if (this.other) { + res.other = this.other.toJSON(); + } + return res; + } +} KEKIdentifier.CLASS_NAME = "KEKIdentifier"; -const VERSION$a = "version"; -const KEK_ID = "kekid"; -const KEY_ENCRYPTION_ALGORITHM$1 = "keyEncryptionAlgorithm"; -const ENCRYPTED_KEY$1 = "encryptedKey"; -const PER_DEFINED_KEK = "preDefinedKEK"; -const CLEAR_PROPS$q = [ - VERSION$a, - KEK_ID, - KEY_ENCRYPTION_ALGORITHM$1, - ENCRYPTED_KEY$1, -]; -class KEKRecipientInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$a, KEKRecipientInfo.defaultValues(VERSION$a)); - this.kekid = getParametersValue(parameters, KEK_ID, KEKRecipientInfo.defaultValues(KEK_ID)); - this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM$1, KEKRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM$1)); - this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY$1, KEKRecipientInfo.defaultValues(ENCRYPTED_KEY$1)); - this.preDefinedKEK = getParametersValue(parameters, PER_DEFINED_KEK, KEKRecipientInfo.defaultValues(PER_DEFINED_KEK)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$a: - return 0; - case KEK_ID: - return new KEKIdentifier(); - case KEY_ENCRYPTION_ALGORITHM$1: - return new AlgorithmIdentifier(); - case ENCRYPTED_KEY$1: - return new OctetString(); - case PER_DEFINED_KEK: - return EMPTY_BUFFER; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case "KEKRecipientInfo": - return (memberValue === KEKRecipientInfo.defaultValues(VERSION$a)); - case KEK_ID: - return ((memberValue.compareWithDefault("keyIdentifier", memberValue.keyIdentifier)) && - (("date" in memberValue) === false) && - (("other" in memberValue) === false)); - case KEY_ENCRYPTION_ALGORITHM$1: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case ENCRYPTED_KEY$1: - return (memberValue.isEqual(KEKRecipientInfo.defaultValues(ENCRYPTED_KEY$1))); - case PER_DEFINED_KEK: - return (memberValue.byteLength === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - KEKIdentifier.schema(names.kekid || {}), - AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), - new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$q); - const asn1 = compareSchema(schema, schema, KEKRecipientInfo.schema({ - names: { - version: VERSION$a, - kekid: { - names: { - blockName: KEK_ID - } - }, - keyEncryptionAlgorithm: { - names: { - blockName: KEY_ENCRYPTION_ALGORITHM$1 - } - }, - encryptedKey: ENCRYPTED_KEY$1 - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.kekid = new KEKIdentifier({ schema: asn1.result.kekid }); - this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); - this.encryptedKey = asn1.result.encryptedKey; - } - toSchema() { - return (new Sequence({ - value: [ - new Integer({ value: this.version }), - this.kekid.toSchema(), - this.keyEncryptionAlgorithm.toSchema(), - this.encryptedKey - ] - })); - } - toJSON() { - return { - version: this.version, - kekid: this.kekid.toJSON(), - keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), - encryptedKey: this.encryptedKey.toJSON(), - }; - } -} +const VERSION$a = "version"; +const KEK_ID = "kekid"; +const KEY_ENCRYPTION_ALGORITHM$1 = "keyEncryptionAlgorithm"; +const ENCRYPTED_KEY$1 = "encryptedKey"; +const PER_DEFINED_KEK = "preDefinedKEK"; +const CLEAR_PROPS$q = [ + VERSION$a, + KEK_ID, + KEY_ENCRYPTION_ALGORITHM$1, + ENCRYPTED_KEY$1, +]; +class KEKRecipientInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$a, KEKRecipientInfo.defaultValues(VERSION$a)); + this.kekid = getParametersValue(parameters, KEK_ID, KEKRecipientInfo.defaultValues(KEK_ID)); + this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM$1, KEKRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM$1)); + this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY$1, KEKRecipientInfo.defaultValues(ENCRYPTED_KEY$1)); + this.preDefinedKEK = getParametersValue(parameters, PER_DEFINED_KEK, KEKRecipientInfo.defaultValues(PER_DEFINED_KEK)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$a: + return 0; + case KEK_ID: + return new KEKIdentifier(); + case KEY_ENCRYPTION_ALGORITHM$1: + return new AlgorithmIdentifier(); + case ENCRYPTED_KEY$1: + return new OctetString(); + case PER_DEFINED_KEK: + return EMPTY_BUFFER; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case "KEKRecipientInfo": + return (memberValue === KEKRecipientInfo.defaultValues(VERSION$a)); + case KEK_ID: + return ((memberValue.compareWithDefault("keyIdentifier", memberValue.keyIdentifier)) && + (("date" in memberValue) === false) && + (("other" in memberValue) === false)); + case KEY_ENCRYPTION_ALGORITHM$1: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case ENCRYPTED_KEY$1: + return (memberValue.isEqual(KEKRecipientInfo.defaultValues(ENCRYPTED_KEY$1))); + case PER_DEFINED_KEK: + return (memberValue.byteLength === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + KEKIdentifier.schema(names.kekid || {}), + AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), + new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$q); + const asn1 = compareSchema(schema, schema, KEKRecipientInfo.schema({ + names: { + version: VERSION$a, + kekid: { + names: { + blockName: KEK_ID + } + }, + keyEncryptionAlgorithm: { + names: { + blockName: KEY_ENCRYPTION_ALGORITHM$1 + } + }, + encryptedKey: ENCRYPTED_KEY$1 + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.kekid = new KEKIdentifier({ schema: asn1.result.kekid }); + this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); + this.encryptedKey = asn1.result.encryptedKey; + } + toSchema() { + return (new Sequence({ + value: [ + new Integer({ value: this.version }), + this.kekid.toSchema(), + this.keyEncryptionAlgorithm.toSchema(), + this.encryptedKey + ] + })); + } + toJSON() { + return { + version: this.version, + kekid: this.kekid.toJSON(), + keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), + encryptedKey: this.encryptedKey.toJSON(), + }; + } +} KEKRecipientInfo.CLASS_NAME = "KEKRecipientInfo"; -const VERSION$9 = "version"; -const KEY_DERIVATION_ALGORITHM = "keyDerivationAlgorithm"; -const KEY_ENCRYPTION_ALGORITHM = "keyEncryptionAlgorithm"; -const ENCRYPTED_KEY = "encryptedKey"; -const PASSWORD = "password"; -const CLEAR_PROPS$p = [ - VERSION$9, - KEY_DERIVATION_ALGORITHM, - KEY_ENCRYPTION_ALGORITHM, - ENCRYPTED_KEY -]; -class PasswordRecipientinfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$9, PasswordRecipientinfo.defaultValues(VERSION$9)); - if (KEY_DERIVATION_ALGORITHM in parameters) { - this.keyDerivationAlgorithm = getParametersValue(parameters, KEY_DERIVATION_ALGORITHM, PasswordRecipientinfo.defaultValues(KEY_DERIVATION_ALGORITHM)); - } - this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM, PasswordRecipientinfo.defaultValues(KEY_ENCRYPTION_ALGORITHM)); - this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY, PasswordRecipientinfo.defaultValues(ENCRYPTED_KEY)); - this.password = getParametersValue(parameters, PASSWORD, PasswordRecipientinfo.defaultValues(PASSWORD)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$9: - return (-1); - case KEY_DERIVATION_ALGORITHM: - return new AlgorithmIdentifier(); - case KEY_ENCRYPTION_ALGORITHM: - return new AlgorithmIdentifier(); - case ENCRYPTED_KEY: - return new OctetString(); - case PASSWORD: - return EMPTY_BUFFER; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$9: - return (memberValue === (-1)); - case KEY_DERIVATION_ALGORITHM: - case KEY_ENCRYPTION_ALGORITHM: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case ENCRYPTED_KEY: - return (memberValue.isEqual(PasswordRecipientinfo.defaultValues(ENCRYPTED_KEY))); - case PASSWORD: - return (memberValue.byteLength === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - new Constructed({ - name: (names.keyDerivationAlgorithm || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: AlgorithmIdentifier.schema().valueBlock.value - }), - AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), - new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$p); - const asn1 = compareSchema(schema, schema, PasswordRecipientinfo.schema({ - names: { - version: VERSION$9, - keyDerivationAlgorithm: KEY_DERIVATION_ALGORITHM, - keyEncryptionAlgorithm: { - names: { - blockName: KEY_ENCRYPTION_ALGORITHM - } - }, - encryptedKey: ENCRYPTED_KEY - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - if (KEY_DERIVATION_ALGORITHM in asn1.result) { - this.keyDerivationAlgorithm = new AlgorithmIdentifier({ - schema: new Sequence({ - value: asn1.result.keyDerivationAlgorithm.valueBlock.value - }) - }); - } - this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); - this.encryptedKey = asn1.result.encryptedKey; - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - if (this.keyDerivationAlgorithm) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.keyDerivationAlgorithm.toSchema().valueBlock.value - })); - } - outputArray.push(this.keyEncryptionAlgorithm.toSchema()); - outputArray.push(this.encryptedKey); - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - version: this.version, - keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), - encryptedKey: this.encryptedKey.toJSON(), - }; - if (this.keyDerivationAlgorithm) { - res.keyDerivationAlgorithm = this.keyDerivationAlgorithm.toJSON(); - } - return res; - } -} +const VERSION$9 = "version"; +const KEY_DERIVATION_ALGORITHM = "keyDerivationAlgorithm"; +const KEY_ENCRYPTION_ALGORITHM = "keyEncryptionAlgorithm"; +const ENCRYPTED_KEY = "encryptedKey"; +const PASSWORD = "password"; +const CLEAR_PROPS$p = [ + VERSION$9, + KEY_DERIVATION_ALGORITHM, + KEY_ENCRYPTION_ALGORITHM, + ENCRYPTED_KEY +]; +class PasswordRecipientinfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$9, PasswordRecipientinfo.defaultValues(VERSION$9)); + if (KEY_DERIVATION_ALGORITHM in parameters) { + this.keyDerivationAlgorithm = getParametersValue(parameters, KEY_DERIVATION_ALGORITHM, PasswordRecipientinfo.defaultValues(KEY_DERIVATION_ALGORITHM)); + } + this.keyEncryptionAlgorithm = getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM, PasswordRecipientinfo.defaultValues(KEY_ENCRYPTION_ALGORITHM)); + this.encryptedKey = getParametersValue(parameters, ENCRYPTED_KEY, PasswordRecipientinfo.defaultValues(ENCRYPTED_KEY)); + this.password = getParametersValue(parameters, PASSWORD, PasswordRecipientinfo.defaultValues(PASSWORD)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$9: + return (-1); + case KEY_DERIVATION_ALGORITHM: + return new AlgorithmIdentifier(); + case KEY_ENCRYPTION_ALGORITHM: + return new AlgorithmIdentifier(); + case ENCRYPTED_KEY: + return new OctetString(); + case PASSWORD: + return EMPTY_BUFFER; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$9: + return (memberValue === (-1)); + case KEY_DERIVATION_ALGORITHM: + case KEY_ENCRYPTION_ALGORITHM: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case ENCRYPTED_KEY: + return (memberValue.isEqual(PasswordRecipientinfo.defaultValues(ENCRYPTED_KEY))); + case PASSWORD: + return (memberValue.byteLength === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + new Constructed({ + name: (names.keyDerivationAlgorithm || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: AlgorithmIdentifier.schema().valueBlock.value + }), + AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}), + new OctetString({ name: (names.encryptedKey || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$p); + const asn1 = compareSchema(schema, schema, PasswordRecipientinfo.schema({ + names: { + version: VERSION$9, + keyDerivationAlgorithm: KEY_DERIVATION_ALGORITHM, + keyEncryptionAlgorithm: { + names: { + blockName: KEY_ENCRYPTION_ALGORITHM + } + }, + encryptedKey: ENCRYPTED_KEY + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + if (KEY_DERIVATION_ALGORITHM in asn1.result) { + this.keyDerivationAlgorithm = new AlgorithmIdentifier({ + schema: new Sequence({ + value: asn1.result.keyDerivationAlgorithm.valueBlock.value + }) + }); + } + this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm }); + this.encryptedKey = asn1.result.encryptedKey; + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + if (this.keyDerivationAlgorithm) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.keyDerivationAlgorithm.toSchema().valueBlock.value + })); + } + outputArray.push(this.keyEncryptionAlgorithm.toSchema()); + outputArray.push(this.encryptedKey); + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + version: this.version, + keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(), + encryptedKey: this.encryptedKey.toJSON(), + }; + if (this.keyDerivationAlgorithm) { + res.keyDerivationAlgorithm = this.keyDerivationAlgorithm.toJSON(); + } + return res; + } +} PasswordRecipientinfo.CLASS_NAME = "PasswordRecipientInfo"; -const ORI_TYPE = "oriType"; -const ORI_VALUE = "oriValue"; -const CLEAR_PROPS$o = [ - ORI_TYPE, - ORI_VALUE -]; -class OtherRecipientInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.oriType = getParametersValue(parameters, ORI_TYPE, OtherRecipientInfo.defaultValues(ORI_TYPE)); - this.oriValue = getParametersValue(parameters, ORI_VALUE, OtherRecipientInfo.defaultValues(ORI_VALUE)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case ORI_TYPE: - return EMPTY_STRING; - case ORI_VALUE: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case ORI_TYPE: - return (memberValue === EMPTY_STRING); - case ORI_VALUE: - return (Object.keys(memberValue).length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.oriType || EMPTY_STRING) }), - new Any({ name: (names.oriValue || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$o); - const asn1 = compareSchema(schema, schema, OtherRecipientInfo.schema({ - names: { - oriType: ORI_TYPE, - oriValue: ORI_VALUE - } - })); - AsnError.assertSchema(asn1, this.className); - this.oriType = asn1.result.oriType.valueBlock.toString(); - this.oriValue = asn1.result.oriValue; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.oriType }), - this.oriValue - ] - })); - } - toJSON() { - const res = { - oriType: this.oriType - }; - if (!OtherRecipientInfo.compareWithDefault(ORI_VALUE, this.oriValue)) { - res.oriValue = this.oriValue.toJSON(); - } - return res; - } -} +const ORI_TYPE = "oriType"; +const ORI_VALUE = "oriValue"; +const CLEAR_PROPS$o = [ + ORI_TYPE, + ORI_VALUE +]; +class OtherRecipientInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.oriType = getParametersValue(parameters, ORI_TYPE, OtherRecipientInfo.defaultValues(ORI_TYPE)); + this.oriValue = getParametersValue(parameters, ORI_VALUE, OtherRecipientInfo.defaultValues(ORI_VALUE)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case ORI_TYPE: + return EMPTY_STRING; + case ORI_VALUE: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case ORI_TYPE: + return (memberValue === EMPTY_STRING); + case ORI_VALUE: + return (Object.keys(memberValue).length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.oriType || EMPTY_STRING) }), + new Any({ name: (names.oriValue || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$o); + const asn1 = compareSchema(schema, schema, OtherRecipientInfo.schema({ + names: { + oriType: ORI_TYPE, + oriValue: ORI_VALUE + } + })); + AsnError.assertSchema(asn1, this.className); + this.oriType = asn1.result.oriType.valueBlock.toString(); + this.oriValue = asn1.result.oriValue; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.oriType }), + this.oriValue + ] + })); + } + toJSON() { + const res = { + oriType: this.oriType + }; + if (!OtherRecipientInfo.compareWithDefault(ORI_VALUE, this.oriValue)) { + res.oriValue = this.oriValue.toJSON(); + } + return res; + } +} OtherRecipientInfo.CLASS_NAME = "OtherRecipientInfo"; -const VARIANT = "variant"; -const VALUE = "value"; -const CLEAR_PROPS$n = [ - "blockName" -]; -class RecipientInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.variant = getParametersValue(parameters, VARIANT, RecipientInfo.defaultValues(VARIANT)); - if (VALUE in parameters) { - this.value = getParametersValue(parameters, VALUE, RecipientInfo.defaultValues(VALUE)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VARIANT: - return (-1); - case VALUE: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VARIANT: - return (memberValue === RecipientInfo.defaultValues(memberName)); - case VALUE: - return (Object.keys(memberValue).length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Choice({ - value: [ - KeyTransRecipientInfo.schema({ - names: { - blockName: (names.blockName || EMPTY_STRING) - } - }), - new Constructed({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: KeyAgreeRecipientInfo.schema().valueBlock.value - }), - new Constructed({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: KEKRecipientInfo.schema().valueBlock.value - }), - new Constructed({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 3 - }, - value: PasswordRecipientinfo.schema().valueBlock.value - }), - new Constructed({ - name: (names.blockName || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 4 - }, - value: OtherRecipientInfo.schema().valueBlock.value - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$n); - const asn1 = compareSchema(schema, schema, RecipientInfo.schema({ - names: { - blockName: "blockName" - } - })); - AsnError.assertSchema(asn1, this.className); - if (asn1.result.blockName.idBlock.tagClass === 1) { - this.variant = 1; - this.value = new KeyTransRecipientInfo({ schema: asn1.result.blockName }); - } - else { - const blockSequence = new Sequence({ - value: asn1.result.blockName.valueBlock.value - }); - switch (asn1.result.blockName.idBlock.tagNumber) { - case 1: - this.variant = 2; - this.value = new KeyAgreeRecipientInfo({ schema: blockSequence }); - break; - case 2: - this.variant = 3; - this.value = new KEKRecipientInfo({ schema: blockSequence }); - break; - case 3: - this.variant = 4; - this.value = new PasswordRecipientinfo({ schema: blockSequence }); - break; - case 4: - this.variant = 5; - this.value = new OtherRecipientInfo({ schema: blockSequence }); - break; - default: - throw new Error("Incorrect structure of RecipientInfo block"); - } - } - } - toSchema() { - ParameterError.assertEmpty(this.value, "value", "RecipientInfo"); - const _schema = this.value.toSchema(); - switch (this.variant) { - case 1: - return _schema; - case 2: - case 3: - case 4: - _schema.idBlock.tagClass = 3; - _schema.idBlock.tagNumber = (this.variant - 1); - return _schema; - default: - return new Any(); - } - } - toJSON() { - const res = { - variant: this.variant - }; - if (this.value && (this.variant >= 1) && (this.variant <= 4)) { - res.value = this.value.toJSON(); - } - return res; - } -} +const VARIANT = "variant"; +const VALUE = "value"; +const CLEAR_PROPS$n = [ + "blockName" +]; +class RecipientInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.variant = getParametersValue(parameters, VARIANT, RecipientInfo.defaultValues(VARIANT)); + if (VALUE in parameters) { + this.value = getParametersValue(parameters, VALUE, RecipientInfo.defaultValues(VALUE)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VARIANT: + return (-1); + case VALUE: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VARIANT: + return (memberValue === RecipientInfo.defaultValues(memberName)); + case VALUE: + return (Object.keys(memberValue).length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Choice({ + value: [ + KeyTransRecipientInfo.schema({ + names: { + blockName: (names.blockName || EMPTY_STRING) + } + }), + new Constructed({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: KeyAgreeRecipientInfo.schema().valueBlock.value + }), + new Constructed({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: KEKRecipientInfo.schema().valueBlock.value + }), + new Constructed({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 3 + }, + value: PasswordRecipientinfo.schema().valueBlock.value + }), + new Constructed({ + name: (names.blockName || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 4 + }, + value: OtherRecipientInfo.schema().valueBlock.value + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$n); + const asn1 = compareSchema(schema, schema, RecipientInfo.schema({ + names: { + blockName: "blockName" + } + })); + AsnError.assertSchema(asn1, this.className); + if (asn1.result.blockName.idBlock.tagClass === 1) { + this.variant = 1; + this.value = new KeyTransRecipientInfo({ schema: asn1.result.blockName }); + } + else { + const blockSequence = new Sequence({ + value: asn1.result.blockName.valueBlock.value + }); + switch (asn1.result.blockName.idBlock.tagNumber) { + case 1: + this.variant = 2; + this.value = new KeyAgreeRecipientInfo({ schema: blockSequence }); + break; + case 2: + this.variant = 3; + this.value = new KEKRecipientInfo({ schema: blockSequence }); + break; + case 3: + this.variant = 4; + this.value = new PasswordRecipientinfo({ schema: blockSequence }); + break; + case 4: + this.variant = 5; + this.value = new OtherRecipientInfo({ schema: blockSequence }); + break; + default: + throw new Error("Incorrect structure of RecipientInfo block"); + } + } + } + toSchema() { + ParameterError.assertEmpty(this.value, "value", "RecipientInfo"); + const _schema = this.value.toSchema(); + switch (this.variant) { + case 1: + return _schema; + case 2: + case 3: + case 4: + _schema.idBlock.tagClass = 3; + _schema.idBlock.tagNumber = (this.variant - 1); + return _schema; + default: + return new Any(); + } + } + toJSON() { + const res = { + variant: this.variant + }; + if (this.value && (this.variant >= 1) && (this.variant <= 4)) { + res.value = this.value.toJSON(); + } + return res; + } +} RecipientInfo.CLASS_NAME = "RecipientInfo"; -const HASH_ALGORITHM$2 = "hashAlgorithm"; -const MASK_GEN_ALGORITHM = "maskGenAlgorithm"; -const P_SOURCE_ALGORITHM = "pSourceAlgorithm"; -const CLEAR_PROPS$m = [ - HASH_ALGORITHM$2, - MASK_GEN_ALGORITHM, - P_SOURCE_ALGORITHM -]; -class RSAESOAEPParams extends PkiObject { - constructor(parameters = {}) { - super(); - this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$2, RSAESOAEPParams.defaultValues(HASH_ALGORITHM$2)); - this.maskGenAlgorithm = getParametersValue(parameters, MASK_GEN_ALGORITHM, RSAESOAEPParams.defaultValues(MASK_GEN_ALGORITHM)); - this.pSourceAlgorithm = getParametersValue(parameters, P_SOURCE_ALGORITHM, RSAESOAEPParams.defaultValues(P_SOURCE_ALGORITHM)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case HASH_ALGORITHM$2: - return new AlgorithmIdentifier({ - algorithmId: "1.3.14.3.2.26", - algorithmParams: new Null() - }); - case MASK_GEN_ALGORITHM: - return new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.1.8", - algorithmParams: (new AlgorithmIdentifier({ - algorithmId: "1.3.14.3.2.26", - algorithmParams: new Null() - })).toSchema() - }); - case P_SOURCE_ALGORITHM: - return new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.1.9", - algorithmParams: new OctetString({ valueHex: (new Uint8Array([0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09])).buffer }) - }); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - optional: true, - value: [AlgorithmIdentifier.schema(names.hashAlgorithm || {})] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - optional: true, - value: [AlgorithmIdentifier.schema(names.maskGenAlgorithm || {})] - }), - new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - optional: true, - value: [AlgorithmIdentifier.schema(names.pSourceAlgorithm || {})] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$m); - const asn1 = compareSchema(schema, schema, RSAESOAEPParams.schema({ - names: { - hashAlgorithm: { - names: { - blockName: HASH_ALGORITHM$2 - } - }, - maskGenAlgorithm: { - names: { - blockName: MASK_GEN_ALGORITHM - } - }, - pSourceAlgorithm: { - names: { - blockName: P_SOURCE_ALGORITHM - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - if (HASH_ALGORITHM$2 in asn1.result) - this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); - if (MASK_GEN_ALGORITHM in asn1.result) - this.maskGenAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.maskGenAlgorithm }); - if (P_SOURCE_ALGORITHM in asn1.result) - this.pSourceAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.pSourceAlgorithm }); - } - toSchema() { - const outputArray = []; - if (!this.hashAlgorithm.isEqual(RSAESOAEPParams.defaultValues(HASH_ALGORITHM$2))) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.hashAlgorithm.toSchema()] - })); - } - if (!this.maskGenAlgorithm.isEqual(RSAESOAEPParams.defaultValues(MASK_GEN_ALGORITHM))) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [this.maskGenAlgorithm.toSchema()] - })); - } - if (!this.pSourceAlgorithm.isEqual(RSAESOAEPParams.defaultValues(P_SOURCE_ALGORITHM))) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [this.pSourceAlgorithm.toSchema()] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = {}; - if (!this.hashAlgorithm.isEqual(RSAESOAEPParams.defaultValues(HASH_ALGORITHM$2))) { - res.hashAlgorithm = this.hashAlgorithm.toJSON(); - } - if (!this.maskGenAlgorithm.isEqual(RSAESOAEPParams.defaultValues(MASK_GEN_ALGORITHM))) { - res.maskGenAlgorithm = this.maskGenAlgorithm.toJSON(); - } - if (!this.pSourceAlgorithm.isEqual(RSAESOAEPParams.defaultValues(P_SOURCE_ALGORITHM))) { - res.pSourceAlgorithm = this.pSourceAlgorithm.toJSON(); - } - return res; - } -} +const HASH_ALGORITHM$2 = "hashAlgorithm"; +const MASK_GEN_ALGORITHM = "maskGenAlgorithm"; +const P_SOURCE_ALGORITHM = "pSourceAlgorithm"; +const CLEAR_PROPS$m = [ + HASH_ALGORITHM$2, + MASK_GEN_ALGORITHM, + P_SOURCE_ALGORITHM +]; +class RSAESOAEPParams extends PkiObject { + constructor(parameters = {}) { + super(); + this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$2, RSAESOAEPParams.defaultValues(HASH_ALGORITHM$2)); + this.maskGenAlgorithm = getParametersValue(parameters, MASK_GEN_ALGORITHM, RSAESOAEPParams.defaultValues(MASK_GEN_ALGORITHM)); + this.pSourceAlgorithm = getParametersValue(parameters, P_SOURCE_ALGORITHM, RSAESOAEPParams.defaultValues(P_SOURCE_ALGORITHM)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case HASH_ALGORITHM$2: + return new AlgorithmIdentifier({ + algorithmId: "1.3.14.3.2.26", + algorithmParams: new Null() + }); + case MASK_GEN_ALGORITHM: + return new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.1.8", + algorithmParams: (new AlgorithmIdentifier({ + algorithmId: "1.3.14.3.2.26", + algorithmParams: new Null() + })).toSchema() + }); + case P_SOURCE_ALGORITHM: + return new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.1.9", + algorithmParams: new OctetString({ valueHex: (new Uint8Array([0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09])).buffer }) + }); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + optional: true, + value: [AlgorithmIdentifier.schema(names.hashAlgorithm || {})] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + optional: true, + value: [AlgorithmIdentifier.schema(names.maskGenAlgorithm || {})] + }), + new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + optional: true, + value: [AlgorithmIdentifier.schema(names.pSourceAlgorithm || {})] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$m); + const asn1 = compareSchema(schema, schema, RSAESOAEPParams.schema({ + names: { + hashAlgorithm: { + names: { + blockName: HASH_ALGORITHM$2 + } + }, + maskGenAlgorithm: { + names: { + blockName: MASK_GEN_ALGORITHM + } + }, + pSourceAlgorithm: { + names: { + blockName: P_SOURCE_ALGORITHM + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + if (HASH_ALGORITHM$2 in asn1.result) + this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); + if (MASK_GEN_ALGORITHM in asn1.result) + this.maskGenAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.maskGenAlgorithm }); + if (P_SOURCE_ALGORITHM in asn1.result) + this.pSourceAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.pSourceAlgorithm }); + } + toSchema() { + const outputArray = []; + if (!this.hashAlgorithm.isEqual(RSAESOAEPParams.defaultValues(HASH_ALGORITHM$2))) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.hashAlgorithm.toSchema()] + })); + } + if (!this.maskGenAlgorithm.isEqual(RSAESOAEPParams.defaultValues(MASK_GEN_ALGORITHM))) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [this.maskGenAlgorithm.toSchema()] + })); + } + if (!this.pSourceAlgorithm.isEqual(RSAESOAEPParams.defaultValues(P_SOURCE_ALGORITHM))) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [this.pSourceAlgorithm.toSchema()] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = {}; + if (!this.hashAlgorithm.isEqual(RSAESOAEPParams.defaultValues(HASH_ALGORITHM$2))) { + res.hashAlgorithm = this.hashAlgorithm.toJSON(); + } + if (!this.maskGenAlgorithm.isEqual(RSAESOAEPParams.defaultValues(MASK_GEN_ALGORITHM))) { + res.maskGenAlgorithm = this.maskGenAlgorithm.toJSON(); + } + if (!this.pSourceAlgorithm.isEqual(RSAESOAEPParams.defaultValues(P_SOURCE_ALGORITHM))) { + res.pSourceAlgorithm = this.pSourceAlgorithm.toJSON(); + } + return res; + } +} RSAESOAEPParams.CLASS_NAME = "RSAESOAEPParams"; -const KEY_INFO = "keyInfo"; -const ENTITY_U_INFO = "entityUInfo"; -const SUPP_PUB_INFO = "suppPubInfo"; -const CLEAR_PROPS$l = [ - KEY_INFO, - ENTITY_U_INFO, - SUPP_PUB_INFO -]; -class ECCCMSSharedInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.keyInfo = getParametersValue(parameters, KEY_INFO, ECCCMSSharedInfo.defaultValues(KEY_INFO)); - if (ENTITY_U_INFO in parameters) { - this.entityUInfo = getParametersValue(parameters, ENTITY_U_INFO, ECCCMSSharedInfo.defaultValues(ENTITY_U_INFO)); - } - this.suppPubInfo = getParametersValue(parameters, SUPP_PUB_INFO, ECCCMSSharedInfo.defaultValues(SUPP_PUB_INFO)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case KEY_INFO: - return new AlgorithmIdentifier(); - case ENTITY_U_INFO: - return new OctetString(); - case SUPP_PUB_INFO: - return new OctetString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case KEY_INFO: - case ENTITY_U_INFO: - case SUPP_PUB_INFO: - return (memberValue.isEqual(ECCCMSSharedInfo.defaultValues(memberName))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.keyInfo || {}), - new Constructed({ - name: (names.entityUInfo || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - optional: true, - value: [new OctetString()] - }), - new Constructed({ - name: (names.suppPubInfo || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [new OctetString()] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$l); - const asn1 = compareSchema(schema, schema, ECCCMSSharedInfo.schema({ - names: { - keyInfo: { - names: { - blockName: KEY_INFO - } - }, - entityUInfo: ENTITY_U_INFO, - suppPubInfo: SUPP_PUB_INFO - } - })); - AsnError.assertSchema(asn1, this.className); - this.keyInfo = new AlgorithmIdentifier({ schema: asn1.result.keyInfo }); - if (ENTITY_U_INFO in asn1.result) - this.entityUInfo = asn1.result.entityUInfo.valueBlock.value[0]; - this.suppPubInfo = asn1.result.suppPubInfo.valueBlock.value[0]; - } - toSchema() { - const outputArray = []; - outputArray.push(this.keyInfo.toSchema()); - if (this.entityUInfo) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.entityUInfo] - })); - } - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [this.suppPubInfo] - })); - return new Sequence({ - value: outputArray - }); - } - toJSON() { - const res = { - keyInfo: this.keyInfo.toJSON(), - suppPubInfo: this.suppPubInfo.toJSON(), - }; - if (this.entityUInfo) { - res.entityUInfo = this.entityUInfo.toJSON(); - } - return res; - } -} +const KEY_INFO = "keyInfo"; +const ENTITY_U_INFO = "entityUInfo"; +const SUPP_PUB_INFO = "suppPubInfo"; +const CLEAR_PROPS$l = [ + KEY_INFO, + ENTITY_U_INFO, + SUPP_PUB_INFO +]; +class ECCCMSSharedInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.keyInfo = getParametersValue(parameters, KEY_INFO, ECCCMSSharedInfo.defaultValues(KEY_INFO)); + if (ENTITY_U_INFO in parameters) { + this.entityUInfo = getParametersValue(parameters, ENTITY_U_INFO, ECCCMSSharedInfo.defaultValues(ENTITY_U_INFO)); + } + this.suppPubInfo = getParametersValue(parameters, SUPP_PUB_INFO, ECCCMSSharedInfo.defaultValues(SUPP_PUB_INFO)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case KEY_INFO: + return new AlgorithmIdentifier(); + case ENTITY_U_INFO: + return new OctetString(); + case SUPP_PUB_INFO: + return new OctetString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case KEY_INFO: + case ENTITY_U_INFO: + case SUPP_PUB_INFO: + return (memberValue.isEqual(ECCCMSSharedInfo.defaultValues(memberName))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.keyInfo || {}), + new Constructed({ + name: (names.entityUInfo || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + optional: true, + value: [new OctetString()] + }), + new Constructed({ + name: (names.suppPubInfo || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [new OctetString()] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$l); + const asn1 = compareSchema(schema, schema, ECCCMSSharedInfo.schema({ + names: { + keyInfo: { + names: { + blockName: KEY_INFO + } + }, + entityUInfo: ENTITY_U_INFO, + suppPubInfo: SUPP_PUB_INFO + } + })); + AsnError.assertSchema(asn1, this.className); + this.keyInfo = new AlgorithmIdentifier({ schema: asn1.result.keyInfo }); + if (ENTITY_U_INFO in asn1.result) + this.entityUInfo = asn1.result.entityUInfo.valueBlock.value[0]; + this.suppPubInfo = asn1.result.suppPubInfo.valueBlock.value[0]; + } + toSchema() { + const outputArray = []; + outputArray.push(this.keyInfo.toSchema()); + if (this.entityUInfo) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.entityUInfo] + })); + } + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [this.suppPubInfo] + })); + return new Sequence({ + value: outputArray + }); + } + toJSON() { + const res = { + keyInfo: this.keyInfo.toJSON(), + suppPubInfo: this.suppPubInfo.toJSON(), + }; + if (this.entityUInfo) { + res.entityUInfo = this.entityUInfo.toJSON(); + } + return res; + } +} ECCCMSSharedInfo.CLASS_NAME = "ECCCMSSharedInfo"; -const VERSION$8 = "version"; -const ORIGINATOR_INFO = "originatorInfo"; -const RECIPIENT_INFOS = "recipientInfos"; -const ENCRYPTED_CONTENT_INFO = "encryptedContentInfo"; -const UNPROTECTED_ATTRS = "unprotectedAttrs"; -const CLEAR_PROPS$k = [ - VERSION$8, - ORIGINATOR_INFO, - RECIPIENT_INFOS, - ENCRYPTED_CONTENT_INFO, - UNPROTECTED_ATTRS -]; -const defaultEncryptionParams = { - kdfAlgorithm: "SHA-512", - kekEncryptionLength: 256 -}; -const curveLengthByName = { - "P-256": 256, - "P-384": 384, - "P-521": 528 -}; -class EnvelopedData extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$8, EnvelopedData.defaultValues(VERSION$8)); - if (ORIGINATOR_INFO in parameters) { - this.originatorInfo = getParametersValue(parameters, ORIGINATOR_INFO, EnvelopedData.defaultValues(ORIGINATOR_INFO)); - } - this.recipientInfos = getParametersValue(parameters, RECIPIENT_INFOS, EnvelopedData.defaultValues(RECIPIENT_INFOS)); - this.encryptedContentInfo = getParametersValue(parameters, ENCRYPTED_CONTENT_INFO, EnvelopedData.defaultValues(ENCRYPTED_CONTENT_INFO)); - if (UNPROTECTED_ATTRS in parameters) { - this.unprotectedAttrs = getParametersValue(parameters, UNPROTECTED_ATTRS, EnvelopedData.defaultValues(UNPROTECTED_ATTRS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$8: - return 0; - case ORIGINATOR_INFO: - return new OriginatorInfo(); - case RECIPIENT_INFOS: - return []; - case ENCRYPTED_CONTENT_INFO: - return new EncryptedContentInfo(); - case UNPROTECTED_ATTRS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$8: - return (memberValue === EnvelopedData.defaultValues(memberName)); - case ORIGINATOR_INFO: - return ((memberValue.certs.certificates.length === 0) && (memberValue.crls.crls.length === 0)); - case RECIPIENT_INFOS: - case UNPROTECTED_ATTRS: - return (memberValue.length === 0); - case ENCRYPTED_CONTENT_INFO: - return ((EncryptedContentInfo.compareWithDefault("contentType", memberValue.contentType)) && - (EncryptedContentInfo.compareWithDefault("contentEncryptionAlgorithm", memberValue.contentEncryptionAlgorithm) && - (EncryptedContentInfo.compareWithDefault("encryptedContent", memberValue.encryptedContent)))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || EMPTY_STRING) }), - new Constructed({ - name: (names.originatorInfo || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: OriginatorInfo.schema().valueBlock.value - }), - new Set({ - value: [ - new Repeated({ - name: (names.recipientInfos || EMPTY_STRING), - value: RecipientInfo.schema() - }) - ] - }), - EncryptedContentInfo.schema(names.encryptedContentInfo || {}), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new Repeated({ - name: (names.unprotectedAttrs || EMPTY_STRING), - value: Attribute.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$k); - const asn1 = compareSchema(schema, schema, EnvelopedData.schema({ - names: { - version: VERSION$8, - originatorInfo: ORIGINATOR_INFO, - recipientInfos: RECIPIENT_INFOS, - encryptedContentInfo: { - names: { - blockName: ENCRYPTED_CONTENT_INFO - } - }, - unprotectedAttrs: UNPROTECTED_ATTRS - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - if (ORIGINATOR_INFO in asn1.result) { - this.originatorInfo = new OriginatorInfo({ - schema: new Sequence({ - value: asn1.result.originatorInfo.valueBlock.value - }) - }); - } - this.recipientInfos = Array.from(asn1.result.recipientInfos, o => new RecipientInfo({ schema: o })); - this.encryptedContentInfo = new EncryptedContentInfo({ schema: asn1.result.encryptedContentInfo }); - if (UNPROTECTED_ATTRS in asn1.result) - this.unprotectedAttrs = Array.from(asn1.result.unprotectedAttrs, o => new Attribute({ schema: o })); - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - if (this.originatorInfo) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: this.originatorInfo.toSchema().valueBlock.value - })); - } - outputArray.push(new Set({ - value: Array.from(this.recipientInfos, o => o.toSchema()) - })); - outputArray.push(this.encryptedContentInfo.toSchema()); - if (this.unprotectedAttrs) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: Array.from(this.unprotectedAttrs, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - version: this.version, - recipientInfos: Array.from(this.recipientInfos, o => o.toJSON()), - encryptedContentInfo: this.encryptedContentInfo.toJSON(), - }; - if (this.originatorInfo) - res.originatorInfo = this.originatorInfo.toJSON(); - if (this.unprotectedAttrs) - res.unprotectedAttrs = Array.from(this.unprotectedAttrs, o => o.toJSON()); - return res; - } - addRecipientByCertificate(certificate, parameters, variant, crypto = getCrypto(true)) { - const encryptionParameters = Object.assign({ useOAEP: true, oaepHashAlgorithm: "SHA-512" }, defaultEncryptionParams, parameters || {}); - if (certificate.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.113549") !== (-1)) - variant = 1; - else { - if (certificate.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.10045") !== (-1)) - variant = 2; - else - throw new Error(`Unknown type of certificate's public key: ${certificate.subjectPublicKeyInfo.algorithm.algorithmId}`); - } - switch (variant) { - case 1: - { - let algorithmId; - let algorithmParams; - if (encryptionParameters.useOAEP === true) { - algorithmId = crypto.getOIDByAlgorithm({ - name: "RSA-OAEP" - }, true, "keyEncryptionAlgorithm"); - const hashOID = crypto.getOIDByAlgorithm({ - name: encryptionParameters.oaepHashAlgorithm - }, true, "RSAES-OAEP-params"); - const hashAlgorithm = new AlgorithmIdentifier({ - algorithmId: hashOID, - algorithmParams: new Null() - }); - const rsaOAEPParams = new RSAESOAEPParams({ - hashAlgorithm, - maskGenAlgorithm: new AlgorithmIdentifier({ - algorithmId: "1.2.840.113549.1.1.8", - algorithmParams: hashAlgorithm.toSchema() - }) - }); - algorithmParams = rsaOAEPParams.toSchema(); - } - else { - algorithmId = crypto.getOIDByAlgorithm({ - name: "RSAES-PKCS1-v1_5" - }); - if (algorithmId === EMPTY_STRING) - throw new Error("Can not find OID for RSAES-PKCS1-v1_5"); - algorithmParams = new Null(); - } - const keyInfo = new KeyTransRecipientInfo({ - version: 0, - rid: new IssuerAndSerialNumber({ - issuer: certificate.issuer, - serialNumber: certificate.serialNumber - }), - keyEncryptionAlgorithm: new AlgorithmIdentifier({ - algorithmId, - algorithmParams - }), - recipientCertificate: certificate, - }); - this.recipientInfos.push(new RecipientInfo({ - variant: 1, - value: keyInfo - })); - } - break; - case 2: - { - const recipientIdentifier = new KeyAgreeRecipientIdentifier({ - variant: 1, - value: new IssuerAndSerialNumber({ - issuer: certificate.issuer, - serialNumber: certificate.serialNumber - }) - }); - this._addKeyAgreeRecipientInfo(recipientIdentifier, encryptionParameters, { recipientCertificate: certificate }, crypto); - } - break; - default: - throw new Error(`Unknown "variant" value: ${variant}`); - } - return true; - } - addRecipientByPreDefinedData(preDefinedData, parameters = {}, variant, crypto = getCrypto(true)) { - ArgumentError.assert(preDefinedData, "preDefinedData", "ArrayBuffer"); - if (!preDefinedData.byteLength) { - throw new Error("Pre-defined data could have zero length"); - } - if (!parameters.keyIdentifier) { - const keyIdentifierBuffer = new ArrayBuffer(16); - const keyIdentifierView = new Uint8Array(keyIdentifierBuffer); - crypto.getRandomValues(keyIdentifierView); - parameters.keyIdentifier = keyIdentifierBuffer; - } - if (!parameters.hmacHashAlgorithm) - parameters.hmacHashAlgorithm = "SHA-512"; - if (parameters.iterationCount === undefined) { - parameters.iterationCount = 2048; - } - if (!parameters.keyEncryptionAlgorithm) { - parameters.keyEncryptionAlgorithm = { - name: "AES-KW", - length: 256 - }; - } - if (!parameters.keyEncryptionAlgorithmParams) - parameters.keyEncryptionAlgorithmParams = new Null(); - switch (variant) { - case 1: - { - const kekOID = crypto.getOIDByAlgorithm(parameters.keyEncryptionAlgorithm, true, "keyEncryptionAlgorithm"); - const keyInfo = new KEKRecipientInfo({ - version: 4, - kekid: new KEKIdentifier({ - keyIdentifier: new OctetString({ valueHex: parameters.keyIdentifier }) - }), - keyEncryptionAlgorithm: new AlgorithmIdentifier({ - algorithmId: kekOID, - algorithmParams: parameters.keyEncryptionAlgorithmParams - }), - preDefinedKEK: preDefinedData - }); - this.recipientInfos.push(new RecipientInfo({ - variant: 3, - value: keyInfo - })); - } - break; - case 2: - { - const pbkdf2OID = crypto.getOIDByAlgorithm({ name: "PBKDF2" }, true, "keyDerivationAlgorithm"); - const saltBuffer = new ArrayBuffer(64); - const saltView = new Uint8Array(saltBuffer); - crypto.getRandomValues(saltView); - const hmacOID = crypto.getOIDByAlgorithm({ - name: "HMAC", - hash: { - name: parameters.hmacHashAlgorithm - } - }, true, "hmacHashAlgorithm"); - const pbkdf2Params = new PBKDF2Params({ - salt: new OctetString({ valueHex: saltBuffer }), - iterationCount: parameters.iterationCount, - prf: new AlgorithmIdentifier({ - algorithmId: hmacOID, - algorithmParams: new Null() - }) - }); - const kekOID = crypto.getOIDByAlgorithm(parameters.keyEncryptionAlgorithm, true, "keyEncryptionAlgorithm"); - const keyInfo = new PasswordRecipientinfo({ - version: 0, - keyDerivationAlgorithm: new AlgorithmIdentifier({ - algorithmId: pbkdf2OID, - algorithmParams: pbkdf2Params.toSchema() - }), - keyEncryptionAlgorithm: new AlgorithmIdentifier({ - algorithmId: kekOID, - algorithmParams: parameters.keyEncryptionAlgorithmParams - }), - password: preDefinedData - }); - this.recipientInfos.push(new RecipientInfo({ - variant: 4, - value: keyInfo - })); - } - break; - default: - throw new Error(`Unknown value for "variant": ${variant}`); - } - } - addRecipientByKeyIdentifier(key, keyId, parameters, crypto = getCrypto(true)) { - const encryptionParameters = Object.assign({}, defaultEncryptionParams, parameters || {}); - const recipientIdentifier = new KeyAgreeRecipientIdentifier({ - variant: 2, - value: new RecipientKeyIdentifier({ - subjectKeyIdentifier: new OctetString({ valueHex: keyId }), - }) - }); - this._addKeyAgreeRecipientInfo(recipientIdentifier, encryptionParameters, { recipientPublicKey: key }, crypto); - } - _addKeyAgreeRecipientInfo(recipientIdentifier, encryptionParameters, extraRecipientInfoParams, crypto = getCrypto(true)) { - const encryptedKey = new RecipientEncryptedKey({ - rid: recipientIdentifier - }); - const aesKWoid = crypto.getOIDByAlgorithm({ - name: "AES-KW", - length: encryptionParameters.kekEncryptionLength - }, true, "keyEncryptionAlgorithm"); - const aesKW = new AlgorithmIdentifier({ - algorithmId: aesKWoid, - }); - const ecdhOID = crypto.getOIDByAlgorithm({ - name: "ECDH", - kdf: encryptionParameters.kdfAlgorithm - }, true, "KeyAgreeRecipientInfo"); - const ukmBuffer = new ArrayBuffer(64); - const ukmView = new Uint8Array(ukmBuffer); - crypto.getRandomValues(ukmView); - const recipientInfoParams = { - version: 3, - ukm: new OctetString({ valueHex: ukmBuffer }), - keyEncryptionAlgorithm: new AlgorithmIdentifier({ - algorithmId: ecdhOID, - algorithmParams: aesKW.toSchema() - }), - recipientEncryptedKeys: new RecipientEncryptedKeys({ - encryptedKeys: [encryptedKey] - }) - }; - const keyInfo = new KeyAgreeRecipientInfo(Object.assign(recipientInfoParams, extraRecipientInfoParams)); - this.recipientInfos.push(new RecipientInfo({ - variant: 2, - value: keyInfo - })); - } - encrypt(contentEncryptionAlgorithm, contentToEncrypt, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const ivBuffer = new ArrayBuffer(16); - const ivView = new Uint8Array(ivBuffer); - crypto.getRandomValues(ivView); - const contentView = new Uint8Array(contentToEncrypt); - const contentEncryptionOID = crypto.getOIDByAlgorithm(contentEncryptionAlgorithm, true, "contentEncryptionAlgorithm"); - const sessionKey = yield crypto.generateKey(contentEncryptionAlgorithm, true, ["encrypt"]); - const encryptedContent = yield crypto.encrypt({ - name: contentEncryptionAlgorithm.name, - iv: ivView - }, sessionKey, contentView); - const exportedSessionKey = yield crypto.exportKey("raw", sessionKey); - this.version = 2; - this.encryptedContentInfo = new EncryptedContentInfo({ - contentType: "1.2.840.113549.1.7.1", - contentEncryptionAlgorithm: new AlgorithmIdentifier({ - algorithmId: contentEncryptionOID, - algorithmParams: new OctetString({ valueHex: ivBuffer }) - }), - encryptedContent: new OctetString({ valueHex: encryptedContent }) - }); - const SubKeyAgreeRecipientInfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - let recipientCurve; - let recipientPublicKey; - if (recipientInfo.recipientPublicKey) { - recipientCurve = recipientInfo.recipientPublicKey.algorithm.namedCurve; - recipientPublicKey = recipientInfo.recipientPublicKey; - } - else if (recipientInfo.recipientCertificate) { - const curveObject = recipientInfo.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams; - if (curveObject.constructor.blockName() !== ObjectIdentifier.blockName()) - throw new Error(`Incorrect "recipientCertificate" for index ${index}`); - const curveOID = curveObject.valueBlock.toString(); - switch (curveOID) { - case "1.2.840.10045.3.1.7": - recipientCurve = "P-256"; - break; - case "1.3.132.0.34": - recipientCurve = "P-384"; - break; - case "1.3.132.0.35": - recipientCurve = "P-521"; - break; - default: - throw new Error(`Incorrect curve OID for index ${index}`); - } - recipientPublicKey = yield recipientInfo.recipientCertificate.getPublicKey({ - algorithm: { - algorithm: { - name: "ECDH", - namedCurve: recipientCurve - }, - usages: [] - } - }, crypto); - } - else { - throw new Error("Unsupported RecipientInfo"); - } - const recipientCurveLength = curveLengthByName[recipientCurve]; - const ecdhKeys = yield crypto.generateKey({ name: "ECDH", namedCurve: recipientCurve }, true, ["deriveBits"]); - const exportedECDHPublicKey = yield crypto.exportKey("spki", ecdhKeys.publicKey); - const derivedBits = yield crypto.deriveBits({ - name: "ECDH", - public: recipientPublicKey - }, ecdhKeys.privateKey, recipientCurveLength); - const aesKWAlgorithm = new AlgorithmIdentifier({ schema: recipientInfo.keyEncryptionAlgorithm.algorithmParams }); - const kwAlgorithm = crypto.getAlgorithmByOID(aesKWAlgorithm.algorithmId, true, "aesKWAlgorithm"); - let kwLength = kwAlgorithm.length; - const kwLengthBuffer = new ArrayBuffer(4); - const kwLengthView = new Uint8Array(kwLengthBuffer); - for (let j = 3; j >= 0; j--) { - kwLengthView[j] = kwLength; - kwLength >>= 8; - } - const eccInfo = new ECCCMSSharedInfo({ - keyInfo: new AlgorithmIdentifier({ - algorithmId: aesKWAlgorithm.algorithmId - }), - entityUInfo: recipientInfo.ukm, - suppPubInfo: new OctetString({ valueHex: kwLengthBuffer }) - }); - const encodedInfo = eccInfo.toSchema().toBER(false); - const ecdhAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "ecdhAlgorithm"); - const derivedKeyRaw = yield kdf(ecdhAlgorithm.kdf, derivedBits, kwAlgorithm.length, encodedInfo, crypto); - const awsKW = yield crypto.importKey("raw", derivedKeyRaw, { name: "AES-KW" }, true, ["wrapKey"]); - const wrappedKey = yield crypto.wrapKey("raw", sessionKey, awsKW, { name: "AES-KW" }); - const originator = new OriginatorIdentifierOrKey(); - originator.variant = 3; - originator.value = OriginatorPublicKey.fromBER(exportedECDHPublicKey); - recipientInfo.originator = originator; - recipientInfo.recipientEncryptedKeys.encryptedKeys[0].encryptedKey = new OctetString({ valueHex: wrappedKey }); - return { ecdhPrivateKey: ecdhKeys.privateKey }; - }); - const SubKeyTransRecipientInfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - const algorithmParameters = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "keyEncryptionAlgorithm"); - if (algorithmParameters.name === "RSA-OAEP") { - const schema = recipientInfo.keyEncryptionAlgorithm.algorithmParams; - const rsaOAEPParams = new RSAESOAEPParams({ schema }); - algorithmParameters.hash = crypto.getAlgorithmByOID(rsaOAEPParams.hashAlgorithm.algorithmId); - if (("name" in algorithmParameters.hash) === false) - throw new Error(`Incorrect OID for hash algorithm: ${rsaOAEPParams.hashAlgorithm.algorithmId}`); - } - try { - const publicKey = yield recipientInfo.recipientCertificate.getPublicKey({ - algorithm: { - algorithm: algorithmParameters, - usages: ["encrypt", "wrapKey"] - } - }, crypto); - const encryptedKey = yield crypto.encrypt(publicKey.algorithm, publicKey, exportedSessionKey); - recipientInfo.encryptedKey = new OctetString({ valueHex: encryptedKey }); - } - catch (_a) { - } - }); - const SubKEKRecipientInfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "kekAlgorithm"); - const kekKey = yield crypto.importKey("raw", new Uint8Array(recipientInfo.preDefinedKEK), kekAlgorithm, true, ["wrapKey"]); - const wrappedKey = yield crypto.wrapKey("raw", sessionKey, kekKey, kekAlgorithm); - recipientInfo.encryptedKey = new OctetString({ valueHex: wrappedKey }); - }); - const SubPasswordRecipientinfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - let pbkdf2Params; - if (!recipientInfo.keyDerivationAlgorithm) - throw new Error("Please append encoded \"keyDerivationAlgorithm\""); - if (!recipientInfo.keyDerivationAlgorithm.algorithmParams) - throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); - try { - pbkdf2Params = new PBKDF2Params({ schema: recipientInfo.keyDerivationAlgorithm.algorithmParams }); - } - catch (ex) { - throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); - } - const passwordView = new Uint8Array(recipientInfo.password); - const derivationKey = yield crypto.importKey("raw", passwordView, "PBKDF2", false, ["deriveKey"]); - const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "kekAlgorithm"); - let hmacHashAlgorithm = "SHA-1"; - if (pbkdf2Params.prf) { - const prfAlgorithm = crypto.getAlgorithmByOID(pbkdf2Params.prf.algorithmId, true, "prfAlgorithm"); - hmacHashAlgorithm = prfAlgorithm.hash.name; - } - const saltView = new Uint8Array(pbkdf2Params.salt.valueBlock.valueHex); - const iterations = pbkdf2Params.iterationCount; - const derivedKey = yield crypto.deriveKey({ - name: "PBKDF2", - hash: { - name: hmacHashAlgorithm - }, - salt: saltView, - iterations - }, derivationKey, kekAlgorithm, true, ["wrapKey"]); - const wrappedKey = yield crypto.wrapKey("raw", sessionKey, derivedKey, kekAlgorithm); - recipientInfo.encryptedKey = new OctetString({ valueHex: wrappedKey }); - }); - const res = []; - for (let i = 0; i < this.recipientInfos.length; i++) { - switch (this.recipientInfos[i].variant) { - case 1: - res.push(yield SubKeyTransRecipientInfo(i)); - break; - case 2: - res.push(yield SubKeyAgreeRecipientInfo(i)); - break; - case 3: - res.push(yield SubKEKRecipientInfo(i)); - break; - case 4: - res.push(yield SubPasswordRecipientinfo(i)); - break; - default: - throw new Error(`Unknown recipient type in array with index ${i}`); - } - } - return res; - }); - } - decrypt(recipientIndex, parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const decryptionParameters = parameters || {}; - if ((recipientIndex + 1) > this.recipientInfos.length) { - throw new Error(`Maximum value for "index" is: ${this.recipientInfos.length - 1}`); - } - const SubKeyAgreeRecipientInfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - let curveOID; - let recipientCurve; - let recipientCurveLength; - const originator = recipientInfo.originator; - if (decryptionParameters.recipientCertificate) { - const curveObject = decryptionParameters.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams; - if (curveObject.constructor.blockName() !== ObjectIdentifier.blockName()) { - throw new Error(`Incorrect "recipientCertificate" for index ${index}`); - } - curveOID = curveObject.valueBlock.toString(); - } - else if (originator.value.algorithm.algorithmParams) { - const curveObject = originator.value.algorithm.algorithmParams; - if (curveObject.constructor.blockName() !== ObjectIdentifier.blockName()) { - throw new Error(`Incorrect originator for index ${index}`); - } - curveOID = curveObject.valueBlock.toString(); - } - else { - throw new Error("Parameter \"recipientCertificate\" is mandatory for \"KeyAgreeRecipientInfo\" if algorithm params are missing from originator"); - } - if (!decryptionParameters.recipientPrivateKey) - throw new Error("Parameter \"recipientPrivateKey\" is mandatory for \"KeyAgreeRecipientInfo\""); - switch (curveOID) { - case "1.2.840.10045.3.1.7": - recipientCurve = "P-256"; - recipientCurveLength = 256; - break; - case "1.3.132.0.34": - recipientCurve = "P-384"; - recipientCurveLength = 384; - break; - case "1.3.132.0.35": - recipientCurve = "P-521"; - recipientCurveLength = 528; - break; - default: - throw new Error(`Incorrect curve OID for index ${index}`); - } - const ecdhPrivateKey = yield crypto.importKey("pkcs8", decryptionParameters.recipientPrivateKey, { - name: "ECDH", - namedCurve: recipientCurve - }, true, ["deriveBits"]); - if (("algorithmParams" in originator.value.algorithm) === false) - originator.value.algorithm.algorithmParams = new ObjectIdentifier({ value: curveOID }); - const buffer = originator.value.toSchema().toBER(false); - const ecdhPublicKey = yield crypto.importKey("spki", buffer, { - name: "ECDH", - namedCurve: recipientCurve - }, true, []); - const sharedSecret = yield crypto.deriveBits({ - name: "ECDH", - public: ecdhPublicKey - }, ecdhPrivateKey, recipientCurveLength); - function applyKDF(includeAlgorithmParams) { - return __awaiter(this, void 0, void 0, function* () { - includeAlgorithmParams = includeAlgorithmParams || false; - const aesKWAlgorithm = new AlgorithmIdentifier({ schema: recipientInfo.keyEncryptionAlgorithm.algorithmParams }); - const kwAlgorithm = crypto.getAlgorithmByOID(aesKWAlgorithm.algorithmId, true, "kwAlgorithm"); - let kwLength = kwAlgorithm.length; - const kwLengthBuffer = new ArrayBuffer(4); - const kwLengthView = new Uint8Array(kwLengthBuffer); - for (let j = 3; j >= 0; j--) { - kwLengthView[j] = kwLength; - kwLength >>= 8; - } - const keyInfoAlgorithm = { - algorithmId: aesKWAlgorithm.algorithmId - }; - if (includeAlgorithmParams) { - keyInfoAlgorithm.algorithmParams = new Null(); - } - const eccInfo = new ECCCMSSharedInfo({ - keyInfo: new AlgorithmIdentifier(keyInfoAlgorithm), - entityUInfo: recipientInfo.ukm, - suppPubInfo: new OctetString({ valueHex: kwLengthBuffer }) - }); - const encodedInfo = eccInfo.toSchema().toBER(false); - const ecdhAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "ecdhAlgorithm"); - if (!ecdhAlgorithm.name) { - throw new Error(`Incorrect OID for key encryption algorithm: ${recipientInfo.keyEncryptionAlgorithm.algorithmId}`); - } - return kdf(ecdhAlgorithm.kdf, sharedSecret, kwAlgorithm.length, encodedInfo, crypto); - }); - } - const kdfResult = yield applyKDF(); - const importAesKwKey = (kdfResult) => __awaiter(this, void 0, void 0, function* () { - return crypto.importKey("raw", kdfResult, { name: "AES-KW" }, true, ["unwrapKey"]); - }); - const aesKwKey = yield importAesKwKey(kdfResult); - const unwrapSessionKey = (aesKwKey) => __awaiter(this, void 0, void 0, function* () { - const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; - const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); - return crypto.unwrapKey("raw", recipientInfo.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView, aesKwKey, { name: "AES-KW" }, contentEncryptionAlgorithm, true, ["decrypt"]); - }); - try { - return yield unwrapSessionKey(aesKwKey); - } - catch (_a) { - const kdfResult = yield applyKDF(true); - const aesKwKey = yield importAesKwKey(kdfResult); - return unwrapSessionKey(aesKwKey); - } - }); - const SubKeyTransRecipientInfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - if (!decryptionParameters.recipientPrivateKey) { - throw new Error("Parameter \"recipientPrivateKey\" is mandatory for \"KeyTransRecipientInfo\""); - } - const algorithmParameters = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "keyEncryptionAlgorithm"); - if (algorithmParameters.name === "RSA-OAEP") { - const schema = recipientInfo.keyEncryptionAlgorithm.algorithmParams; - const rsaOAEPParams = new RSAESOAEPParams({ schema }); - algorithmParameters.hash = crypto.getAlgorithmByOID(rsaOAEPParams.hashAlgorithm.algorithmId); - if (("name" in algorithmParameters.hash) === false) - throw new Error(`Incorrect OID for hash algorithm: ${rsaOAEPParams.hashAlgorithm.algorithmId}`); - } - const privateKey = yield crypto.importKey("pkcs8", decryptionParameters.recipientPrivateKey, algorithmParameters, true, ["decrypt"]); - const sessionKey = yield crypto.decrypt(privateKey.algorithm, privateKey, recipientInfo.encryptedKey.valueBlock.valueHexView); - const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; - const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); - if (("name" in contentEncryptionAlgorithm) === false) - throw new Error(`Incorrect "contentEncryptionAlgorithm": ${algorithmId}`); - return crypto.importKey("raw", sessionKey, contentEncryptionAlgorithm, true, ["decrypt"]); - }); - const SubKEKRecipientInfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - if (!decryptionParameters.preDefinedData) - throw new Error("Parameter \"preDefinedData\" is mandatory for \"KEKRecipientInfo\""); - const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "kekAlgorithm"); - const importedKey = yield crypto.importKey("raw", decryptionParameters.preDefinedData, kekAlgorithm, true, ["unwrapKey"]); - const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; - const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); - if (!contentEncryptionAlgorithm.name) { - throw new Error(`Incorrect "contentEncryptionAlgorithm": ${algorithmId}`); - } - return crypto.unwrapKey("raw", recipientInfo.encryptedKey.valueBlock.valueHexView, importedKey, kekAlgorithm, contentEncryptionAlgorithm, true, ["decrypt"]); - }); - const SubPasswordRecipientinfo = (index) => __awaiter(this, void 0, void 0, function* () { - const recipientInfo = this.recipientInfos[index].value; - let pbkdf2Params; - if (!decryptionParameters.preDefinedData) { - throw new Error("Parameter \"preDefinedData\" is mandatory for \"KEKRecipientInfo\""); - } - if (!recipientInfo.keyDerivationAlgorithm) { - throw new Error("Please append encoded \"keyDerivationAlgorithm\""); - } - if (!recipientInfo.keyDerivationAlgorithm.algorithmParams) { - throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); - } - try { - pbkdf2Params = new PBKDF2Params({ schema: recipientInfo.keyDerivationAlgorithm.algorithmParams }); - } - catch (ex) { - throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); - } - const pbkdf2Key = yield crypto.importKey("raw", decryptionParameters.preDefinedData, "PBKDF2", false, ["deriveKey"]); - const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "keyEncryptionAlgorithm"); - const hmacHashAlgorithm = pbkdf2Params.prf - ? crypto.getAlgorithmByOID(pbkdf2Params.prf.algorithmId, true, "prfAlgorithm").hash.name - : "SHA-1"; - const saltView = new Uint8Array(pbkdf2Params.salt.valueBlock.valueHex); - const iterations = pbkdf2Params.iterationCount; - const kekKey = yield crypto.deriveKey({ - name: "PBKDF2", - hash: { - name: hmacHashAlgorithm - }, - salt: saltView, - iterations - }, pbkdf2Key, kekAlgorithm, true, ["unwrapKey"]); - const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; - const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); - return crypto.unwrapKey("raw", recipientInfo.encryptedKey.valueBlock.valueHexView, kekKey, kekAlgorithm, contentEncryptionAlgorithm, true, ["decrypt"]); - }); - let unwrappedKey; - switch (this.recipientInfos[recipientIndex].variant) { - case 1: - unwrappedKey = yield SubKeyTransRecipientInfo(recipientIndex); - break; - case 2: - unwrappedKey = yield SubKeyAgreeRecipientInfo(recipientIndex); - break; - case 3: - unwrappedKey = yield SubKEKRecipientInfo(recipientIndex); - break; - case 4: - unwrappedKey = yield SubPasswordRecipientinfo(recipientIndex); - break; - default: - throw new Error(`Unknown recipient type in array with index ${recipientIndex}`); - } - const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; - const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); - const ivBuffer = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams.valueBlock.valueHex; - const ivView = new Uint8Array(ivBuffer); - if (!this.encryptedContentInfo.encryptedContent) { - throw new Error("Required property `encryptedContent` is empty"); - } - const dataBuffer = this.encryptedContentInfo.getEncryptedContent(); - return crypto.decrypt({ - name: contentEncryptionAlgorithm.name, - iv: ivView - }, unwrappedKey, dataBuffer); - }); - } -} +const VERSION$8 = "version"; +const ORIGINATOR_INFO = "originatorInfo"; +const RECIPIENT_INFOS = "recipientInfos"; +const ENCRYPTED_CONTENT_INFO = "encryptedContentInfo"; +const UNPROTECTED_ATTRS = "unprotectedAttrs"; +const CLEAR_PROPS$k = [ + VERSION$8, + ORIGINATOR_INFO, + RECIPIENT_INFOS, + ENCRYPTED_CONTENT_INFO, + UNPROTECTED_ATTRS +]; +const defaultEncryptionParams = { + kdfAlgorithm: "SHA-512", + kekEncryptionLength: 256 +}; +const curveLengthByName = { + "P-256": 256, + "P-384": 384, + "P-521": 528 +}; +class EnvelopedData extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$8, EnvelopedData.defaultValues(VERSION$8)); + if (ORIGINATOR_INFO in parameters) { + this.originatorInfo = getParametersValue(parameters, ORIGINATOR_INFO, EnvelopedData.defaultValues(ORIGINATOR_INFO)); + } + this.recipientInfos = getParametersValue(parameters, RECIPIENT_INFOS, EnvelopedData.defaultValues(RECIPIENT_INFOS)); + this.encryptedContentInfo = getParametersValue(parameters, ENCRYPTED_CONTENT_INFO, EnvelopedData.defaultValues(ENCRYPTED_CONTENT_INFO)); + if (UNPROTECTED_ATTRS in parameters) { + this.unprotectedAttrs = getParametersValue(parameters, UNPROTECTED_ATTRS, EnvelopedData.defaultValues(UNPROTECTED_ATTRS)); + } + this.policy = { + disableSplit: !!parameters.disableSplit, + }; + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$8: + return 0; + case ORIGINATOR_INFO: + return new OriginatorInfo(); + case RECIPIENT_INFOS: + return []; + case ENCRYPTED_CONTENT_INFO: + return new EncryptedContentInfo(); + case UNPROTECTED_ATTRS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$8: + return (memberValue === EnvelopedData.defaultValues(memberName)); + case ORIGINATOR_INFO: + return ((memberValue.certs.certificates.length === 0) && (memberValue.crls.crls.length === 0)); + case RECIPIENT_INFOS: + case UNPROTECTED_ATTRS: + return (memberValue.length === 0); + case ENCRYPTED_CONTENT_INFO: + return ((EncryptedContentInfo.compareWithDefault("contentType", memberValue.contentType)) && + (EncryptedContentInfo.compareWithDefault("contentEncryptionAlgorithm", memberValue.contentEncryptionAlgorithm) && + (EncryptedContentInfo.compareWithDefault("encryptedContent", memberValue.encryptedContent)))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || EMPTY_STRING) }), + new Constructed({ + name: (names.originatorInfo || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: OriginatorInfo.schema().valueBlock.value + }), + new Set({ + value: [ + new Repeated({ + name: (names.recipientInfos || EMPTY_STRING), + value: RecipientInfo.schema() + }) + ] + }), + EncryptedContentInfo.schema(names.encryptedContentInfo || {}), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new Repeated({ + name: (names.unprotectedAttrs || EMPTY_STRING), + value: Attribute.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$k); + const asn1 = compareSchema(schema, schema, EnvelopedData.schema({ + names: { + version: VERSION$8, + originatorInfo: ORIGINATOR_INFO, + recipientInfos: RECIPIENT_INFOS, + encryptedContentInfo: { + names: { + blockName: ENCRYPTED_CONTENT_INFO + } + }, + unprotectedAttrs: UNPROTECTED_ATTRS + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + if (ORIGINATOR_INFO in asn1.result) { + this.originatorInfo = new OriginatorInfo({ + schema: new Sequence({ + value: asn1.result.originatorInfo.valueBlock.value + }) + }); + } + this.recipientInfos = Array.from(asn1.result.recipientInfos, o => new RecipientInfo({ schema: o })); + this.encryptedContentInfo = new EncryptedContentInfo({ schema: asn1.result.encryptedContentInfo }); + if (UNPROTECTED_ATTRS in asn1.result) + this.unprotectedAttrs = Array.from(asn1.result.unprotectedAttrs, o => new Attribute({ schema: o })); + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + if (this.originatorInfo) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: this.originatorInfo.toSchema().valueBlock.value + })); + } + outputArray.push(new Set({ + value: Array.from(this.recipientInfos, o => o.toSchema()) + })); + outputArray.push(this.encryptedContentInfo.toSchema()); + if (this.unprotectedAttrs) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: Array.from(this.unprotectedAttrs, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + version: this.version, + recipientInfos: Array.from(this.recipientInfos, o => o.toJSON()), + encryptedContentInfo: this.encryptedContentInfo.toJSON(), + }; + if (this.originatorInfo) + res.originatorInfo = this.originatorInfo.toJSON(); + if (this.unprotectedAttrs) + res.unprotectedAttrs = Array.from(this.unprotectedAttrs, o => o.toJSON()); + return res; + } + addRecipientByCertificate(certificate, parameters, variant, crypto = getCrypto(true)) { + const encryptionParameters = Object.assign({ useOAEP: true, oaepHashAlgorithm: "SHA-512" }, defaultEncryptionParams, parameters || {}); + if (certificate.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.113549") !== (-1)) + variant = 1; + else { + if (certificate.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.10045") !== (-1)) + variant = 2; + else + throw new Error(`Unknown type of certificate's public key: ${certificate.subjectPublicKeyInfo.algorithm.algorithmId}`); + } + switch (variant) { + case 1: + { + let algorithmId; + let algorithmParams; + if (encryptionParameters.useOAEP === true) { + algorithmId = crypto.getOIDByAlgorithm({ + name: "RSA-OAEP" + }, true, "keyEncryptionAlgorithm"); + const hashOID = crypto.getOIDByAlgorithm({ + name: encryptionParameters.oaepHashAlgorithm + }, true, "RSAES-OAEP-params"); + const hashAlgorithm = new AlgorithmIdentifier({ + algorithmId: hashOID, + algorithmParams: new Null() + }); + const rsaOAEPParams = new RSAESOAEPParams({ + hashAlgorithm, + maskGenAlgorithm: new AlgorithmIdentifier({ + algorithmId: "1.2.840.113549.1.1.8", + algorithmParams: hashAlgorithm.toSchema() + }) + }); + algorithmParams = rsaOAEPParams.toSchema(); + } + else { + algorithmId = crypto.getOIDByAlgorithm({ + name: "RSAES-PKCS1-v1_5" + }); + if (algorithmId === EMPTY_STRING) + throw new Error("Can not find OID for RSAES-PKCS1-v1_5"); + algorithmParams = new Null(); + } + const keyInfo = new KeyTransRecipientInfo({ + version: 0, + rid: new IssuerAndSerialNumber({ + issuer: certificate.issuer, + serialNumber: certificate.serialNumber + }), + keyEncryptionAlgorithm: new AlgorithmIdentifier({ + algorithmId, + algorithmParams + }), + recipientCertificate: certificate, + }); + this.recipientInfos.push(new RecipientInfo({ + variant: 1, + value: keyInfo + })); + } + break; + case 2: + { + const recipientIdentifier = new KeyAgreeRecipientIdentifier({ + variant: 1, + value: new IssuerAndSerialNumber({ + issuer: certificate.issuer, + serialNumber: certificate.serialNumber + }) + }); + this._addKeyAgreeRecipientInfo(recipientIdentifier, encryptionParameters, { recipientCertificate: certificate }, crypto); + } + break; + default: + throw new Error(`Unknown "variant" value: ${variant}`); + } + return true; + } + addRecipientByPreDefinedData(preDefinedData, parameters = {}, variant, crypto = getCrypto(true)) { + ArgumentError.assert(preDefinedData, "preDefinedData", "ArrayBuffer"); + if (!preDefinedData.byteLength) { + throw new Error("Pre-defined data could have zero length"); + } + if (!parameters.keyIdentifier) { + const keyIdentifierBuffer = new ArrayBuffer(16); + const keyIdentifierView = new Uint8Array(keyIdentifierBuffer); + crypto.getRandomValues(keyIdentifierView); + parameters.keyIdentifier = keyIdentifierBuffer; + } + if (!parameters.hmacHashAlgorithm) + parameters.hmacHashAlgorithm = "SHA-512"; + if (parameters.iterationCount === undefined) { + parameters.iterationCount = 2048; + } + if (!parameters.keyEncryptionAlgorithm) { + parameters.keyEncryptionAlgorithm = { + name: "AES-KW", + length: 256 + }; + } + if (!parameters.keyEncryptionAlgorithmParams) + parameters.keyEncryptionAlgorithmParams = new Null(); + switch (variant) { + case 1: + { + const kekOID = crypto.getOIDByAlgorithm(parameters.keyEncryptionAlgorithm, true, "keyEncryptionAlgorithm"); + const keyInfo = new KEKRecipientInfo({ + version: 4, + kekid: new KEKIdentifier({ + keyIdentifier: new OctetString({ valueHex: parameters.keyIdentifier }) + }), + keyEncryptionAlgorithm: new AlgorithmIdentifier({ + algorithmId: kekOID, + algorithmParams: parameters.keyEncryptionAlgorithmParams + }), + preDefinedKEK: preDefinedData + }); + this.recipientInfos.push(new RecipientInfo({ + variant: 3, + value: keyInfo + })); + } + break; + case 2: + { + const pbkdf2OID = crypto.getOIDByAlgorithm({ name: "PBKDF2" }, true, "keyDerivationAlgorithm"); + const saltBuffer = new ArrayBuffer(64); + const saltView = new Uint8Array(saltBuffer); + crypto.getRandomValues(saltView); + const hmacOID = crypto.getOIDByAlgorithm({ + name: "HMAC", + hash: { + name: parameters.hmacHashAlgorithm + } + }, true, "hmacHashAlgorithm"); + const pbkdf2Params = new PBKDF2Params({ + salt: new OctetString({ valueHex: saltBuffer }), + iterationCount: parameters.iterationCount, + prf: new AlgorithmIdentifier({ + algorithmId: hmacOID, + algorithmParams: new Null() + }) + }); + const kekOID = crypto.getOIDByAlgorithm(parameters.keyEncryptionAlgorithm, true, "keyEncryptionAlgorithm"); + const keyInfo = new PasswordRecipientinfo({ + version: 0, + keyDerivationAlgorithm: new AlgorithmIdentifier({ + algorithmId: pbkdf2OID, + algorithmParams: pbkdf2Params.toSchema() + }), + keyEncryptionAlgorithm: new AlgorithmIdentifier({ + algorithmId: kekOID, + algorithmParams: parameters.keyEncryptionAlgorithmParams + }), + password: preDefinedData + }); + this.recipientInfos.push(new RecipientInfo({ + variant: 4, + value: keyInfo + })); + } + break; + default: + throw new Error(`Unknown value for "variant": ${variant}`); + } + } + addRecipientByKeyIdentifier(key, keyId, parameters, crypto = getCrypto(true)) { + const encryptionParameters = Object.assign({}, defaultEncryptionParams, parameters || {}); + const recipientIdentifier = new KeyAgreeRecipientIdentifier({ + variant: 2, + value: new RecipientKeyIdentifier({ + subjectKeyIdentifier: new OctetString({ valueHex: keyId }), + }) + }); + this._addKeyAgreeRecipientInfo(recipientIdentifier, encryptionParameters, { recipientPublicKey: key }, crypto); + } + _addKeyAgreeRecipientInfo(recipientIdentifier, encryptionParameters, extraRecipientInfoParams, crypto = getCrypto(true)) { + const encryptedKey = new RecipientEncryptedKey({ + rid: recipientIdentifier + }); + const aesKWoid = crypto.getOIDByAlgorithm({ + name: "AES-KW", + length: encryptionParameters.kekEncryptionLength + }, true, "keyEncryptionAlgorithm"); + const aesKW = new AlgorithmIdentifier({ + algorithmId: aesKWoid, + }); + const ecdhOID = crypto.getOIDByAlgorithm({ + name: "ECDH", + kdf: encryptionParameters.kdfAlgorithm + }, true, "KeyAgreeRecipientInfo"); + const ukmBuffer = new ArrayBuffer(64); + const ukmView = new Uint8Array(ukmBuffer); + crypto.getRandomValues(ukmView); + const recipientInfoParams = { + version: 3, + ukm: new OctetString({ valueHex: ukmBuffer }), + keyEncryptionAlgorithm: new AlgorithmIdentifier({ + algorithmId: ecdhOID, + algorithmParams: aesKW.toSchema() + }), + recipientEncryptedKeys: new RecipientEncryptedKeys({ + encryptedKeys: [encryptedKey] + }) + }; + const keyInfo = new KeyAgreeRecipientInfo(Object.assign(recipientInfoParams, extraRecipientInfoParams)); + this.recipientInfos.push(new RecipientInfo({ + variant: 2, + value: keyInfo + })); + } + async encrypt(contentEncryptionAlgorithm, contentToEncrypt, crypto = getCrypto(true)) { + const ivBuffer = new ArrayBuffer(16); + const ivView = new Uint8Array(ivBuffer); + crypto.getRandomValues(ivView); + const contentView = new Uint8Array(contentToEncrypt); + const contentEncryptionOID = crypto.getOIDByAlgorithm(contentEncryptionAlgorithm, true, "contentEncryptionAlgorithm"); + const sessionKey = await crypto.generateKey(contentEncryptionAlgorithm, true, ["encrypt"]); + const encryptedContent = await crypto.encrypt({ + name: contentEncryptionAlgorithm.name, + iv: ivView + }, sessionKey, contentView); + const exportedSessionKey = await crypto.exportKey("raw", sessionKey); + this.version = 2; + this.encryptedContentInfo = new EncryptedContentInfo({ + disableSplit: this.policy.disableSplit, + contentType: "1.2.840.113549.1.7.1", + contentEncryptionAlgorithm: new AlgorithmIdentifier({ + algorithmId: contentEncryptionOID, + algorithmParams: new OctetString({ valueHex: ivBuffer }) + }), + encryptedContent: new OctetString({ valueHex: encryptedContent }) + }); + const SubKeyAgreeRecipientInfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + let recipientCurve; + let recipientPublicKey; + if (recipientInfo.recipientPublicKey) { + recipientCurve = recipientInfo.recipientPublicKey.algorithm.namedCurve; + recipientPublicKey = recipientInfo.recipientPublicKey; + } + else if (recipientInfo.recipientCertificate) { + const curveObject = recipientInfo.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams; + if (curveObject.constructor.blockName() !== ObjectIdentifier.blockName()) + throw new Error(`Incorrect "recipientCertificate" for index ${index}`); + const curveOID = curveObject.valueBlock.toString(); + switch (curveOID) { + case "1.2.840.10045.3.1.7": + recipientCurve = "P-256"; + break; + case "1.3.132.0.34": + recipientCurve = "P-384"; + break; + case "1.3.132.0.35": + recipientCurve = "P-521"; + break; + default: + throw new Error(`Incorrect curve OID for index ${index}`); + } + recipientPublicKey = await recipientInfo.recipientCertificate.getPublicKey({ + algorithm: { + algorithm: { + name: "ECDH", + namedCurve: recipientCurve + }, + usages: [] + } + }, crypto); + } + else { + throw new Error("Unsupported RecipientInfo"); + } + const recipientCurveLength = curveLengthByName[recipientCurve]; + const ecdhKeys = await crypto.generateKey({ name: "ECDH", namedCurve: recipientCurve }, true, ["deriveBits"]); + const exportedECDHPublicKey = await crypto.exportKey("spki", ecdhKeys.publicKey); + const derivedBits = await crypto.deriveBits({ + name: "ECDH", + public: recipientPublicKey + }, ecdhKeys.privateKey, recipientCurveLength); + const aesKWAlgorithm = new AlgorithmIdentifier({ schema: recipientInfo.keyEncryptionAlgorithm.algorithmParams }); + const kwAlgorithm = crypto.getAlgorithmByOID(aesKWAlgorithm.algorithmId, true, "aesKWAlgorithm"); + let kwLength = kwAlgorithm.length; + const kwLengthBuffer = new ArrayBuffer(4); + const kwLengthView = new Uint8Array(kwLengthBuffer); + for (let j = 3; j >= 0; j--) { + kwLengthView[j] = kwLength; + kwLength >>= 8; + } + const eccInfo = new ECCCMSSharedInfo({ + keyInfo: new AlgorithmIdentifier({ + algorithmId: aesKWAlgorithm.algorithmId + }), + entityUInfo: recipientInfo.ukm, + suppPubInfo: new OctetString({ valueHex: kwLengthBuffer }) + }); + const encodedInfo = eccInfo.toSchema().toBER(false); + const ecdhAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "ecdhAlgorithm"); + const derivedKeyRaw = await kdf(ecdhAlgorithm.kdf, derivedBits, kwAlgorithm.length, encodedInfo, crypto); + const awsKW = await crypto.importKey("raw", derivedKeyRaw, { name: "AES-KW" }, true, ["wrapKey"]); + const wrappedKey = await crypto.wrapKey("raw", sessionKey, awsKW, { name: "AES-KW" }); + const originator = new OriginatorIdentifierOrKey(); + originator.variant = 3; + originator.value = OriginatorPublicKey.fromBER(exportedECDHPublicKey); + recipientInfo.originator = originator; + recipientInfo.recipientEncryptedKeys.encryptedKeys[0].encryptedKey = new OctetString({ valueHex: wrappedKey }); + return { ecdhPrivateKey: ecdhKeys.privateKey }; + }; + const SubKeyTransRecipientInfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + const algorithmParameters = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "keyEncryptionAlgorithm"); + if (algorithmParameters.name === "RSA-OAEP") { + const schema = recipientInfo.keyEncryptionAlgorithm.algorithmParams; + const rsaOAEPParams = new RSAESOAEPParams({ schema }); + algorithmParameters.hash = crypto.getAlgorithmByOID(rsaOAEPParams.hashAlgorithm.algorithmId); + if (("name" in algorithmParameters.hash) === false) + throw new Error(`Incorrect OID for hash algorithm: ${rsaOAEPParams.hashAlgorithm.algorithmId}`); + } + try { + const publicKey = await recipientInfo.recipientCertificate.getPublicKey({ + algorithm: { + algorithm: algorithmParameters, + usages: ["encrypt", "wrapKey"] + } + }, crypto); + const encryptedKey = await crypto.encrypt(publicKey.algorithm, publicKey, exportedSessionKey); + recipientInfo.encryptedKey = new OctetString({ valueHex: encryptedKey }); + } + catch { + } + }; + const SubKEKRecipientInfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "kekAlgorithm"); + const kekKey = await crypto.importKey("raw", new Uint8Array(recipientInfo.preDefinedKEK), kekAlgorithm, true, ["wrapKey"]); + const wrappedKey = await crypto.wrapKey("raw", sessionKey, kekKey, kekAlgorithm); + recipientInfo.encryptedKey = new OctetString({ valueHex: wrappedKey }); + }; + const SubPasswordRecipientinfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + let pbkdf2Params; + if (!recipientInfo.keyDerivationAlgorithm) + throw new Error("Please append encoded \"keyDerivationAlgorithm\""); + if (!recipientInfo.keyDerivationAlgorithm.algorithmParams) + throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); + try { + pbkdf2Params = new PBKDF2Params({ schema: recipientInfo.keyDerivationAlgorithm.algorithmParams }); + } + catch { + throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); + } + const passwordView = new Uint8Array(recipientInfo.password); + const derivationKey = await crypto.importKey("raw", passwordView, "PBKDF2", false, ["deriveKey"]); + const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "kekAlgorithm"); + let hmacHashAlgorithm = "SHA-1"; + if (pbkdf2Params.prf) { + const prfAlgorithm = crypto.getAlgorithmByOID(pbkdf2Params.prf.algorithmId, true, "prfAlgorithm"); + hmacHashAlgorithm = prfAlgorithm.hash.name; + } + const saltView = new Uint8Array(pbkdf2Params.salt.valueBlock.valueHex); + const iterations = pbkdf2Params.iterationCount; + const derivedKey = await crypto.deriveKey({ + name: "PBKDF2", + hash: { + name: hmacHashAlgorithm + }, + salt: saltView, + iterations + }, derivationKey, kekAlgorithm, true, ["wrapKey"]); + const wrappedKey = await crypto.wrapKey("raw", sessionKey, derivedKey, kekAlgorithm); + recipientInfo.encryptedKey = new OctetString({ valueHex: wrappedKey }); + }; + const res = []; + for (let i = 0; i < this.recipientInfos.length; i++) { + switch (this.recipientInfos[i].variant) { + case 1: + res.push(await SubKeyTransRecipientInfo(i)); + break; + case 2: + res.push(await SubKeyAgreeRecipientInfo(i)); + break; + case 3: + res.push(await SubKEKRecipientInfo(i)); + break; + case 4: + res.push(await SubPasswordRecipientinfo(i)); + break; + default: + throw new Error(`Unknown recipient type in array with index ${i}`); + } + } + return res; + } + async decrypt(recipientIndex, parameters, crypto = getCrypto(true)) { + const decryptionParameters = parameters || {}; + if ((recipientIndex + 1) > this.recipientInfos.length) { + throw new Error(`Maximum value for "index" is: ${this.recipientInfos.length - 1}`); + } + const SubKeyAgreeRecipientInfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + let curveOID; + let recipientCurve; + let recipientCurveLength; + const originator = recipientInfo.originator; + if (decryptionParameters.recipientCertificate) { + const curveObject = decryptionParameters.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams; + if (curveObject.constructor.blockName() !== ObjectIdentifier.blockName()) { + throw new Error(`Incorrect "recipientCertificate" for index ${index}`); + } + curveOID = curveObject.valueBlock.toString(); + } + else if (originator.value.algorithm.algorithmParams) { + const curveObject = originator.value.algorithm.algorithmParams; + if (curveObject.constructor.blockName() !== ObjectIdentifier.blockName()) { + throw new Error(`Incorrect originator for index ${index}`); + } + curveOID = curveObject.valueBlock.toString(); + } + else { + throw new Error("Parameter \"recipientCertificate\" is mandatory for \"KeyAgreeRecipientInfo\" if algorithm params are missing from originator"); + } + if (!decryptionParameters.recipientPrivateKey) + throw new Error("Parameter \"recipientPrivateKey\" is mandatory for \"KeyAgreeRecipientInfo\""); + switch (curveOID) { + case "1.2.840.10045.3.1.7": + recipientCurve = "P-256"; + recipientCurveLength = 256; + break; + case "1.3.132.0.34": + recipientCurve = "P-384"; + recipientCurveLength = 384; + break; + case "1.3.132.0.35": + recipientCurve = "P-521"; + recipientCurveLength = 528; + break; + default: + throw new Error(`Incorrect curve OID for index ${index}`); + } + let ecdhPrivateKey; + let keyCrypto = crypto; + if (BufferSourceConverter.isBufferSource(decryptionParameters.recipientPrivateKey)) { + ecdhPrivateKey = await crypto.importKey("pkcs8", decryptionParameters.recipientPrivateKey, { + name: "ECDH", + namedCurve: recipientCurve + }, true, ["deriveBits"]); + } + else { + ecdhPrivateKey = decryptionParameters.recipientPrivateKey; + if ("crypto" in decryptionParameters && decryptionParameters.crypto) { + keyCrypto = decryptionParameters.crypto.subtle; + } + } + if (("algorithmParams" in originator.value.algorithm) === false) + originator.value.algorithm.algorithmParams = new ObjectIdentifier({ value: curveOID }); + const buffer = originator.value.toSchema().toBER(false); + const ecdhPublicKey = await crypto.importKey("spki", buffer, { + name: "ECDH", + namedCurve: recipientCurve + }, true, []); + const sharedSecret = await keyCrypto.deriveBits({ + name: "ECDH", + public: ecdhPublicKey + }, ecdhPrivateKey, recipientCurveLength); + async function applyKDF(includeAlgorithmParams) { + includeAlgorithmParams = includeAlgorithmParams || false; + const aesKWAlgorithm = new AlgorithmIdentifier({ schema: recipientInfo.keyEncryptionAlgorithm.algorithmParams }); + const kwAlgorithm = crypto.getAlgorithmByOID(aesKWAlgorithm.algorithmId, true, "kwAlgorithm"); + let kwLength = kwAlgorithm.length; + const kwLengthBuffer = new ArrayBuffer(4); + const kwLengthView = new Uint8Array(kwLengthBuffer); + for (let j = 3; j >= 0; j--) { + kwLengthView[j] = kwLength; + kwLength >>= 8; + } + const keyInfoAlgorithm = { + algorithmId: aesKWAlgorithm.algorithmId + }; + if (includeAlgorithmParams) { + keyInfoAlgorithm.algorithmParams = new Null(); + } + const eccInfo = new ECCCMSSharedInfo({ + keyInfo: new AlgorithmIdentifier(keyInfoAlgorithm), + entityUInfo: recipientInfo.ukm, + suppPubInfo: new OctetString({ valueHex: kwLengthBuffer }) + }); + const encodedInfo = eccInfo.toSchema().toBER(false); + const ecdhAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "ecdhAlgorithm"); + if (!ecdhAlgorithm.name) { + throw new Error(`Incorrect OID for key encryption algorithm: ${recipientInfo.keyEncryptionAlgorithm.algorithmId}`); + } + return kdf(ecdhAlgorithm.kdf, sharedSecret, kwAlgorithm.length, encodedInfo, crypto); + } + const kdfResult = await applyKDF(); + const importAesKwKey = async (kdfResult) => { + return crypto.importKey("raw", kdfResult, { name: "AES-KW" }, true, ["unwrapKey"]); + }; + const aesKwKey = await importAesKwKey(kdfResult); + const unwrapSessionKey = async (aesKwKey) => { + const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; + const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); + return crypto.unwrapKey("raw", recipientInfo.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView, aesKwKey, { name: "AES-KW" }, contentEncryptionAlgorithm, true, ["decrypt"]); + }; + try { + return await unwrapSessionKey(aesKwKey); + } + catch { + const kdfResult = await applyKDF(true); + const aesKwKey = await importAesKwKey(kdfResult); + return unwrapSessionKey(aesKwKey); + } + }; + const SubKeyTransRecipientInfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + if (!decryptionParameters.recipientPrivateKey) { + throw new Error("Parameter \"recipientPrivateKey\" is mandatory for \"KeyTransRecipientInfo\""); + } + const algorithmParameters = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "keyEncryptionAlgorithm"); + if (algorithmParameters.name === "RSA-OAEP") { + const schema = recipientInfo.keyEncryptionAlgorithm.algorithmParams; + const rsaOAEPParams = new RSAESOAEPParams({ schema }); + algorithmParameters.hash = crypto.getAlgorithmByOID(rsaOAEPParams.hashAlgorithm.algorithmId); + if (("name" in algorithmParameters.hash) === false) + throw new Error(`Incorrect OID for hash algorithm: ${rsaOAEPParams.hashAlgorithm.algorithmId}`); + } + let privateKey; + let keyCrypto = crypto; + if (BufferSourceConverter.isBufferSource(decryptionParameters.recipientPrivateKey)) { + privateKey = await crypto.importKey("pkcs8", decryptionParameters.recipientPrivateKey, algorithmParameters, true, ["decrypt"]); + } + else { + privateKey = decryptionParameters.recipientPrivateKey; + if ("crypto" in decryptionParameters && decryptionParameters.crypto) { + keyCrypto = decryptionParameters.crypto.subtle; + } + } + const sessionKey = await keyCrypto.decrypt(privateKey.algorithm, privateKey, recipientInfo.encryptedKey.valueBlock.valueHexView); + const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; + const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); + if (("name" in contentEncryptionAlgorithm) === false) + throw new Error(`Incorrect "contentEncryptionAlgorithm": ${algorithmId}`); + return crypto.importKey("raw", sessionKey, contentEncryptionAlgorithm, true, ["decrypt"]); + }; + const SubKEKRecipientInfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + if (!decryptionParameters.preDefinedData) + throw new Error("Parameter \"preDefinedData\" is mandatory for \"KEKRecipientInfo\""); + const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "kekAlgorithm"); + const importedKey = await crypto.importKey("raw", decryptionParameters.preDefinedData, kekAlgorithm, true, ["unwrapKey"]); + const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; + const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); + if (!contentEncryptionAlgorithm.name) { + throw new Error(`Incorrect "contentEncryptionAlgorithm": ${algorithmId}`); + } + return crypto.unwrapKey("raw", recipientInfo.encryptedKey.valueBlock.valueHexView, importedKey, kekAlgorithm, contentEncryptionAlgorithm, true, ["decrypt"]); + }; + const SubPasswordRecipientinfo = async (index) => { + const recipientInfo = this.recipientInfos[index].value; + let pbkdf2Params; + if (!decryptionParameters.preDefinedData) { + throw new Error("Parameter \"preDefinedData\" is mandatory for \"KEKRecipientInfo\""); + } + if (!recipientInfo.keyDerivationAlgorithm) { + throw new Error("Please append encoded \"keyDerivationAlgorithm\""); + } + if (!recipientInfo.keyDerivationAlgorithm.algorithmParams) { + throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); + } + try { + pbkdf2Params = new PBKDF2Params({ schema: recipientInfo.keyDerivationAlgorithm.algorithmParams }); + } + catch { + throw new Error("Incorrectly encoded \"keyDerivationAlgorithm\""); + } + const pbkdf2Key = await crypto.importKey("raw", decryptionParameters.preDefinedData, "PBKDF2", false, ["deriveKey"]); + const kekAlgorithm = crypto.getAlgorithmByOID(recipientInfo.keyEncryptionAlgorithm.algorithmId, true, "keyEncryptionAlgorithm"); + const hmacHashAlgorithm = pbkdf2Params.prf + ? crypto.getAlgorithmByOID(pbkdf2Params.prf.algorithmId, true, "prfAlgorithm").hash.name + : "SHA-1"; + const saltView = new Uint8Array(pbkdf2Params.salt.valueBlock.valueHex); + const iterations = pbkdf2Params.iterationCount; + const kekKey = await crypto.deriveKey({ + name: "PBKDF2", + hash: { + name: hmacHashAlgorithm + }, + salt: saltView, + iterations + }, pbkdf2Key, kekAlgorithm, true, ["unwrapKey"]); + const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; + const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); + return crypto.unwrapKey("raw", recipientInfo.encryptedKey.valueBlock.valueHexView, kekKey, kekAlgorithm, contentEncryptionAlgorithm, true, ["decrypt"]); + }; + let unwrappedKey; + switch (this.recipientInfos[recipientIndex].variant) { + case 1: + unwrappedKey = await SubKeyTransRecipientInfo(recipientIndex); + break; + case 2: + unwrappedKey = await SubKeyAgreeRecipientInfo(recipientIndex); + break; + case 3: + unwrappedKey = await SubKEKRecipientInfo(recipientIndex); + break; + case 4: + unwrappedKey = await SubPasswordRecipientinfo(recipientIndex); + break; + default: + throw new Error(`Unknown recipient type in array with index ${recipientIndex}`); + } + const algorithmId = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId; + const contentEncryptionAlgorithm = crypto.getAlgorithmByOID(algorithmId, true, "contentEncryptionAlgorithm"); + const ivBuffer = this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams.valueBlock.valueHex; + const ivView = new Uint8Array(ivBuffer); + if (!this.encryptedContentInfo.encryptedContent) { + throw new Error("Required property `encryptedContent` is empty"); + } + const dataBuffer = this.encryptedContentInfo.getEncryptedContent(); + return crypto.decrypt({ + name: contentEncryptionAlgorithm.name, + iv: ivView + }, unwrappedKey, dataBuffer); + } +} EnvelopedData.CLASS_NAME = "EnvelopedData"; -const SAFE_CONTENTS = "safeContents"; -const PARSED_VALUE$1 = "parsedValue"; -const CONTENT_INFOS = "contentInfos"; -class AuthenticatedSafe extends PkiObject { - constructor(parameters = {}) { - super(); - this.safeContents = getParametersValue(parameters, SAFE_CONTENTS, AuthenticatedSafe.defaultValues(SAFE_CONTENTS)); - if (PARSED_VALUE$1 in parameters) { - this.parsedValue = getParametersValue(parameters, PARSED_VALUE$1, AuthenticatedSafe.defaultValues(PARSED_VALUE$1)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case SAFE_CONTENTS: - return []; - case PARSED_VALUE$1: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case SAFE_CONTENTS: - return (memberValue.length === 0); - case PARSED_VALUE$1: - return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Repeated({ - name: (names.contentInfos || EMPTY_STRING), - value: ContentInfo.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - CONTENT_INFOS - ]); - const asn1 = compareSchema(schema, schema, AuthenticatedSafe.schema({ - names: { - contentInfos: CONTENT_INFOS - } - })); - AsnError.assertSchema(asn1, this.className); - this.safeContents = Array.from(asn1.result.contentInfos, element => new ContentInfo({ schema: element })); - } - toSchema() { - return (new Sequence({ - value: Array.from(this.safeContents, o => o.toSchema()) - })); - } - toJSON() { - return { - safeContents: Array.from(this.safeContents, o => o.toJSON()) - }; - } - parseInternalValues(parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - ParameterError.assert(parameters, SAFE_CONTENTS); - ArgumentError.assert(parameters.safeContents, SAFE_CONTENTS, "Array"); - if (parameters.safeContents.length !== this.safeContents.length) { - throw new ArgumentError("Length of \"parameters.safeContents\" must be equal to \"this.safeContents.length\""); - } - this.parsedValue = { - safeContents: [], - }; - for (const [index, content] of this.safeContents.entries()) { - const safeContent = parameters.safeContents[index]; - const errorTarget = `parameters.safeContents[${index}]`; - switch (content.contentType) { - case id_ContentType_Data: - { - ArgumentError.assert(content.content, "this.safeContents[j].content", OctetString); - const authSafeContent = content.content.getValue(); - this.parsedValue.safeContents.push({ - privacyMode: 0, - value: SafeContents.fromBER(authSafeContent) - }); - } - break; - case id_ContentType_EnvelopedData: - { - const cmsEnveloped = new EnvelopedData({ schema: content.content }); - ParameterError.assert(errorTarget, safeContent, "recipientCertificate", "recipientKey"); - const envelopedData = safeContent; - const recipientCertificate = envelopedData.recipientCertificate; - const recipientKey = envelopedData.recipientKey; - const decrypted = yield cmsEnveloped.decrypt(0, { - recipientCertificate, - recipientPrivateKey: recipientKey - }, crypto); - this.parsedValue.safeContents.push({ - privacyMode: 2, - value: SafeContents.fromBER(decrypted), - }); - } - break; - case id_ContentType_EncryptedData: - { - const cmsEncrypted = new EncryptedData({ schema: content.content }); - ParameterError.assert(errorTarget, safeContent, "password"); - const password = safeContent.password; - const decrypted = yield cmsEncrypted.decrypt({ - password - }, crypto); - this.parsedValue.safeContents.push({ - privacyMode: 1, - value: SafeContents.fromBER(decrypted), - }); - } - break; - default: - throw new Error(`Unknown "contentType" for AuthenticatedSafe: " ${content.contentType}`); - } - } - }); - } - makeInternalValues(parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - if (!(this.parsedValue)) { - throw new Error("Please run \"parseValues\" first or add \"parsedValue\" manually"); - } - ArgumentError.assert(this.parsedValue, "this.parsedValue", "object"); - ArgumentError.assert(this.parsedValue.safeContents, "this.parsedValue.safeContents", "Array"); - ArgumentError.assert(parameters, "parameters", "object"); - ParameterError.assert(parameters, "safeContents"); - ArgumentError.assert(parameters.safeContents, "parameters.safeContents", "Array"); - if (parameters.safeContents.length !== this.parsedValue.safeContents.length) { - throw new ArgumentError("Length of \"parameters.safeContents\" must be equal to \"this.parsedValue.safeContents\""); - } - this.safeContents = []; - for (const [index, content] of this.parsedValue.safeContents.entries()) { - ParameterError.assert("content", content, "privacyMode", "value"); - ArgumentError.assert(content.value, "content.value", SafeContents); - switch (content.privacyMode) { - case 0: - { - const contentBuffer = content.value.toSchema().toBER(false); - this.safeContents.push(new ContentInfo({ - contentType: "1.2.840.113549.1.7.1", - content: new OctetString({ valueHex: contentBuffer }) - })); - } - break; - case 1: - { - const cmsEncrypted = new EncryptedData(); - const currentParameters = parameters.safeContents[index]; - currentParameters.contentToEncrypt = content.value.toSchema().toBER(false); - yield cmsEncrypted.encrypt(currentParameters); - this.safeContents.push(new ContentInfo({ - contentType: "1.2.840.113549.1.7.6", - content: cmsEncrypted.toSchema() - })); - } - break; - case 2: - { - const cmsEnveloped = new EnvelopedData(); - const contentToEncrypt = content.value.toSchema().toBER(false); - const safeContent = parameters.safeContents[index]; - ParameterError.assert(`parameters.safeContents[${index}]`, safeContent, "encryptingCertificate", "encryptionAlgorithm"); - switch (true) { - case (safeContent.encryptionAlgorithm.name.toLowerCase() === "aes-cbc"): - case (safeContent.encryptionAlgorithm.name.toLowerCase() === "aes-gcm"): - break; - default: - throw new Error(`Incorrect parameter "encryptionAlgorithm" in "parameters.safeContents[i]": ${safeContent.encryptionAlgorithm}`); - } - switch (true) { - case (safeContent.encryptionAlgorithm.length === 128): - case (safeContent.encryptionAlgorithm.length === 192): - case (safeContent.encryptionAlgorithm.length === 256): - break; - default: - throw new Error(`Incorrect parameter "encryptionAlgorithm.length" in "parameters.safeContents[i]": ${safeContent.encryptionAlgorithm.length}`); - } - const encryptionAlgorithm = safeContent.encryptionAlgorithm; - cmsEnveloped.addRecipientByCertificate(safeContent.encryptingCertificate, {}, undefined, crypto); - yield cmsEnveloped.encrypt(encryptionAlgorithm, contentToEncrypt, crypto); - this.safeContents.push(new ContentInfo({ - contentType: "1.2.840.113549.1.7.3", - content: cmsEnveloped.toSchema() - })); - } - break; - default: - throw new Error(`Incorrect value for "content.privacyMode": ${content.privacyMode}`); - } - } - return this; - }); - } -} +const SAFE_CONTENTS = "safeContents"; +const PARSED_VALUE$1 = "parsedValue"; +const CONTENT_INFOS = "contentInfos"; +class AuthenticatedSafe extends PkiObject { + constructor(parameters = {}) { + super(); + this.safeContents = getParametersValue(parameters, SAFE_CONTENTS, AuthenticatedSafe.defaultValues(SAFE_CONTENTS)); + if (PARSED_VALUE$1 in parameters) { + this.parsedValue = getParametersValue(parameters, PARSED_VALUE$1, AuthenticatedSafe.defaultValues(PARSED_VALUE$1)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case SAFE_CONTENTS: + return []; + case PARSED_VALUE$1: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case SAFE_CONTENTS: + return (memberValue.length === 0); + case PARSED_VALUE$1: + return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Repeated({ + name: (names.contentInfos || EMPTY_STRING), + value: ContentInfo.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + CONTENT_INFOS + ]); + const asn1 = compareSchema(schema, schema, AuthenticatedSafe.schema({ + names: { + contentInfos: CONTENT_INFOS + } + })); + AsnError.assertSchema(asn1, this.className); + this.safeContents = Array.from(asn1.result.contentInfos, element => new ContentInfo({ schema: element })); + } + toSchema() { + return (new Sequence({ + value: Array.from(this.safeContents, o => o.toSchema()) + })); + } + toJSON() { + return { + safeContents: Array.from(this.safeContents, o => o.toJSON()) + }; + } + async parseInternalValues(parameters, crypto = getCrypto(true)) { + ParameterError.assert(parameters, SAFE_CONTENTS); + ArgumentError.assert(parameters.safeContents, SAFE_CONTENTS, "Array"); + if (parameters.safeContents.length !== this.safeContents.length) { + throw new ArgumentError("Length of \"parameters.safeContents\" must be equal to \"this.safeContents.length\""); + } + this.parsedValue = { + safeContents: [], + }; + for (const [index, content] of this.safeContents.entries()) { + const safeContent = parameters.safeContents[index]; + const errorTarget = `parameters.safeContents[${index}]`; + switch (content.contentType) { + case id_ContentType_Data: + { + ArgumentError.assert(content.content, "this.safeContents[j].content", OctetString); + const authSafeContent = content.content.getValue(); + this.parsedValue.safeContents.push({ + privacyMode: 0, + value: SafeContents.fromBER(authSafeContent) + }); + } + break; + case id_ContentType_EnvelopedData: + { + const cmsEnveloped = new EnvelopedData({ schema: content.content }); + ParameterError.assert(errorTarget, safeContent, "recipientCertificate", "recipientKey"); + const envelopedData = safeContent; + const recipientCertificate = envelopedData.recipientCertificate; + const recipientKey = envelopedData.recipientKey; + const decrypted = await cmsEnveloped.decrypt(0, { + recipientCertificate, + recipientPrivateKey: recipientKey + }, crypto); + this.parsedValue.safeContents.push({ + privacyMode: 2, + value: SafeContents.fromBER(decrypted), + }); + } + break; + case id_ContentType_EncryptedData: + { + const cmsEncrypted = new EncryptedData({ schema: content.content }); + ParameterError.assert(errorTarget, safeContent, "password"); + const password = safeContent.password; + const decrypted = await cmsEncrypted.decrypt({ + password + }, crypto); + this.parsedValue.safeContents.push({ + privacyMode: 1, + value: SafeContents.fromBER(decrypted), + }); + } + break; + default: + throw new Error(`Unknown "contentType" for AuthenticatedSafe: " ${content.contentType}`); + } + } + } + async makeInternalValues(parameters, crypto = getCrypto(true)) { + if (!(this.parsedValue)) { + throw new Error("Please run \"parseValues\" first or add \"parsedValue\" manually"); + } + ArgumentError.assert(this.parsedValue, "this.parsedValue", "object"); + ArgumentError.assert(this.parsedValue.safeContents, "this.parsedValue.safeContents", "Array"); + ArgumentError.assert(parameters, "parameters", "object"); + ParameterError.assert(parameters, "safeContents"); + ArgumentError.assert(parameters.safeContents, "parameters.safeContents", "Array"); + if (parameters.safeContents.length !== this.parsedValue.safeContents.length) { + throw new ArgumentError("Length of \"parameters.safeContents\" must be equal to \"this.parsedValue.safeContents\""); + } + this.safeContents = []; + for (const [index, content] of this.parsedValue.safeContents.entries()) { + ParameterError.assert("content", content, "privacyMode", "value"); + ArgumentError.assert(content.value, "content.value", SafeContents); + switch (content.privacyMode) { + case 0: + { + const contentBuffer = content.value.toSchema().toBER(false); + this.safeContents.push(new ContentInfo({ + contentType: "1.2.840.113549.1.7.1", + content: new OctetString({ valueHex: contentBuffer }) + })); + } + break; + case 1: + { + const cmsEncrypted = new EncryptedData(); + const currentParameters = parameters.safeContents[index]; + currentParameters.contentToEncrypt = content.value.toSchema().toBER(false); + await cmsEncrypted.encrypt(currentParameters, crypto); + this.safeContents.push(new ContentInfo({ + contentType: "1.2.840.113549.1.7.6", + content: cmsEncrypted.toSchema() + })); + } + break; + case 2: + { + const cmsEnveloped = new EnvelopedData(); + const contentToEncrypt = content.value.toSchema().toBER(false); + const safeContent = parameters.safeContents[index]; + ParameterError.assert(`parameters.safeContents[${index}]`, safeContent, "encryptingCertificate", "encryptionAlgorithm"); + switch (true) { + case (safeContent.encryptionAlgorithm.name.toLowerCase() === "aes-cbc"): + case (safeContent.encryptionAlgorithm.name.toLowerCase() === "aes-gcm"): + break; + default: + throw new Error(`Incorrect parameter "encryptionAlgorithm" in "parameters.safeContents[i]": ${safeContent.encryptionAlgorithm}`); + } + switch (true) { + case (safeContent.encryptionAlgorithm.length === 128): + case (safeContent.encryptionAlgorithm.length === 192): + case (safeContent.encryptionAlgorithm.length === 256): + break; + default: + throw new Error(`Incorrect parameter "encryptionAlgorithm.length" in "parameters.safeContents[i]": ${safeContent.encryptionAlgorithm.length}`); + } + const encryptionAlgorithm = safeContent.encryptionAlgorithm; + cmsEnveloped.addRecipientByCertificate(safeContent.encryptingCertificate, {}, undefined, crypto); + await cmsEnveloped.encrypt(encryptionAlgorithm, contentToEncrypt, crypto); + this.safeContents.push(new ContentInfo({ + contentType: "1.2.840.113549.1.7.3", + content: cmsEnveloped.toSchema() + })); + } + break; + default: + throw new Error(`Incorrect value for "content.privacyMode": ${content.privacyMode}`); + } + } + return this; + } +} AuthenticatedSafe.CLASS_NAME = "AuthenticatedSafe"; -const HASH_ALGORITHM$1 = "hashAlgorithm"; -const ISSUER_NAME_HASH = "issuerNameHash"; -const ISSUER_KEY_HASH = "issuerKeyHash"; -const SERIAL_NUMBER$1 = "serialNumber"; -const CLEAR_PROPS$j = [ - HASH_ALGORITHM$1, - ISSUER_NAME_HASH, - ISSUER_KEY_HASH, - SERIAL_NUMBER$1, -]; -class CertID extends PkiObject { - constructor(parameters = {}) { - super(); - this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$1, CertID.defaultValues(HASH_ALGORITHM$1)); - this.issuerNameHash = getParametersValue(parameters, ISSUER_NAME_HASH, CertID.defaultValues(ISSUER_NAME_HASH)); - this.issuerKeyHash = getParametersValue(parameters, ISSUER_KEY_HASH, CertID.defaultValues(ISSUER_KEY_HASH)); - this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$1, CertID.defaultValues(SERIAL_NUMBER$1)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static create(certificate, parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const certID = new CertID(); - yield certID.createForCertificate(certificate, parameters, crypto); - return certID; - }); - } - static defaultValues(memberName) { - switch (memberName) { - case HASH_ALGORITHM$1: - return new AlgorithmIdentifier(); - case ISSUER_NAME_HASH: - case ISSUER_KEY_HASH: - return new OctetString(); - case SERIAL_NUMBER$1: - return new Integer(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case HASH_ALGORITHM$1: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case ISSUER_NAME_HASH: - case ISSUER_KEY_HASH: - case SERIAL_NUMBER$1: - return (memberValue.isEqual(CertID.defaultValues(SERIAL_NUMBER$1))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.hashAlgorithmObject || { - names: { - blockName: (names.hashAlgorithm || EMPTY_STRING) - } - }), - new OctetString({ name: (names.issuerNameHash || EMPTY_STRING) }), - new OctetString({ name: (names.issuerKeyHash || EMPTY_STRING) }), - new Integer({ name: (names.serialNumber || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$j); - const asn1 = compareSchema(schema, schema, CertID.schema({ - names: { - hashAlgorithm: HASH_ALGORITHM$1, - issuerNameHash: ISSUER_NAME_HASH, - issuerKeyHash: ISSUER_KEY_HASH, - serialNumber: SERIAL_NUMBER$1 - } - })); - AsnError.assertSchema(asn1, this.className); - this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); - this.issuerNameHash = asn1.result.issuerNameHash; - this.issuerKeyHash = asn1.result.issuerKeyHash; - this.serialNumber = asn1.result.serialNumber; - } - toSchema() { - return (new Sequence({ - value: [ - this.hashAlgorithm.toSchema(), - this.issuerNameHash, - this.issuerKeyHash, - this.serialNumber - ] - })); - } - toJSON() { - return { - hashAlgorithm: this.hashAlgorithm.toJSON(), - issuerNameHash: this.issuerNameHash.toJSON(), - issuerKeyHash: this.issuerKeyHash.toJSON(), - serialNumber: this.serialNumber.toJSON(), - }; - } - isEqual(certificateID) { - if (this.hashAlgorithm.algorithmId !== certificateID.hashAlgorithm.algorithmId) { - return false; - } - if (!BufferSourceConverter.isEqual(this.issuerNameHash.valueBlock.valueHexView, certificateID.issuerNameHash.valueBlock.valueHexView)) { - return false; - } - if (!BufferSourceConverter.isEqual(this.issuerKeyHash.valueBlock.valueHexView, certificateID.issuerKeyHash.valueBlock.valueHexView)) { - return false; - } - if (!this.serialNumber.isEqual(certificateID.serialNumber)) { - return false; - } - return true; - } - createForCertificate(certificate, parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - ParameterError.assert(parameters, HASH_ALGORITHM$1, "issuerCertificate"); - const hashOID = crypto.getOIDByAlgorithm({ name: parameters.hashAlgorithm }, true, "hashAlgorithm"); - this.hashAlgorithm = new AlgorithmIdentifier({ - algorithmId: hashOID, - algorithmParams: new Null() - }); - const issuerCertificate = parameters.issuerCertificate; - this.serialNumber = certificate.serialNumber; - const hashIssuerName = yield crypto.digest({ name: parameters.hashAlgorithm }, issuerCertificate.subject.toSchema().toBER(false)); - this.issuerNameHash = new OctetString({ valueHex: hashIssuerName }); - const issuerKeyBuffer = issuerCertificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView; - const hashIssuerKey = yield crypto.digest({ name: parameters.hashAlgorithm }, issuerKeyBuffer); - this.issuerKeyHash = new OctetString({ valueHex: hashIssuerKey }); - }); - } -} +const HASH_ALGORITHM$1 = "hashAlgorithm"; +const ISSUER_NAME_HASH = "issuerNameHash"; +const ISSUER_KEY_HASH = "issuerKeyHash"; +const SERIAL_NUMBER$1 = "serialNumber"; +const CLEAR_PROPS$j = [ + HASH_ALGORITHM$1, + ISSUER_NAME_HASH, + ISSUER_KEY_HASH, + SERIAL_NUMBER$1, +]; +class CertID extends PkiObject { + static async create(certificate, parameters, crypto = getCrypto(true)) { + const certID = new CertID(); + await certID.createForCertificate(certificate, parameters, crypto); + return certID; + } + constructor(parameters = {}) { + super(); + this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM$1, CertID.defaultValues(HASH_ALGORITHM$1)); + this.issuerNameHash = getParametersValue(parameters, ISSUER_NAME_HASH, CertID.defaultValues(ISSUER_NAME_HASH)); + this.issuerKeyHash = getParametersValue(parameters, ISSUER_KEY_HASH, CertID.defaultValues(ISSUER_KEY_HASH)); + this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER$1, CertID.defaultValues(SERIAL_NUMBER$1)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case HASH_ALGORITHM$1: + return new AlgorithmIdentifier(); + case ISSUER_NAME_HASH: + case ISSUER_KEY_HASH: + return new OctetString(); + case SERIAL_NUMBER$1: + return new Integer(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case HASH_ALGORITHM$1: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case ISSUER_NAME_HASH: + case ISSUER_KEY_HASH: + case SERIAL_NUMBER$1: + return (memberValue.isEqual(CertID.defaultValues(SERIAL_NUMBER$1))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.hashAlgorithmObject || { + names: { + blockName: (names.hashAlgorithm || EMPTY_STRING) + } + }), + new OctetString({ name: (names.issuerNameHash || EMPTY_STRING) }), + new OctetString({ name: (names.issuerKeyHash || EMPTY_STRING) }), + new Integer({ name: (names.serialNumber || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$j); + const asn1 = compareSchema(schema, schema, CertID.schema({ + names: { + hashAlgorithm: HASH_ALGORITHM$1, + issuerNameHash: ISSUER_NAME_HASH, + issuerKeyHash: ISSUER_KEY_HASH, + serialNumber: SERIAL_NUMBER$1 + } + })); + AsnError.assertSchema(asn1, this.className); + this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); + this.issuerNameHash = asn1.result.issuerNameHash; + this.issuerKeyHash = asn1.result.issuerKeyHash; + this.serialNumber = asn1.result.serialNumber; + } + toSchema() { + return (new Sequence({ + value: [ + this.hashAlgorithm.toSchema(), + this.issuerNameHash, + this.issuerKeyHash, + this.serialNumber + ] + })); + } + toJSON() { + return { + hashAlgorithm: this.hashAlgorithm.toJSON(), + issuerNameHash: this.issuerNameHash.toJSON(), + issuerKeyHash: this.issuerKeyHash.toJSON(), + serialNumber: this.serialNumber.toJSON(), + }; + } + isEqual(certificateID) { + if (this.hashAlgorithm.algorithmId !== certificateID.hashAlgorithm.algorithmId) { + return false; + } + if (!BufferSourceConverter.isEqual(this.issuerNameHash.valueBlock.valueHexView, certificateID.issuerNameHash.valueBlock.valueHexView)) { + return false; + } + if (!BufferSourceConverter.isEqual(this.issuerKeyHash.valueBlock.valueHexView, certificateID.issuerKeyHash.valueBlock.valueHexView)) { + return false; + } + if (!this.serialNumber.isEqual(certificateID.serialNumber)) { + return false; + } + return true; + } + async createForCertificate(certificate, parameters, crypto = getCrypto(true)) { + ParameterError.assert(parameters, HASH_ALGORITHM$1, "issuerCertificate"); + const hashOID = crypto.getOIDByAlgorithm({ name: parameters.hashAlgorithm }, true, "hashAlgorithm"); + this.hashAlgorithm = new AlgorithmIdentifier({ + algorithmId: hashOID, + algorithmParams: new Null() + }); + const issuerCertificate = parameters.issuerCertificate; + this.serialNumber = certificate.serialNumber; + const hashIssuerName = await crypto.digest({ name: parameters.hashAlgorithm }, issuerCertificate.subject.toSchema().toBER(false)); + this.issuerNameHash = new OctetString({ valueHex: hashIssuerName }); + const issuerKeyBuffer = issuerCertificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView; + const hashIssuerKey = await crypto.digest({ name: parameters.hashAlgorithm }, issuerKeyBuffer); + this.issuerKeyHash = new OctetString({ valueHex: hashIssuerKey }); + } +} CertID.CLASS_NAME = "CertID"; -const CERT_ID = "certID"; -const CERT_STATUS = "certStatus"; -const THIS_UPDATE = "thisUpdate"; -const NEXT_UPDATE = "nextUpdate"; -const SINGLE_EXTENSIONS = "singleExtensions"; -const CLEAR_PROPS$i = [ - CERT_ID, - CERT_STATUS, - THIS_UPDATE, - NEXT_UPDATE, - SINGLE_EXTENSIONS, -]; -class SingleResponse extends PkiObject { - constructor(parameters = {}) { - super(); - this.certID = getParametersValue(parameters, CERT_ID, SingleResponse.defaultValues(CERT_ID)); - this.certStatus = getParametersValue(parameters, CERT_STATUS, SingleResponse.defaultValues(CERT_STATUS)); - this.thisUpdate = getParametersValue(parameters, THIS_UPDATE, SingleResponse.defaultValues(THIS_UPDATE)); - if (NEXT_UPDATE in parameters) { - this.nextUpdate = getParametersValue(parameters, NEXT_UPDATE, SingleResponse.defaultValues(NEXT_UPDATE)); - } - if (SINGLE_EXTENSIONS in parameters) { - this.singleExtensions = getParametersValue(parameters, SINGLE_EXTENSIONS, SingleResponse.defaultValues(SINGLE_EXTENSIONS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case CERT_ID: - return new CertID(); - case CERT_STATUS: - return {}; - case THIS_UPDATE: - case NEXT_UPDATE: - return new Date(0, 0, 0); - case SINGLE_EXTENSIONS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case CERT_ID: - return ((CertID.compareWithDefault("hashAlgorithm", memberValue.hashAlgorithm)) && - (CertID.compareWithDefault("issuerNameHash", memberValue.issuerNameHash)) && - (CertID.compareWithDefault("issuerKeyHash", memberValue.issuerKeyHash)) && - (CertID.compareWithDefault("serialNumber", memberValue.serialNumber))); - case CERT_STATUS: - return (Object.keys(memberValue).length === 0); - case THIS_UPDATE: - case NEXT_UPDATE: - return (memberValue === SingleResponse.defaultValues(memberName)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - CertID.schema(names.certID || {}), - new Choice({ - value: [ - new Primitive({ - name: (names.certStatus || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - }), - new Constructed({ - name: (names.certStatus || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new GeneralizedTime(), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Enumerated()] - }) - ] - }), - new Primitive({ - name: (names.certStatus || EMPTY_STRING), - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - lenBlock: { length: 1 } - }) - ] - }), - new GeneralizedTime({ name: (names.thisUpdate || EMPTY_STRING) }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new GeneralizedTime({ name: (names.nextUpdate || EMPTY_STRING) })] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [Extensions.schema(names.singleExtensions || {})] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$i); - const asn1 = compareSchema(schema, schema, SingleResponse.schema({ - names: { - certID: { - names: { - blockName: CERT_ID - } - }, - certStatus: CERT_STATUS, - thisUpdate: THIS_UPDATE, - nextUpdate: NEXT_UPDATE, - singleExtensions: { - names: { - blockName: SINGLE_EXTENSIONS - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.certID = new CertID({ schema: asn1.result.certID }); - this.certStatus = asn1.result.certStatus; - this.thisUpdate = asn1.result.thisUpdate.toDate(); - if (NEXT_UPDATE in asn1.result) - this.nextUpdate = asn1.result.nextUpdate.toDate(); - if (SINGLE_EXTENSIONS in asn1.result) - this.singleExtensions = Array.from(asn1.result.singleExtensions.valueBlock.value, element => new Extension({ schema: element })); - } - toSchema() { - const outputArray = []; - outputArray.push(this.certID.toSchema()); - outputArray.push(this.certStatus); - outputArray.push(new GeneralizedTime({ valueDate: this.thisUpdate })); - if (this.nextUpdate) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new GeneralizedTime({ valueDate: this.nextUpdate })] - })); - } - if (this.singleExtensions) { - outputArray.push(new Sequence({ - value: Array.from(this.singleExtensions, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - certID: this.certID.toJSON(), - certStatus: this.certStatus.toJSON(), - thisUpdate: this.thisUpdate - }; - if (this.nextUpdate) { - res.nextUpdate = this.nextUpdate; - } - if (this.singleExtensions) { - res.singleExtensions = Array.from(this.singleExtensions, o => o.toJSON()); - } - return res; - } -} -SingleResponse.CLASS_NAME = "SingleResponse"; - -const TBS$2 = "tbs"; -const VERSION$7 = "version"; -const RESPONDER_ID = "responderID"; -const PRODUCED_AT = "producedAt"; -const RESPONSES = "responses"; -const RESPONSE_EXTENSIONS = "responseExtensions"; -const RESPONSE_DATA = "ResponseData"; -const RESPONSE_DATA_VERSION = `${RESPONSE_DATA}.${VERSION$7}`; -const RESPONSE_DATA_RESPONDER_ID = `${RESPONSE_DATA}.${RESPONDER_ID}`; -const RESPONSE_DATA_PRODUCED_AT = `${RESPONSE_DATA}.${PRODUCED_AT}`; -const RESPONSE_DATA_RESPONSES = `${RESPONSE_DATA}.${RESPONSES}`; -const RESPONSE_DATA_RESPONSE_EXTENSIONS = `${RESPONSE_DATA}.${RESPONSE_EXTENSIONS}`; -const CLEAR_PROPS$h = [ - RESPONSE_DATA, - RESPONSE_DATA_VERSION, - RESPONSE_DATA_RESPONDER_ID, - RESPONSE_DATA_PRODUCED_AT, - RESPONSE_DATA_RESPONSES, - RESPONSE_DATA_RESPONSE_EXTENSIONS -]; -class ResponseData extends PkiObject { - constructor(parameters = {}) { - super(); - this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$2, ResponseData.defaultValues(TBS$2))); - if (VERSION$7 in parameters) { - this.version = getParametersValue(parameters, VERSION$7, ResponseData.defaultValues(VERSION$7)); - } - this.responderID = getParametersValue(parameters, RESPONDER_ID, ResponseData.defaultValues(RESPONDER_ID)); - this.producedAt = getParametersValue(parameters, PRODUCED_AT, ResponseData.defaultValues(PRODUCED_AT)); - this.responses = getParametersValue(parameters, RESPONSES, ResponseData.defaultValues(RESPONSES)); - if (RESPONSE_EXTENSIONS in parameters) { - this.responseExtensions = getParametersValue(parameters, RESPONSE_EXTENSIONS, ResponseData.defaultValues(RESPONSE_EXTENSIONS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - get tbs() { - return BufferSourceConverter.toArrayBuffer(this.tbsView); - } - set tbs(value) { - this.tbsView = new Uint8Array(value); - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$7: - return 0; - case TBS$2: - return EMPTY_BUFFER; - case RESPONDER_ID: - return {}; - case PRODUCED_AT: - return new Date(0, 0, 0); - case RESPONSES: - case RESPONSE_EXTENSIONS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TBS$2: - return (memberValue.byteLength === 0); - case RESPONDER_ID: - return (Object.keys(memberValue).length === 0); - case PRODUCED_AT: - return (memberValue === ResponseData.defaultValues(memberName)); - case RESPONSES: - case RESPONSE_EXTENSIONS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || RESPONSE_DATA), - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Integer({ name: (names.version || RESPONSE_DATA_VERSION) })] - }), - new Choice({ - value: [ - new Constructed({ - name: (names.responderID || RESPONSE_DATA_RESPONDER_ID), - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [RelativeDistinguishedNames.schema(names.ResponseDataByName || { - names: { - blockName: "ResponseData.byName" - } - })] - }), - new Constructed({ - name: (names.responderID || RESPONSE_DATA_RESPONDER_ID), - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [new OctetString({ name: (names.ResponseDataByKey || "ResponseData.byKey") })] - }) - ] - }), - new GeneralizedTime({ name: (names.producedAt || RESPONSE_DATA_PRODUCED_AT) }), - new Sequence({ - value: [ - new Repeated({ - name: RESPONSE_DATA_RESPONSES, - value: SingleResponse.schema(names.response || {}) - }) - ] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [Extensions.schema(names.extensions || { - names: { - blockName: RESPONSE_DATA_RESPONSE_EXTENSIONS - } - })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$h); - const asn1 = compareSchema(schema, schema, ResponseData.schema()); - AsnError.assertSchema(asn1, this.className); - this.tbsView = asn1.result.ResponseData.valueBeforeDecodeView; - if (RESPONSE_DATA_VERSION in asn1.result) - this.version = asn1.result[RESPONSE_DATA_VERSION].valueBlock.valueDec; - if (asn1.result[RESPONSE_DATA_RESPONDER_ID].idBlock.tagNumber === 1) - this.responderID = new RelativeDistinguishedNames({ schema: asn1.result[RESPONSE_DATA_RESPONDER_ID].valueBlock.value[0] }); - else - this.responderID = asn1.result[RESPONSE_DATA_RESPONDER_ID].valueBlock.value[0]; - this.producedAt = asn1.result[RESPONSE_DATA_PRODUCED_AT].toDate(); - this.responses = Array.from(asn1.result[RESPONSE_DATA_RESPONSES], element => new SingleResponse({ schema: element })); - if (RESPONSE_DATA_RESPONSE_EXTENSIONS in asn1.result) - this.responseExtensions = Array.from(asn1.result[RESPONSE_DATA_RESPONSE_EXTENSIONS].valueBlock.value, element => new Extension({ schema: element })); - } - toSchema(encodeFlag = false) { - let tbsSchema; - if (encodeFlag === false) { - if (!this.tbsView.byteLength) { - return ResponseData.schema(); - } - const asn1 = fromBER(this.tbsView); - AsnError.assert(asn1, "TBS Response Data"); - tbsSchema = asn1.result; - } - else { - const outputArray = []; - if (VERSION$7 in this) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Integer({ value: this.version })] - })); - } - if (this.responderID instanceof RelativeDistinguishedNames) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [this.responderID.toSchema()] - })); - } - else { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [this.responderID] - })); - } - outputArray.push(new GeneralizedTime({ valueDate: this.producedAt })); - outputArray.push(new Sequence({ - value: Array.from(this.responses, o => o.toSchema()) - })); - if (this.responseExtensions) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [new Sequence({ - value: Array.from(this.responseExtensions, o => o.toSchema()) - })] - })); - } - tbsSchema = new Sequence({ - value: outputArray - }); - } - return tbsSchema; - } - toJSON() { - const res = {}; - if (VERSION$7 in this) { - res.version = this.version; - } - if (this.responderID) { - res.responderID = this.responderID; - } - if (this.producedAt) { - res.producedAt = this.producedAt; - } - if (this.responses) { - res.responses = Array.from(this.responses, o => o.toJSON()); - } - if (this.responseExtensions) { - res.responseExtensions = Array.from(this.responseExtensions, o => o.toJSON()); - } - return res; - } -} -ResponseData.CLASS_NAME = "ResponseData"; - -const TRUSTED_CERTS = "trustedCerts"; -const CERTS$2 = "certs"; -const CRLS$1 = "crls"; -const OCSPS$1 = "ocsps"; -const CHECK_DATE = "checkDate"; -const FIND_ORIGIN = "findOrigin"; -const FIND_ISSUER = "findIssuer"; -var ChainValidationCode; -(function (ChainValidationCode) { - ChainValidationCode[ChainValidationCode["unknown"] = -1] = "unknown"; - ChainValidationCode[ChainValidationCode["success"] = 0] = "success"; - ChainValidationCode[ChainValidationCode["noRevocation"] = 11] = "noRevocation"; - ChainValidationCode[ChainValidationCode["noPath"] = 60] = "noPath"; - ChainValidationCode[ChainValidationCode["noValidPath"] = 97] = "noValidPath"; -})(ChainValidationCode || (ChainValidationCode = {})); -class ChainValidationError extends Error { - constructor(code, message) { - super(message); - this.name = ChainValidationError.NAME; - this.code = code; - this.message = message; - } -} -ChainValidationError.NAME = "ChainValidationError"; -function isTrusted(cert, trustedList) { - for (let i = 0; i < trustedList.length; i++) { - if (BufferSourceConverter.isEqual(cert.tbsView, trustedList[i].tbsView)) { - return true; - } - } - return false; -} -class CertificateChainValidationEngine { - constructor(parameters = {}) { - this.trustedCerts = getParametersValue(parameters, TRUSTED_CERTS, this.defaultValues(TRUSTED_CERTS)); - this.certs = getParametersValue(parameters, CERTS$2, this.defaultValues(CERTS$2)); - this.crls = getParametersValue(parameters, CRLS$1, this.defaultValues(CRLS$1)); - this.ocsps = getParametersValue(parameters, OCSPS$1, this.defaultValues(OCSPS$1)); - this.checkDate = getParametersValue(parameters, CHECK_DATE, this.defaultValues(CHECK_DATE)); - this.findOrigin = getParametersValue(parameters, FIND_ORIGIN, this.defaultValues(FIND_ORIGIN)); - this.findIssuer = getParametersValue(parameters, FIND_ISSUER, this.defaultValues(FIND_ISSUER)); - } - static defaultFindOrigin(certificate, validationEngine) { - if (certificate.tbsView.byteLength === 0) { - certificate.tbsView = new Uint8Array(certificate.encodeTBS().toBER()); - } - for (const localCert of validationEngine.certs) { - if (localCert.tbsView.byteLength === 0) { - localCert.tbsView = new Uint8Array(localCert.encodeTBS().toBER()); - } - if (BufferSourceConverter.isEqual(certificate.tbsView, localCert.tbsView)) - return "Intermediate Certificates"; - } - for (const trustedCert of validationEngine.trustedCerts) { - if (trustedCert.tbsView.byteLength === 0) - trustedCert.tbsView = new Uint8Array(trustedCert.encodeTBS().toBER()); - if (BufferSourceConverter.isEqual(certificate.tbsView, trustedCert.tbsView)) - return "Trusted Certificates"; - } - return "Unknown"; - } - defaultFindIssuer(certificate, validationEngine, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const result = []; - let keyIdentifier = null; - let authorityCertIssuer = null; - let authorityCertSerialNumber = null; - if (certificate.subject.isEqual(certificate.issuer)) { - try { - const verificationResult = yield certificate.verify(undefined, crypto); - if (verificationResult) { - return [certificate]; - } - } - catch (ex) { - } - } - if (certificate.extensions) { - for (const extension of certificate.extensions) { - if (extension.extnID === id_AuthorityKeyIdentifier && extension.parsedValue instanceof AuthorityKeyIdentifier) { - if (extension.parsedValue.keyIdentifier) { - keyIdentifier = extension.parsedValue.keyIdentifier; - } - else { - if (extension.parsedValue.authorityCertIssuer) { - authorityCertIssuer = extension.parsedValue.authorityCertIssuer; - } - if (extension.parsedValue.authorityCertSerialNumber) { - authorityCertSerialNumber = extension.parsedValue.authorityCertSerialNumber; - } - } - break; - } - } - } - function checkCertificate(possibleIssuer) { - if (keyIdentifier !== null) { - if (possibleIssuer.extensions) { - let extensionFound = false; - for (const extension of possibleIssuer.extensions) { - if (extension.extnID === id_SubjectKeyIdentifier && extension.parsedValue) { - extensionFound = true; - if (BufferSourceConverter.isEqual(extension.parsedValue.valueBlock.valueHex, keyIdentifier.valueBlock.valueHexView)) { - result.push(possibleIssuer); - } - break; - } - } - if (extensionFound) { - return; - } - } - } - let authorityCertSerialNumberEqual = false; - if (authorityCertSerialNumber !== null) - authorityCertSerialNumberEqual = possibleIssuer.serialNumber.isEqual(authorityCertSerialNumber); - if (authorityCertIssuer !== null) { - if (possibleIssuer.subject.isEqual(authorityCertIssuer)) { - if (authorityCertSerialNumberEqual) - result.push(possibleIssuer); - } - } - else { - if (certificate.issuer.isEqual(possibleIssuer.subject)) - result.push(possibleIssuer); - } - } - for (const trustedCert of validationEngine.trustedCerts) { - checkCertificate(trustedCert); - } - for (const intermediateCert of validationEngine.certs) { - checkCertificate(intermediateCert); - } - for (let i = 0; i < result.length; i++) { - try { - const verificationResult = yield certificate.verify(result[i], crypto); - if (verificationResult === false) - result.splice(i, 1); - } - catch (ex) { - result.splice(i, 1); - } - } - return result; - }); - } - defaultValues(memberName) { - switch (memberName) { - case TRUSTED_CERTS: - return []; - case CERTS$2: - return []; - case CRLS$1: - return []; - case OCSPS$1: - return []; - case CHECK_DATE: - return new Date(); - case FIND_ORIGIN: - return CertificateChainValidationEngine.defaultFindOrigin; - case FIND_ISSUER: - return this.defaultFindIssuer; - default: - throw new Error(`Invalid member name for CertificateChainValidationEngine class: ${memberName}`); - } - } - sort(passedWhenNotRevValues = false, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const localCerts = []; - const buildPath = (certificate, crypto) => __awaiter(this, void 0, void 0, function* () { - const result = []; - function checkUnique(array) { - let unique = true; - for (let i = 0; i < array.length; i++) { - for (let j = 0; j < array.length; j++) { - if (j === i) - continue; - if (array[i] === array[j]) { - unique = false; - break; - } - } - if (!unique) - break; - } - return unique; - } - if (isTrusted(certificate, this.trustedCerts)) { - return [[certificate]]; - } - const findIssuerResult = yield this.findIssuer(certificate, this, crypto); - if (findIssuerResult.length === 0) { - throw new Error("No valid certificate paths found"); - } - for (let i = 0; i < findIssuerResult.length; i++) { - if (BufferSourceConverter.isEqual(findIssuerResult[i].tbsView, certificate.tbsView)) { - result.push([findIssuerResult[i]]); - continue; - } - const buildPathResult = yield buildPath(findIssuerResult[i], crypto); - for (let j = 0; j < buildPathResult.length; j++) { - const copy = buildPathResult[j].slice(); - copy.splice(0, 0, findIssuerResult[i]); - if (checkUnique(copy)) - result.push(copy); - else - result.push(buildPathResult[j]); - } - } - return result; - }); - const findCRL = (certificate) => __awaiter(this, void 0, void 0, function* () { - const issuerCertificates = []; - const crls = []; - const crlsAndCertificates = []; - issuerCertificates.push(...localCerts.filter(element => certificate.issuer.isEqual(element.subject))); - if (issuerCertificates.length === 0) { - return { - status: 1, - statusMessage: "No certificate's issuers" - }; - } - crls.push(...this.crls.filter(o => o.issuer.isEqual(certificate.issuer))); - if (crls.length === 0) { - return { - status: 2, - statusMessage: "No CRLs for specific certificate issuer" - }; - } - for (let i = 0; i < crls.length; i++) { - const crl = crls[i]; - if (crl.nextUpdate && crl.nextUpdate.value < this.checkDate) { - continue; - } - for (let j = 0; j < issuerCertificates.length; j++) { - try { - const result = yield crls[i].verify({ issuerCertificate: issuerCertificates[j] }, crypto); - if (result) { - crlsAndCertificates.push({ - crl: crls[i], - certificate: issuerCertificates[j] - }); - break; - } - } - catch (ex) { - } - } - } - if (crlsAndCertificates.length) { - return { - status: 0, - statusMessage: EMPTY_STRING, - result: crlsAndCertificates - }; - } - return { - status: 3, - statusMessage: "No valid CRLs found" - }; - }); - const findOCSP = (certificate, issuerCertificate) => __awaiter(this, void 0, void 0, function* () { - const hashAlgorithm = crypto.getAlgorithmByOID(certificate.signatureAlgorithm.algorithmId); - if (!hashAlgorithm.name) { - return 1; - } - if (!hashAlgorithm.hash) { - return 1; - } - for (let i = 0; i < this.ocsps.length; i++) { - const ocsp = this.ocsps[i]; - const result = yield ocsp.getCertificateStatus(certificate, issuerCertificate, crypto); - if (result.isForCertificate) { - if (result.status === 0) - return 0; - return 1; - } - } - return 2; - }); - function checkForCA(certificate, needToCheckCRL = false) { - return __awaiter(this, void 0, void 0, function* () { - let isCA = false; - let mustBeCA = false; - let keyUsagePresent = false; - let cRLSign = false; - if (certificate.extensions) { - for (let j = 0; j < certificate.extensions.length; j++) { - const extension = certificate.extensions[j]; - if (extension.critical && !extension.parsedValue) { - return { - result: false, - resultCode: 6, - resultMessage: `Unable to parse critical certificate extension: ${extension.extnID}` - }; - } - if (extension.extnID === id_KeyUsage) { - keyUsagePresent = true; - const view = new Uint8Array(extension.parsedValue.valueBlock.valueHex); - if ((view[0] & 0x04) === 0x04) - mustBeCA = true; - if ((view[0] & 0x02) === 0x02) - cRLSign = true; - } - if (extension.extnID === id_BasicConstraints) { - if ("cA" in extension.parsedValue) { - if (extension.parsedValue.cA === true) - isCA = true; - } - } - } - if ((mustBeCA === true) && (isCA === false)) { - return { - result: false, - resultCode: 3, - resultMessage: "Unable to build certificate chain - using \"keyCertSign\" flag set without BasicConstraints" - }; - } - if ((keyUsagePresent === true) && (isCA === true) && (mustBeCA === false)) { - return { - result: false, - resultCode: 4, - resultMessage: "Unable to build certificate chain - \"keyCertSign\" flag was not set" - }; - } - if ((isCA === true) && (keyUsagePresent === true) && ((needToCheckCRL) && (cRLSign === false))) { - return { - result: false, - resultCode: 5, - resultMessage: "Unable to build certificate chain - intermediate certificate must have \"cRLSign\" key usage flag" - }; - } - } - if (isCA === false) { - return { - result: false, - resultCode: 7, - resultMessage: "Unable to build certificate chain - more than one possible end-user certificate" - }; - } - return { - result: true, - resultCode: 0, - resultMessage: EMPTY_STRING - }; - }); - } - const basicCheck = (path, checkDate) => __awaiter(this, void 0, void 0, function* () { - for (let i = 0; i < path.length; i++) { - if ((path[i].notBefore.value > checkDate) || - (path[i].notAfter.value < checkDate)) { - return { - result: false, - resultCode: 8, - resultMessage: "The certificate is either not yet valid or expired" - }; - } - } - if (path.length < 2) { - return { - result: false, - resultCode: 9, - resultMessage: "Too short certificate path" - }; - } - for (let i = (path.length - 2); i >= 0; i--) { - if (path[i].issuer.isEqual(path[i].subject) === false) { - if (path[i].issuer.isEqual(path[i + 1].subject) === false) { - return { - result: false, - resultCode: 10, - resultMessage: "Incorrect name chaining" - }; - } - } - } - if ((this.crls.length !== 0) || (this.ocsps.length !== 0)) { - for (let i = 0; i < (path.length - 1); i++) { - let ocspResult = 2; - let crlResult = { - status: 0, - statusMessage: EMPTY_STRING - }; - if (this.ocsps.length !== 0) { - ocspResult = yield findOCSP(path[i], path[i + 1]); - switch (ocspResult) { - case 0: - continue; - case 1: - return { - result: false, - resultCode: 12, - resultMessage: "One of certificates was revoked via OCSP response" - }; - } - } - if (this.crls.length !== 0) { - crlResult = yield findCRL(path[i]); - if (crlResult.status === 0 && crlResult.result) { - for (let j = 0; j < crlResult.result.length; j++) { - const isCertificateRevoked = crlResult.result[j].crl.isCertificateRevoked(path[i]); - if (isCertificateRevoked) { - return { - result: false, - resultCode: 12, - resultMessage: "One of certificates had been revoked" - }; - } - const isCertificateCA = yield checkForCA(crlResult.result[j].certificate, true); - if (isCertificateCA.result === false) { - return { - result: false, - resultCode: 13, - resultMessage: "CRL issuer certificate is not a CA certificate or does not have crlSign flag" - }; - } - } - } - else { - if (passedWhenNotRevValues === false) { - throw new ChainValidationError(ChainValidationCode.noRevocation, `No revocation values found for one of certificates: ${crlResult.statusMessage}`); - } - } - } - else { - if (ocspResult === 2) { - return { - result: false, - resultCode: 11, - resultMessage: "No revocation values found for one of certificates" - }; - } - } - if ((ocspResult === 2) && (crlResult.status === 2) && passedWhenNotRevValues) { - const issuerCertificate = path[i + 1]; - let extensionFound = false; - if (issuerCertificate.extensions) { - for (const extension of issuerCertificate.extensions) { - switch (extension.extnID) { - case id_CRLDistributionPoints: - case id_FreshestCRL: - case id_AuthorityInfoAccess: - extensionFound = true; - break; - } - } - } - if (extensionFound) { - throw new ChainValidationError(ChainValidationCode.noRevocation, `No revocation values found for one of certificates: ${crlResult.statusMessage}`); - } - } - } - } - for (const [i, cert] of path.entries()) { - if (!i) { - continue; - } - const result = yield checkForCA(cert); - if (!result.result) { - return { - result: false, - resultCode: 14, - resultMessage: "One of intermediate certificates is not a CA certificate" - }; - } - } - return { - result: true - }; - }); - localCerts.push(...this.trustedCerts); - localCerts.push(...this.certs); - for (let i = 0; i < localCerts.length; i++) { - for (let j = 0; j < localCerts.length; j++) { - if (i === j) - continue; - if (BufferSourceConverter.isEqual(localCerts[i].tbsView, localCerts[j].tbsView)) { - localCerts.splice(j, 1); - i = 0; - break; - } - } - } - const leafCert = localCerts[localCerts.length - 1]; - let result; - const certificatePath = [leafCert]; - result = yield buildPath(leafCert, crypto); - if (result.length === 0) { - throw new ChainValidationError(ChainValidationCode.noPath, "Unable to find certificate path"); - } - for (let i = 0; i < result.length; i++) { - let found = false; - for (let j = 0; j < (result[i]).length; j++) { - const certificate = (result[i])[j]; - for (let k = 0; k < this.trustedCerts.length; k++) { - if (BufferSourceConverter.isEqual(certificate.tbsView, this.trustedCerts[k].tbsView)) { - found = true; - break; - } - } - if (found) - break; - } - if (!found) { - result.splice(i, 1); - i = 0; - } - } - if (result.length === 0) { - throw new ChainValidationError(ChainValidationCode.noValidPath, "No valid certificate paths found"); - } - let shortestLength = result[0].length; - let shortestIndex = 0; - for (let i = 0; i < result.length; i++) { - if (result[i].length < shortestLength) { - shortestLength = result[i].length; - shortestIndex = i; - } - } - for (let i = 0; i < result[shortestIndex].length; i++) - certificatePath.push((result[shortestIndex])[i]); - result = yield basicCheck(certificatePath, this.checkDate); - if (result.result === false) - throw result; - return certificatePath; - }); - } - verify(parameters = {}, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - function compareDNSName(name, constraint) { - const namePrepared = stringPrep(name); - const constraintPrepared = stringPrep(constraint); - const nameSplitted = namePrepared.split("."); - const constraintSplitted = constraintPrepared.split("."); - const nameLen = nameSplitted.length; - const constrLen = constraintSplitted.length; - if ((nameLen === 0) || (constrLen === 0) || (nameLen < constrLen)) { - return false; - } - for (let i = 0; i < nameLen; i++) { - if (nameSplitted[i].length === 0) { - return false; - } - } - for (let i = 0; i < constrLen; i++) { - if (constraintSplitted[i].length === 0) { - if (i === 0) { - if (constrLen === 1) { - return false; - } - continue; - } - return false; - } - } - for (let i = 0; i < constrLen; i++) { - if (constraintSplitted[constrLen - 1 - i].length === 0) { - continue; - } - if (nameSplitted[nameLen - 1 - i].localeCompare(constraintSplitted[constrLen - 1 - i]) !== 0) { - return false; - } - } - return true; - } - function compareRFC822Name(name, constraint) { - const namePrepared = stringPrep(name); - const constraintPrepared = stringPrep(constraint); - const nameSplitted = namePrepared.split("@"); - const constraintSplitted = constraintPrepared.split("@"); - if ((nameSplitted.length === 0) || (constraintSplitted.length === 0) || (nameSplitted.length < constraintSplitted.length)) - return false; - if (constraintSplitted.length === 1) { - const result = compareDNSName(nameSplitted[1], constraintSplitted[0]); - if (result) { - const ns = nameSplitted[1].split("."); - const cs = constraintSplitted[0].split("."); - if (cs[0].length === 0) - return true; - return ns.length === cs.length; - } - return false; - } - return (namePrepared.localeCompare(constraintPrepared) === 0); - } - function compareUniformResourceIdentifier(name, constraint) { - let namePrepared = stringPrep(name); - const constraintPrepared = stringPrep(constraint); - const ns = namePrepared.split("/"); - const cs = constraintPrepared.split("/"); - if (cs.length > 1) - return false; - if (ns.length > 1) { - for (let i = 0; i < ns.length; i++) { - if ((ns[i].length > 0) && (ns[i].charAt(ns[i].length - 1) !== ":")) { - const nsPort = ns[i].split(":"); - namePrepared = nsPort[0]; - break; - } - } - } - const result = compareDNSName(namePrepared, constraintPrepared); - if (result) { - const nameSplitted = namePrepared.split("."); - const constraintSplitted = constraintPrepared.split("."); - if (constraintSplitted[0].length === 0) - return true; - return nameSplitted.length === constraintSplitted.length; - } - return false; - } - function compareIPAddress(name, constraint) { - const nameView = name.valueBlock.valueHexView; - const constraintView = constraint.valueBlock.valueHexView; - if ((nameView.length === 4) && (constraintView.length === 8)) { - for (let i = 0; i < 4; i++) { - if ((nameView[i] ^ constraintView[i]) & constraintView[i + 4]) - return false; - } - return true; - } - if ((nameView.length === 16) && (constraintView.length === 32)) { - for (let i = 0; i < 16; i++) { - if ((nameView[i] ^ constraintView[i]) & constraintView[i + 16]) - return false; - } - return true; - } - return false; - } - function compareDirectoryName(name, constraint) { - if ((name.typesAndValues.length === 0) || (constraint.typesAndValues.length === 0)) - return true; - if (name.typesAndValues.length < constraint.typesAndValues.length) - return false; - let result = true; - let nameStart = 0; - for (let i = 0; i < constraint.typesAndValues.length; i++) { - let localResult = false; - for (let j = nameStart; j < name.typesAndValues.length; j++) { - localResult = name.typesAndValues[j].isEqual(constraint.typesAndValues[i]); - if (name.typesAndValues[j].type === constraint.typesAndValues[i].type) - result = result && localResult; - if (localResult === true) { - if ((nameStart === 0) || (nameStart === j)) { - nameStart = j + 1; - break; - } - else - return false; - } - } - if (localResult === false) - return false; - } - return (nameStart === 0) ? false : result; - } - try { - if (this.certs.length === 0) - throw new Error("Empty certificate array"); - const passedWhenNotRevValues = parameters.passedWhenNotRevValues || false; - const initialPolicySet = parameters.initialPolicySet || [id_AnyPolicy]; - const initialExplicitPolicy = parameters.initialExplicitPolicy || false; - const initialPolicyMappingInhibit = parameters.initialPolicyMappingInhibit || false; - const initialInhibitPolicy = parameters.initialInhibitPolicy || false; - const initialPermittedSubtreesSet = parameters.initialPermittedSubtreesSet || []; - const initialExcludedSubtreesSet = parameters.initialExcludedSubtreesSet || []; - const initialRequiredNameForms = parameters.initialRequiredNameForms || []; - let explicitPolicyIndicator = initialExplicitPolicy; - let policyMappingInhibitIndicator = initialPolicyMappingInhibit; - let inhibitAnyPolicyIndicator = initialInhibitPolicy; - const pendingConstraints = [ - false, - false, - false, - ]; - let explicitPolicyPending = 0; - let policyMappingInhibitPending = 0; - let inhibitAnyPolicyPending = 0; - let permittedSubtrees = initialPermittedSubtreesSet; - let excludedSubtrees = initialExcludedSubtreesSet; - const requiredNameForms = initialRequiredNameForms; - let pathDepth = 1; - this.certs = yield this.sort(passedWhenNotRevValues, crypto); - const allPolicies = []; - allPolicies.push(id_AnyPolicy); - const policiesAndCerts = []; - const anyPolicyArray = new Array(this.certs.length - 1); - for (let ii = 0; ii < (this.certs.length - 1); ii++) - anyPolicyArray[ii] = true; - policiesAndCerts.push(anyPolicyArray); - const policyMappings = new Array(this.certs.length - 1); - const certPolicies = new Array(this.certs.length - 1); - let explicitPolicyStart = (explicitPolicyIndicator) ? (this.certs.length - 1) : (-1); - for (let i = (this.certs.length - 2); i >= 0; i--, pathDepth++) { - const cert = this.certs[i]; - if (cert.extensions) { - for (let j = 0; j < cert.extensions.length; j++) { - const extension = cert.extensions[j]; - if (extension.extnID === id_CertificatePolicies) { - certPolicies[i] = extension.parsedValue; - for (let s = 0; s < allPolicies.length; s++) { - if (allPolicies[s] === id_AnyPolicy) { - delete (policiesAndCerts[s])[i]; - break; - } - } - for (let k = 0; k < extension.parsedValue.certificatePolicies.length; k++) { - let policyIndex = (-1); - const policyId = extension.parsedValue.certificatePolicies[k].policyIdentifier; - for (let s = 0; s < allPolicies.length; s++) { - if (policyId === allPolicies[s]) { - policyIndex = s; - break; - } - } - if (policyIndex === (-1)) { - allPolicies.push(policyId); - const certArray = new Array(this.certs.length - 1); - certArray[i] = true; - policiesAndCerts.push(certArray); - } - else - (policiesAndCerts[policyIndex])[i] = true; - } - } - if (extension.extnID === id_PolicyMappings) { - if (policyMappingInhibitIndicator) { - return { - result: false, - resultCode: 98, - resultMessage: "Policy mapping prohibited" - }; - } - policyMappings[i] = extension.parsedValue; - } - if (extension.extnID === id_PolicyConstraints) { - if (explicitPolicyIndicator === false) { - if (extension.parsedValue.requireExplicitPolicy === 0) { - explicitPolicyIndicator = true; - explicitPolicyStart = i; - } - else { - if (pendingConstraints[0] === false) { - pendingConstraints[0] = true; - explicitPolicyPending = extension.parsedValue.requireExplicitPolicy; - } - else - explicitPolicyPending = (explicitPolicyPending > extension.parsedValue.requireExplicitPolicy) ? extension.parsedValue.requireExplicitPolicy : explicitPolicyPending; - } - if (extension.parsedValue.inhibitPolicyMapping === 0) - policyMappingInhibitIndicator = true; - else { - if (pendingConstraints[1] === false) { - pendingConstraints[1] = true; - policyMappingInhibitPending = extension.parsedValue.inhibitPolicyMapping + 1; - } - else - policyMappingInhibitPending = (policyMappingInhibitPending > (extension.parsedValue.inhibitPolicyMapping + 1)) ? (extension.parsedValue.inhibitPolicyMapping + 1) : policyMappingInhibitPending; - } - } - } - if (extension.extnID === id_InhibitAnyPolicy) { - if (inhibitAnyPolicyIndicator === false) { - if (extension.parsedValue.valueBlock.valueDec === 0) - inhibitAnyPolicyIndicator = true; - else { - if (pendingConstraints[2] === false) { - pendingConstraints[2] = true; - inhibitAnyPolicyPending = extension.parsedValue.valueBlock.valueDec; - } - else - inhibitAnyPolicyPending = (inhibitAnyPolicyPending > extension.parsedValue.valueBlock.valueDec) ? extension.parsedValue.valueBlock.valueDec : inhibitAnyPolicyPending; - } - } - } - } - if (inhibitAnyPolicyIndicator === true) { - let policyIndex = (-1); - for (let searchAnyPolicy = 0; searchAnyPolicy < allPolicies.length; searchAnyPolicy++) { - if (allPolicies[searchAnyPolicy] === id_AnyPolicy) { - policyIndex = searchAnyPolicy; - break; - } - } - if (policyIndex !== (-1)) - delete (policiesAndCerts[0])[i]; - } - if (explicitPolicyIndicator === false) { - if (pendingConstraints[0] === true) { - explicitPolicyPending--; - if (explicitPolicyPending === 0) { - explicitPolicyIndicator = true; - explicitPolicyStart = i; - pendingConstraints[0] = false; - } - } - } - if (policyMappingInhibitIndicator === false) { - if (pendingConstraints[1] === true) { - policyMappingInhibitPending--; - if (policyMappingInhibitPending === 0) { - policyMappingInhibitIndicator = true; - pendingConstraints[1] = false; - } - } - } - if (inhibitAnyPolicyIndicator === false) { - if (pendingConstraints[2] === true) { - inhibitAnyPolicyPending--; - if (inhibitAnyPolicyPending === 0) { - inhibitAnyPolicyIndicator = true; - pendingConstraints[2] = false; - } - } - } - } - } - for (let i = 0; i < (this.certs.length - 1); i++) { - if ((i < (this.certs.length - 2)) && (typeof policyMappings[i + 1] !== "undefined")) { - for (let k = 0; k < policyMappings[i + 1].mappings.length; k++) { - if ((policyMappings[i + 1].mappings[k].issuerDomainPolicy === id_AnyPolicy) || (policyMappings[i + 1].mappings[k].subjectDomainPolicy === id_AnyPolicy)) { - return { - result: false, - resultCode: 99, - resultMessage: "The \"anyPolicy\" should not be a part of policy mapping scheme" - }; - } - let issuerDomainPolicyIndex = (-1); - let subjectDomainPolicyIndex = (-1); - for (let n = 0; n < allPolicies.length; n++) { - if (allPolicies[n] === policyMappings[i + 1].mappings[k].issuerDomainPolicy) - issuerDomainPolicyIndex = n; - if (allPolicies[n] === policyMappings[i + 1].mappings[k].subjectDomainPolicy) - subjectDomainPolicyIndex = n; - } - if (typeof (policiesAndCerts[issuerDomainPolicyIndex])[i] !== "undefined") - delete (policiesAndCerts[issuerDomainPolicyIndex])[i]; - for (let j = 0; j < certPolicies[i].certificatePolicies.length; j++) { - if (policyMappings[i + 1].mappings[k].subjectDomainPolicy === certPolicies[i].certificatePolicies[j].policyIdentifier) { - if ((issuerDomainPolicyIndex !== (-1)) && (subjectDomainPolicyIndex !== (-1))) { - for (let m = 0; m <= i; m++) { - if (typeof (policiesAndCerts[subjectDomainPolicyIndex])[m] !== "undefined") { - (policiesAndCerts[issuerDomainPolicyIndex])[m] = true; - delete (policiesAndCerts[subjectDomainPolicyIndex])[m]; - } - } - } - } - } - } - } - } - for (let i = 0; i < allPolicies.length; i++) { - if (allPolicies[i] === id_AnyPolicy) { - for (let j = 0; j < explicitPolicyStart; j++) - delete (policiesAndCerts[i])[j]; - } - } - const authConstrPolicies = []; - for (let i = 0; i < policiesAndCerts.length; i++) { - let found = true; - for (let j = 0; j < (this.certs.length - 1); j++) { - let anyPolicyFound = false; - if ((j < explicitPolicyStart) && (allPolicies[i] === id_AnyPolicy) && (allPolicies.length > 1)) { - found = false; - break; - } - if (typeof (policiesAndCerts[i])[j] === "undefined") { - if (j >= explicitPolicyStart) { - for (let k = 0; k < allPolicies.length; k++) { - if (allPolicies[k] === id_AnyPolicy) { - if ((policiesAndCerts[k])[j] === true) - anyPolicyFound = true; - break; - } - } - } - if (!anyPolicyFound) { - found = false; - break; - } - } - } - if (found === true) - authConstrPolicies.push(allPolicies[i]); - } - let userConstrPolicies = []; - if ((initialPolicySet.length === 1) && (initialPolicySet[0] === id_AnyPolicy) && (explicitPolicyIndicator === false)) - userConstrPolicies = initialPolicySet; - else { - if ((authConstrPolicies.length === 1) && (authConstrPolicies[0] === id_AnyPolicy)) - userConstrPolicies = initialPolicySet; - else { - for (let i = 0; i < authConstrPolicies.length; i++) { - for (let j = 0; j < initialPolicySet.length; j++) { - if ((initialPolicySet[j] === authConstrPolicies[i]) || (initialPolicySet[j] === id_AnyPolicy)) { - userConstrPolicies.push(authConstrPolicies[i]); - break; - } - } - } - } - } - const policyResult = { - result: (userConstrPolicies.length > 0), - resultCode: 0, - resultMessage: (userConstrPolicies.length > 0) ? EMPTY_STRING : "Zero \"userConstrPolicies\" array, no intersections with \"authConstrPolicies\"", - authConstrPolicies, - userConstrPolicies, - explicitPolicyIndicator, - policyMappings, - certificatePath: this.certs - }; - if (userConstrPolicies.length === 0) - return policyResult; - if (policyResult.result === false) - return policyResult; - pathDepth = 1; - for (let i = (this.certs.length - 2); i >= 0; i--, pathDepth++) { - const cert = this.certs[i]; - let subjectAltNames = []; - let certPermittedSubtrees = []; - let certExcludedSubtrees = []; - if (cert.extensions) { - for (let j = 0; j < cert.extensions.length; j++) { - const extension = cert.extensions[j]; - if (extension.extnID === id_NameConstraints) { - if ("permittedSubtrees" in extension.parsedValue) - certPermittedSubtrees = certPermittedSubtrees.concat(extension.parsedValue.permittedSubtrees); - if ("excludedSubtrees" in extension.parsedValue) - certExcludedSubtrees = certExcludedSubtrees.concat(extension.parsedValue.excludedSubtrees); - } - if (extension.extnID === id_SubjectAltName) - subjectAltNames = subjectAltNames.concat(extension.parsedValue.altNames); - } - } - let formFound = (requiredNameForms.length <= 0); - for (let j = 0; j < requiredNameForms.length; j++) { - switch (requiredNameForms[j].base.type) { - case 4: - { - if (requiredNameForms[j].base.value.typesAndValues.length !== cert.subject.typesAndValues.length) - continue; - formFound = true; - for (let k = 0; k < cert.subject.typesAndValues.length; k++) { - if (cert.subject.typesAndValues[k].type !== requiredNameForms[j].base.value.typesAndValues[k].type) { - formFound = false; - break; - } - } - if (formFound === true) - break; - } - break; - default: - } - } - if (formFound === false) { - policyResult.result = false; - policyResult.resultCode = 21; - policyResult.resultMessage = "No necessary name form found"; - throw policyResult; - } - const constrGroups = [ - [], - [], - [], - [], - [], - ]; - for (let j = 0; j < permittedSubtrees.length; j++) { - switch (permittedSubtrees[j].base.type) { - case 1: - constrGroups[0].push(permittedSubtrees[j]); - break; - case 2: - constrGroups[1].push(permittedSubtrees[j]); - break; - case 4: - constrGroups[2].push(permittedSubtrees[j]); - break; - case 6: - constrGroups[3].push(permittedSubtrees[j]); - break; - case 7: - constrGroups[4].push(permittedSubtrees[j]); - break; - default: - } - } - for (let p = 0; p < 5; p++) { - let groupPermitted = false; - let valueExists = false; - const group = constrGroups[p]; - for (let j = 0; j < group.length; j++) { - switch (p) { - case 0: - if (subjectAltNames.length > 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 1) { - valueExists = true; - groupPermitted = groupPermitted || compareRFC822Name(subjectAltNames[k].value, group[j].base.value); - } - } - } - else { - for (let k = 0; k < cert.subject.typesAndValues.length; k++) { - if ((cert.subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") || - (cert.subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) { - valueExists = true; - groupPermitted = groupPermitted || compareRFC822Name(cert.subject.typesAndValues[k].value.valueBlock.value, group[j].base.value); - } - } - } - break; - case 1: - if (subjectAltNames.length > 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 2) { - valueExists = true; - groupPermitted = groupPermitted || compareDNSName(subjectAltNames[k].value, group[j].base.value); - } - } - } - break; - case 2: - valueExists = true; - groupPermitted = compareDirectoryName(cert.subject, group[j].base.value); - break; - case 3: - if (subjectAltNames.length > 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 6) { - valueExists = true; - groupPermitted = groupPermitted || compareUniformResourceIdentifier(subjectAltNames[k].value, group[j].base.value); - } - } - } - break; - case 4: - if (subjectAltNames.length > 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 7) { - valueExists = true; - groupPermitted = groupPermitted || compareIPAddress(subjectAltNames[k].value, group[j].base.value); - } - } - } - break; - default: - } - if (groupPermitted) - break; - } - if ((groupPermitted === false) && (group.length > 0) && valueExists) { - policyResult.result = false; - policyResult.resultCode = 41; - policyResult.resultMessage = "Failed to meet \"permitted sub-trees\" name constraint"; - throw policyResult; - } - } - let excluded = false; - for (let j = 0; j < excludedSubtrees.length; j++) { - switch (excludedSubtrees[j].base.type) { - case 1: - if (subjectAltNames.length >= 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 1) - excluded = excluded || compareRFC822Name(subjectAltNames[k].value, excludedSubtrees[j].base.value); - } - } - else { - for (let k = 0; k < cert.subject.typesAndValues.length; k++) { - if ((cert.subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") || - (cert.subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) - excluded = excluded || compareRFC822Name(cert.subject.typesAndValues[k].value.valueBlock.value, excludedSubtrees[j].base.value); - } - } - break; - case 2: - if (subjectAltNames.length > 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 2) - excluded = excluded || compareDNSName(subjectAltNames[k].value, excludedSubtrees[j].base.value); - } - } - break; - case 4: - excluded = excluded || compareDirectoryName(cert.subject, excludedSubtrees[j].base.value); - break; - case 6: - if (subjectAltNames.length > 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 6) - excluded = excluded || compareUniformResourceIdentifier(subjectAltNames[k].value, excludedSubtrees[j].base.value); - } - } - break; - case 7: - if (subjectAltNames.length > 0) { - for (let k = 0; k < subjectAltNames.length; k++) { - if (subjectAltNames[k].type === 7) - excluded = excluded || compareIPAddress(subjectAltNames[k].value, excludedSubtrees[j].base.value); - } - } - break; - default: - } - if (excluded) - break; - } - if (excluded === true) { - policyResult.result = false; - policyResult.resultCode = 42; - policyResult.resultMessage = "Failed to meet \"excluded sub-trees\" name constraint"; - throw policyResult; - } - permittedSubtrees = permittedSubtrees.concat(certPermittedSubtrees); - excludedSubtrees = excludedSubtrees.concat(certExcludedSubtrees); - } - return policyResult; - } - catch (error) { - if (error instanceof Error) { - if (error instanceof ChainValidationError) { - return { - result: false, - resultCode: error.code, - resultMessage: error.message, - error: error, - }; - } - return { - result: false, - resultCode: ChainValidationCode.unknown, - resultMessage: error.message, - error: error, - }; - } - if (error && typeof error === "object" && "resultMessage" in error) { - return error; - } - return { - result: false, - resultCode: -1, - resultMessage: `${error}`, - }; - } - }); - } +const CERT_ID = "certID"; +const CERT_STATUS = "certStatus"; +const THIS_UPDATE = "thisUpdate"; +const NEXT_UPDATE = "nextUpdate"; +const SINGLE_EXTENSIONS = "singleExtensions"; +const CLEAR_PROPS$i = [ + CERT_ID, + CERT_STATUS, + THIS_UPDATE, + NEXT_UPDATE, + SINGLE_EXTENSIONS, +]; +class SingleResponse extends PkiObject { + constructor(parameters = {}) { + super(); + this.certID = getParametersValue(parameters, CERT_ID, SingleResponse.defaultValues(CERT_ID)); + this.certStatus = getParametersValue(parameters, CERT_STATUS, SingleResponse.defaultValues(CERT_STATUS)); + this.thisUpdate = getParametersValue(parameters, THIS_UPDATE, SingleResponse.defaultValues(THIS_UPDATE)); + if (NEXT_UPDATE in parameters) { + this.nextUpdate = getParametersValue(parameters, NEXT_UPDATE, SingleResponse.defaultValues(NEXT_UPDATE)); + } + if (SINGLE_EXTENSIONS in parameters) { + this.singleExtensions = getParametersValue(parameters, SINGLE_EXTENSIONS, SingleResponse.defaultValues(SINGLE_EXTENSIONS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case CERT_ID: + return new CertID(); + case CERT_STATUS: + return {}; + case THIS_UPDATE: + case NEXT_UPDATE: + return new Date(0, 0, 0); + case SINGLE_EXTENSIONS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case CERT_ID: + return ((CertID.compareWithDefault("hashAlgorithm", memberValue.hashAlgorithm)) && + (CertID.compareWithDefault("issuerNameHash", memberValue.issuerNameHash)) && + (CertID.compareWithDefault("issuerKeyHash", memberValue.issuerKeyHash)) && + (CertID.compareWithDefault("serialNumber", memberValue.serialNumber))); + case CERT_STATUS: + return (Object.keys(memberValue).length === 0); + case THIS_UPDATE: + case NEXT_UPDATE: + return (memberValue === SingleResponse.defaultValues(memberName)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + CertID.schema(names.certID || {}), + new Choice({ + value: [ + new Primitive({ + name: (names.certStatus || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + }), + new Constructed({ + name: (names.certStatus || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new GeneralizedTime(), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Enumerated()] + }) + ] + }), + new Primitive({ + name: (names.certStatus || EMPTY_STRING), + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + lenBlock: { length: 1 } + }) + ] + }), + new GeneralizedTime({ name: (names.thisUpdate || EMPTY_STRING) }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new GeneralizedTime({ name: (names.nextUpdate || EMPTY_STRING) })] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [Extensions.schema(names.singleExtensions || {})] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$i); + const asn1 = compareSchema(schema, schema, SingleResponse.schema({ + names: { + certID: { + names: { + blockName: CERT_ID + } + }, + certStatus: CERT_STATUS, + thisUpdate: THIS_UPDATE, + nextUpdate: NEXT_UPDATE, + singleExtensions: { + names: { + blockName: SINGLE_EXTENSIONS + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.certID = new CertID({ schema: asn1.result.certID }); + this.certStatus = asn1.result.certStatus; + this.thisUpdate = asn1.result.thisUpdate.toDate(); + if (NEXT_UPDATE in asn1.result) + this.nextUpdate = asn1.result.nextUpdate.toDate(); + if (SINGLE_EXTENSIONS in asn1.result) + this.singleExtensions = Array.from(asn1.result.singleExtensions.valueBlock.value, element => new Extension({ schema: element })); + } + toSchema() { + const outputArray = []; + outputArray.push(this.certID.toSchema()); + outputArray.push(this.certStatus); + outputArray.push(new GeneralizedTime({ valueDate: this.thisUpdate })); + if (this.nextUpdate) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new GeneralizedTime({ valueDate: this.nextUpdate })] + })); + } + if (this.singleExtensions) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [new Sequence({ value: Array.from(this.singleExtensions, o => o.toSchema()) })] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + certID: this.certID.toJSON(), + certStatus: this.certStatus.toJSON(), + thisUpdate: this.thisUpdate + }; + if (this.nextUpdate) { + res.nextUpdate = this.nextUpdate; + } + if (this.singleExtensions) { + res.singleExtensions = Array.from(this.singleExtensions, o => o.toJSON()); + } + return res; + } +} +SingleResponse.CLASS_NAME = "SingleResponse"; + +const TBS$2 = "tbs"; +const VERSION$7 = "version"; +const RESPONDER_ID = "responderID"; +const PRODUCED_AT = "producedAt"; +const RESPONSES = "responses"; +const RESPONSE_EXTENSIONS = "responseExtensions"; +const RESPONSE_DATA = "ResponseData"; +const RESPONSE_DATA_VERSION = `${RESPONSE_DATA}.${VERSION$7}`; +const RESPONSE_DATA_RESPONDER_ID = `${RESPONSE_DATA}.${RESPONDER_ID}`; +const RESPONSE_DATA_PRODUCED_AT = `${RESPONSE_DATA}.${PRODUCED_AT}`; +const RESPONSE_DATA_RESPONSES = `${RESPONSE_DATA}.${RESPONSES}`; +const RESPONSE_DATA_RESPONSE_EXTENSIONS = `${RESPONSE_DATA}.${RESPONSE_EXTENSIONS}`; +const CLEAR_PROPS$h = [ + RESPONSE_DATA, + RESPONSE_DATA_VERSION, + RESPONSE_DATA_RESPONDER_ID, + RESPONSE_DATA_PRODUCED_AT, + RESPONSE_DATA_RESPONSES, + RESPONSE_DATA_RESPONSE_EXTENSIONS +]; +class ResponseData extends PkiObject { + get tbs() { + return BufferSourceConverter.toArrayBuffer(this.tbsView); + } + set tbs(value) { + this.tbsView = new Uint8Array(value); + } + constructor(parameters = {}) { + super(); + this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$2, ResponseData.defaultValues(TBS$2))); + if (VERSION$7 in parameters) { + this.version = getParametersValue(parameters, VERSION$7, ResponseData.defaultValues(VERSION$7)); + } + this.responderID = getParametersValue(parameters, RESPONDER_ID, ResponseData.defaultValues(RESPONDER_ID)); + this.producedAt = getParametersValue(parameters, PRODUCED_AT, ResponseData.defaultValues(PRODUCED_AT)); + this.responses = getParametersValue(parameters, RESPONSES, ResponseData.defaultValues(RESPONSES)); + if (RESPONSE_EXTENSIONS in parameters) { + this.responseExtensions = getParametersValue(parameters, RESPONSE_EXTENSIONS, ResponseData.defaultValues(RESPONSE_EXTENSIONS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$7: + return 0; + case TBS$2: + return EMPTY_BUFFER; + case RESPONDER_ID: + return {}; + case PRODUCED_AT: + return new Date(0, 0, 0); + case RESPONSES: + case RESPONSE_EXTENSIONS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TBS$2: + return (memberValue.byteLength === 0); + case RESPONDER_ID: + return (Object.keys(memberValue).length === 0); + case PRODUCED_AT: + return (memberValue === ResponseData.defaultValues(memberName)); + case RESPONSES: + case RESPONSE_EXTENSIONS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || RESPONSE_DATA), + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Integer({ name: (names.version || RESPONSE_DATA_VERSION) })] + }), + new Choice({ + value: [ + new Constructed({ + name: (names.responderID || RESPONSE_DATA_RESPONDER_ID), + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [RelativeDistinguishedNames.schema(names.ResponseDataByName || { + names: { + blockName: "ResponseData.byName" + } + })] + }), + new Constructed({ + name: (names.responderID || RESPONSE_DATA_RESPONDER_ID), + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [new OctetString({ name: (names.ResponseDataByKey || "ResponseData.byKey") })] + }) + ] + }), + new GeneralizedTime({ name: (names.producedAt || RESPONSE_DATA_PRODUCED_AT) }), + new Sequence({ + value: [ + new Repeated({ + name: RESPONSE_DATA_RESPONSES, + value: SingleResponse.schema(names.response || {}) + }) + ] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [Extensions.schema(names.extensions || { + names: { + blockName: RESPONSE_DATA_RESPONSE_EXTENSIONS + } + })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$h); + const asn1 = compareSchema(schema, schema, ResponseData.schema()); + AsnError.assertSchema(asn1, this.className); + this.tbsView = asn1.result.ResponseData.valueBeforeDecodeView; + if (RESPONSE_DATA_VERSION in asn1.result) + this.version = asn1.result[RESPONSE_DATA_VERSION].valueBlock.valueDec; + if (asn1.result[RESPONSE_DATA_RESPONDER_ID].idBlock.tagNumber === 1) + this.responderID = new RelativeDistinguishedNames({ schema: asn1.result[RESPONSE_DATA_RESPONDER_ID].valueBlock.value[0] }); + else + this.responderID = asn1.result[RESPONSE_DATA_RESPONDER_ID].valueBlock.value[0]; + this.producedAt = asn1.result[RESPONSE_DATA_PRODUCED_AT].toDate(); + this.responses = Array.from(asn1.result[RESPONSE_DATA_RESPONSES], element => new SingleResponse({ schema: element })); + if (RESPONSE_DATA_RESPONSE_EXTENSIONS in asn1.result) + this.responseExtensions = Array.from(asn1.result[RESPONSE_DATA_RESPONSE_EXTENSIONS].valueBlock.value, element => new Extension({ schema: element })); + } + toSchema(encodeFlag = false) { + let tbsSchema; + if (encodeFlag === false) { + if (!this.tbsView.byteLength) { + return ResponseData.schema(); + } + const asn1 = fromBER(this.tbsView); + AsnError.assert(asn1, "TBS Response Data"); + tbsSchema = asn1.result; + } + else { + const outputArray = []; + if (VERSION$7 in this) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Integer({ value: this.version })] + })); + } + if (this.responderID instanceof RelativeDistinguishedNames) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [this.responderID.toSchema()] + })); + } + else { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [this.responderID] + })); + } + outputArray.push(new GeneralizedTime({ valueDate: this.producedAt })); + outputArray.push(new Sequence({ + value: Array.from(this.responses, o => o.toSchema()) + })); + if (this.responseExtensions) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [new Sequence({ + value: Array.from(this.responseExtensions, o => o.toSchema()) + })] + })); + } + tbsSchema = new Sequence({ + value: outputArray + }); + } + return tbsSchema; + } + toJSON() { + const res = {}; + if (VERSION$7 in this) { + res.version = this.version; + } + if (this.responderID) { + res.responderID = this.responderID; + } + if (this.producedAt) { + res.producedAt = this.producedAt; + } + if (this.responses) { + res.responses = Array.from(this.responses, o => o.toJSON()); + } + if (this.responseExtensions) { + res.responseExtensions = Array.from(this.responseExtensions, o => o.toJSON()); + } + return res; + } +} +ResponseData.CLASS_NAME = "ResponseData"; + +const TRUSTED_CERTS = "trustedCerts"; +const CERTS$2 = "certs"; +const CRLS$1 = "crls"; +const OCSPS$1 = "ocsps"; +const CHECK_DATE = "checkDate"; +const FIND_ORIGIN = "findOrigin"; +const FIND_ISSUER = "findIssuer"; +var ChainValidationCode; +(function (ChainValidationCode) { + ChainValidationCode[ChainValidationCode["unknown"] = -1] = "unknown"; + ChainValidationCode[ChainValidationCode["success"] = 0] = "success"; + ChainValidationCode[ChainValidationCode["noRevocation"] = 11] = "noRevocation"; + ChainValidationCode[ChainValidationCode["noPath"] = 60] = "noPath"; + ChainValidationCode[ChainValidationCode["noValidPath"] = 97] = "noValidPath"; +})(ChainValidationCode || (ChainValidationCode = {})); +class ChainValidationError extends Error { + constructor(code, message) { + super(message); + this.name = ChainValidationError.NAME; + this.code = code; + this.message = message; + } +} +ChainValidationError.NAME = "ChainValidationError"; +function isTrusted(cert, trustedList) { + for (let i = 0; i < trustedList.length; i++) { + if (BufferSourceConverter.isEqual(cert.tbsView, trustedList[i].tbsView)) { + return true; + } + } + return false; +} +class CertificateChainValidationEngine { + constructor(parameters = {}) { + this.trustedCerts = getParametersValue(parameters, TRUSTED_CERTS, this.defaultValues(TRUSTED_CERTS)); + this.certs = getParametersValue(parameters, CERTS$2, this.defaultValues(CERTS$2)); + this.crls = getParametersValue(parameters, CRLS$1, this.defaultValues(CRLS$1)); + this.ocsps = getParametersValue(parameters, OCSPS$1, this.defaultValues(OCSPS$1)); + this.checkDate = getParametersValue(parameters, CHECK_DATE, this.defaultValues(CHECK_DATE)); + this.findOrigin = getParametersValue(parameters, FIND_ORIGIN, this.defaultValues(FIND_ORIGIN)); + this.findIssuer = getParametersValue(parameters, FIND_ISSUER, this.defaultValues(FIND_ISSUER)); + } + static defaultFindOrigin(certificate, validationEngine) { + if (certificate.tbsView.byteLength === 0) { + certificate.tbsView = new Uint8Array(certificate.encodeTBS().toBER()); + } + for (const localCert of validationEngine.certs) { + if (localCert.tbsView.byteLength === 0) { + localCert.tbsView = new Uint8Array(localCert.encodeTBS().toBER()); + } + if (BufferSourceConverter.isEqual(certificate.tbsView, localCert.tbsView)) + return "Intermediate Certificates"; + } + for (const trustedCert of validationEngine.trustedCerts) { + if (trustedCert.tbsView.byteLength === 0) + trustedCert.tbsView = new Uint8Array(trustedCert.encodeTBS().toBER()); + if (BufferSourceConverter.isEqual(certificate.tbsView, trustedCert.tbsView)) + return "Trusted Certificates"; + } + return "Unknown"; + } + async defaultFindIssuer(certificate, validationEngine, crypto = getCrypto(true)) { + const result = []; + let keyIdentifier = null; + let authorityCertIssuer = null; + let authorityCertSerialNumber = null; + if (certificate.subject.isEqual(certificate.issuer)) { + try { + const verificationResult = await certificate.verify(undefined, crypto); + if (verificationResult) { + return [certificate]; + } + } + catch { + } + } + if (certificate.extensions) { + for (const extension of certificate.extensions) { + if (extension.extnID === id_AuthorityKeyIdentifier && extension.parsedValue instanceof AuthorityKeyIdentifier) { + if (extension.parsedValue.keyIdentifier) { + keyIdentifier = extension.parsedValue.keyIdentifier; + } + else { + if (extension.parsedValue.authorityCertIssuer) { + authorityCertIssuer = extension.parsedValue.authorityCertIssuer; + } + if (extension.parsedValue.authorityCertSerialNumber) { + authorityCertSerialNumber = extension.parsedValue.authorityCertSerialNumber; + } + } + break; + } + } + } + function checkCertificate(possibleIssuer) { + if (keyIdentifier !== null) { + if (possibleIssuer.extensions) { + let extensionFound = false; + for (const extension of possibleIssuer.extensions) { + if (extension.extnID === id_SubjectKeyIdentifier && extension.parsedValue) { + extensionFound = true; + if (BufferSourceConverter.isEqual(extension.parsedValue.valueBlock.valueHex, keyIdentifier.valueBlock.valueHexView)) { + result.push(possibleIssuer); + } + break; + } + } + if (extensionFound) { + return; + } + } + } + let authorityCertSerialNumberEqual = false; + if (authorityCertSerialNumber !== null) + authorityCertSerialNumberEqual = possibleIssuer.serialNumber.isEqual(authorityCertSerialNumber); + if (authorityCertIssuer !== null) { + if (possibleIssuer.subject.isEqual(authorityCertIssuer)) { + if (authorityCertSerialNumberEqual) + result.push(possibleIssuer); + } + } + else { + if (certificate.issuer.isEqual(possibleIssuer.subject)) + result.push(possibleIssuer); + } + } + for (const trustedCert of validationEngine.trustedCerts) { + checkCertificate(trustedCert); + } + for (const intermediateCert of validationEngine.certs) { + checkCertificate(intermediateCert); + } + for (let i = result.length - 1; i >= 0; i--) { + try { + const verificationResult = await certificate.verify(result[i], crypto); + if (verificationResult === false) + result.splice(i, 1); + } + catch { + result.splice(i, 1); + } + } + return result; + } + defaultValues(memberName) { + switch (memberName) { + case TRUSTED_CERTS: + return []; + case CERTS$2: + return []; + case CRLS$1: + return []; + case OCSPS$1: + return []; + case CHECK_DATE: + return new Date(); + case FIND_ORIGIN: + return CertificateChainValidationEngine.defaultFindOrigin; + case FIND_ISSUER: + return this.defaultFindIssuer; + default: + throw new Error(`Invalid member name for CertificateChainValidationEngine class: ${memberName}`); + } + } + async sort(passedWhenNotRevValues = false, crypto = getCrypto(true)) { + const localCerts = []; + const buildPath = async (certificate, crypto) => { + const result = []; + function checkUnique(array) { + let unique = true; + for (let i = 0; i < array.length; i++) { + for (let j = 0; j < array.length; j++) { + if (j === i) + continue; + if (array[i] === array[j]) { + unique = false; + break; + } + } + if (!unique) + break; + } + return unique; + } + if (isTrusted(certificate, this.trustedCerts)) { + return [[certificate]]; + } + const findIssuerResult = await this.findIssuer(certificate, this, crypto); + if (findIssuerResult.length === 0) { + throw new Error("No valid certificate paths found"); + } + for (let i = 0; i < findIssuerResult.length; i++) { + if (BufferSourceConverter.isEqual(findIssuerResult[i].tbsView, certificate.tbsView)) { + result.push([findIssuerResult[i]]); + continue; + } + const buildPathResult = await buildPath(findIssuerResult[i], crypto); + for (let j = 0; j < buildPathResult.length; j++) { + const copy = buildPathResult[j].slice(); + copy.splice(0, 0, findIssuerResult[i]); + if (checkUnique(copy)) + result.push(copy); + else + result.push(buildPathResult[j]); + } + } + return result; + }; + const findCRL = async (certificate) => { + const issuerCertificates = []; + const crls = []; + const crlsAndCertificates = []; + issuerCertificates.push(...localCerts.filter(element => certificate.issuer.isEqual(element.subject))); + if (issuerCertificates.length === 0) { + return { + status: 1, + statusMessage: "No certificate's issuers" + }; + } + crls.push(...this.crls.filter(o => o.issuer.isEqual(certificate.issuer))); + if (crls.length === 0) { + return { + status: 2, + statusMessage: "No CRLs for specific certificate issuer" + }; + } + for (let i = 0; i < crls.length; i++) { + const crl = crls[i]; + if (crl.nextUpdate && crl.nextUpdate.value < this.checkDate) { + continue; + } + for (let j = 0; j < issuerCertificates.length; j++) { + try { + const result = await crls[i].verify({ issuerCertificate: issuerCertificates[j] }, crypto); + if (result) { + crlsAndCertificates.push({ + crl: crls[i], + certificate: issuerCertificates[j] + }); + break; + } + } + catch { + } + } + } + if (crlsAndCertificates.length) { + return { + status: 0, + statusMessage: EMPTY_STRING, + result: crlsAndCertificates + }; + } + return { + status: 3, + statusMessage: "No valid CRLs found" + }; + }; + const findOCSP = async (certificate, issuerCertificate) => { + const hashAlgorithm = crypto.getAlgorithmByOID(certificate.signatureAlgorithm.algorithmId); + if (!hashAlgorithm.name) { + return 1; + } + if (!hashAlgorithm.hash) { + return 1; + } + for (let i = 0; i < this.ocsps.length; i++) { + const ocsp = this.ocsps[i]; + const result = await ocsp.getCertificateStatus(certificate, issuerCertificate, crypto); + if (result.isForCertificate) { + if (result.status === 0) + return 0; + return 1; + } + } + return 2; + }; + async function checkForCA(certificate, needToCheckCRL = false) { + let isCA = false; + let mustBeCA = false; + let keyUsagePresent = false; + let cRLSign = false; + if (certificate.extensions) { + for (let j = 0; j < certificate.extensions.length; j++) { + const extension = certificate.extensions[j]; + if (extension.critical && !extension.parsedValue) { + return { + result: false, + resultCode: 6, + resultMessage: `Unable to parse critical certificate extension: ${extension.extnID}` + }; + } + if (extension.extnID === id_KeyUsage) { + keyUsagePresent = true; + const view = new Uint8Array(extension.parsedValue.valueBlock.valueHex); + if ((view[0] & 0x04) === 0x04) + mustBeCA = true; + if ((view[0] & 0x02) === 0x02) + cRLSign = true; + } + if (extension.extnID === id_BasicConstraints) { + if ("cA" in extension.parsedValue) { + if (extension.parsedValue.cA === true) + isCA = true; + } + } + } + if ((mustBeCA === true) && (isCA === false)) { + return { + result: false, + resultCode: 3, + resultMessage: "Unable to build certificate chain - using \"keyCertSign\" flag set without BasicConstraints" + }; + } + if ((keyUsagePresent === true) && (isCA === true) && (mustBeCA === false)) { + return { + result: false, + resultCode: 4, + resultMessage: "Unable to build certificate chain - \"keyCertSign\" flag was not set" + }; + } + if ((isCA === true) && (keyUsagePresent === true) && ((needToCheckCRL) && (cRLSign === false))) { + return { + result: false, + resultCode: 5, + resultMessage: "Unable to build certificate chain - intermediate certificate must have \"cRLSign\" key usage flag" + }; + } + } + if (isCA === false) { + return { + result: false, + resultCode: 7, + resultMessage: "Unable to build certificate chain - more than one possible end-user certificate" + }; + } + return { + result: true, + resultCode: 0, + resultMessage: EMPTY_STRING + }; + } + const basicCheck = async (path, checkDate) => { + for (let i = 0; i < path.length; i++) { + if ((path[i].notBefore.value > checkDate) || + (path[i].notAfter.value < checkDate)) { + return { + result: false, + resultCode: 8, + resultMessage: "The certificate is either not yet valid or expired" + }; + } + } + if (path.length < 2) { + return { + result: false, + resultCode: 9, + resultMessage: "Too short certificate path" + }; + } + for (let i = (path.length - 2); i >= 0; i--) { + if (path[i].issuer.isEqual(path[i].subject) === false) { + if (path[i].issuer.isEqual(path[i + 1].subject) === false) { + return { + result: false, + resultCode: 10, + resultMessage: "Incorrect name chaining" + }; + } + } + } + if ((this.crls.length !== 0) || (this.ocsps.length !== 0)) { + for (let i = 0; i < (path.length - 1); i++) { + let ocspResult = 2; + let crlResult = { + status: 0, + statusMessage: EMPTY_STRING + }; + if (this.ocsps.length !== 0) { + ocspResult = await findOCSP(path[i], path[i + 1]); + switch (ocspResult) { + case 0: + continue; + case 1: + return { + result: false, + resultCode: 12, + resultMessage: "One of certificates was revoked via OCSP response" + }; + } + } + if (this.crls.length !== 0) { + crlResult = await findCRL(path[i]); + if (crlResult.status === 0 && crlResult.result) { + for (let j = 0; j < crlResult.result.length; j++) { + const isCertificateRevoked = crlResult.result[j].crl.isCertificateRevoked(path[i]); + if (isCertificateRevoked) { + return { + result: false, + resultCode: 12, + resultMessage: "One of certificates had been revoked" + }; + } + const isCertificateCA = await checkForCA(crlResult.result[j].certificate, true); + if (isCertificateCA.result === false) { + return { + result: false, + resultCode: 13, + resultMessage: "CRL issuer certificate is not a CA certificate or does not have crlSign flag" + }; + } + } + } + else { + if (passedWhenNotRevValues === false) { + throw new ChainValidationError(ChainValidationCode.noRevocation, `No revocation values found for one of certificates: ${crlResult.statusMessage}`); + } + } + } + else { + if (ocspResult === 2) { + return { + result: false, + resultCode: 11, + resultMessage: "No revocation values found for one of certificates" + }; + } + } + if ((ocspResult === 2) && (crlResult.status === 2) && passedWhenNotRevValues) { + const issuerCertificate = path[i + 1]; + let extensionFound = false; + if (issuerCertificate.extensions) { + for (const extension of issuerCertificate.extensions) { + switch (extension.extnID) { + case id_CRLDistributionPoints: + case id_FreshestCRL: + case id_AuthorityInfoAccess: + extensionFound = true; + break; + } + } + } + if (extensionFound) { + throw new ChainValidationError(ChainValidationCode.noRevocation, `No revocation values found for one of certificates: ${crlResult.statusMessage}`); + } + } + } + } + for (const [i, cert] of path.entries()) { + if (!i) { + continue; + } + const result = await checkForCA(cert); + if (!result.result) { + return { + result: false, + resultCode: 14, + resultMessage: "One of intermediate certificates is not a CA certificate" + }; + } + } + return { + result: true + }; + }; + localCerts.push(...this.trustedCerts); + localCerts.push(...this.certs); + for (let i = 0; i < localCerts.length; i++) { + for (let j = 0; j < localCerts.length; j++) { + if (i === j) + continue; + if (BufferSourceConverter.isEqual(localCerts[i].tbsView, localCerts[j].tbsView)) { + localCerts.splice(j, 1); + i = 0; + break; + } + } + } + const leafCert = localCerts[localCerts.length - 1]; + let result; + const certificatePath = [leafCert]; + result = await buildPath(leafCert, crypto); + if (result.length === 0) { + throw new ChainValidationError(ChainValidationCode.noPath, "Unable to find certificate path"); + } + for (let i = result.length - 1; i >= 0; i--) { + let found = false; + for (let j = 0; j < (result[i]).length; j++) { + const certificate = (result[i])[j]; + for (let k = 0; k < this.trustedCerts.length; k++) { + if (BufferSourceConverter.isEqual(certificate.tbsView, this.trustedCerts[k].tbsView)) { + found = true; + break; + } + } + if (found) + break; + } + if (!found) { + result.splice(i, 1); + } + } + if (result.length === 0) { + throw new ChainValidationError(ChainValidationCode.noValidPath, "No valid certificate paths found"); + } + let shortestLength = result[0].length; + let shortestIndex = 0; + for (let i = 0; i < result.length; i++) { + if (result[i].length < shortestLength) { + shortestLength = result[i].length; + shortestIndex = i; + } + } + for (let i = 0; i < result[shortestIndex].length; i++) + certificatePath.push((result[shortestIndex])[i]); + result = await basicCheck(certificatePath, this.checkDate); + if (result.result === false) + throw result; + return certificatePath; + } + async verify(parameters = {}, crypto = getCrypto(true)) { + function compareDNSName(name, constraint) { + const namePrepared = stringPrep(name); + const constraintPrepared = stringPrep(constraint); + const nameSplitted = namePrepared.split("."); + const constraintSplitted = constraintPrepared.split("."); + const nameLen = nameSplitted.length; + const constrLen = constraintSplitted.length; + if ((nameLen === 0) || (constrLen === 0) || (nameLen < constrLen)) { + return false; + } + for (let i = 0; i < nameLen; i++) { + if (nameSplitted[i].length === 0) { + return false; + } + } + for (let i = 0; i < constrLen; i++) { + if (constraintSplitted[i].length === 0) { + if (i === 0) { + if (constrLen === 1) { + return false; + } + continue; + } + return false; + } + } + for (let i = 0; i < constrLen; i++) { + if (constraintSplitted[constrLen - 1 - i].length === 0) { + continue; + } + if (nameSplitted[nameLen - 1 - i].localeCompare(constraintSplitted[constrLen - 1 - i]) !== 0) { + return false; + } + } + return true; + } + function compareRFC822Name(name, constraint) { + const namePrepared = stringPrep(name); + const constraintPrepared = stringPrep(constraint); + const nameSplitted = namePrepared.split("@"); + const constraintSplitted = constraintPrepared.split("@"); + if ((nameSplitted.length === 0) || (constraintSplitted.length === 0) || (nameSplitted.length < constraintSplitted.length)) + return false; + if (constraintSplitted.length === 1) { + const result = compareDNSName(nameSplitted[1], constraintSplitted[0]); + if (result) { + const ns = nameSplitted[1].split("."); + const cs = constraintSplitted[0].split("."); + if (cs[0].length === 0) + return true; + return ns.length === cs.length; + } + return false; + } + return (namePrepared.localeCompare(constraintPrepared) === 0); + } + function compareUniformResourceIdentifier(name, constraint) { + let namePrepared = stringPrep(name); + const constraintPrepared = stringPrep(constraint); + const ns = namePrepared.split("/"); + const cs = constraintPrepared.split("/"); + if (cs.length > 1) + return false; + if (ns.length > 1) { + for (let i = 0; i < ns.length; i++) { + if ((ns[i].length > 0) && (ns[i].charAt(ns[i].length - 1) !== ":")) { + const nsPort = ns[i].split(":"); + namePrepared = nsPort[0]; + break; + } + } + } + const result = compareDNSName(namePrepared, constraintPrepared); + if (result) { + const nameSplitted = namePrepared.split("."); + const constraintSplitted = constraintPrepared.split("."); + if (constraintSplitted[0].length === 0) + return true; + return nameSplitted.length === constraintSplitted.length; + } + return false; + } + function compareIPAddress(name, constraint) { + const nameView = name.valueBlock.valueHexView; + const constraintView = constraint.valueBlock.valueHexView; + if ((nameView.length === 4) && (constraintView.length === 8)) { + for (let i = 0; i < 4; i++) { + if ((nameView[i] ^ constraintView[i]) & constraintView[i + 4]) + return false; + } + return true; + } + if ((nameView.length === 16) && (constraintView.length === 32)) { + for (let i = 0; i < 16; i++) { + if ((nameView[i] ^ constraintView[i]) & constraintView[i + 16]) + return false; + } + return true; + } + return false; + } + function compareDirectoryName(name, constraint) { + if ((name.typesAndValues.length === 0) || (constraint.typesAndValues.length === 0)) + return true; + if (name.typesAndValues.length < constraint.typesAndValues.length) + return false; + let result = true; + let nameStart = 0; + for (let i = 0; i < constraint.typesAndValues.length; i++) { + let localResult = false; + for (let j = nameStart; j < name.typesAndValues.length; j++) { + localResult = name.typesAndValues[j].isEqual(constraint.typesAndValues[i]); + if (name.typesAndValues[j].type === constraint.typesAndValues[i].type) + result = result && localResult; + if (localResult === true) { + if ((nameStart === 0) || (nameStart === j)) { + nameStart = j + 1; + break; + } + else + return false; + } + } + if (localResult === false) + return false; + } + return (nameStart === 0) ? false : result; + } + try { + if (this.certs.length === 0) + throw new Error("Empty certificate array"); + const passedWhenNotRevValues = parameters.passedWhenNotRevValues || false; + const initialPolicySet = parameters.initialPolicySet || [id_AnyPolicy]; + const initialExplicitPolicy = parameters.initialExplicitPolicy || false; + const initialPolicyMappingInhibit = parameters.initialPolicyMappingInhibit || false; + const initialInhibitPolicy = parameters.initialInhibitPolicy || false; + const initialPermittedSubtreesSet = parameters.initialPermittedSubtreesSet || []; + const initialExcludedSubtreesSet = parameters.initialExcludedSubtreesSet || []; + const initialRequiredNameForms = parameters.initialRequiredNameForms || []; + let explicitPolicyIndicator = initialExplicitPolicy; + let policyMappingInhibitIndicator = initialPolicyMappingInhibit; + let inhibitAnyPolicyIndicator = initialInhibitPolicy; + const pendingConstraints = [ + false, + false, + false, + ]; + let explicitPolicyPending = 0; + let policyMappingInhibitPending = 0; + let inhibitAnyPolicyPending = 0; + let permittedSubtrees = initialPermittedSubtreesSet; + let excludedSubtrees = initialExcludedSubtreesSet; + const requiredNameForms = initialRequiredNameForms; + let pathDepth = 1; + this.certs = await this.sort(passedWhenNotRevValues, crypto); + const allPolicies = []; + allPolicies.push(id_AnyPolicy); + const policiesAndCerts = []; + const anyPolicyArray = new Array(this.certs.length - 1); + for (let ii = 0; ii < (this.certs.length - 1); ii++) + anyPolicyArray[ii] = true; + policiesAndCerts.push(anyPolicyArray); + const policyMappings = new Array(this.certs.length - 1); + const certPolicies = new Array(this.certs.length - 1); + let explicitPolicyStart = (explicitPolicyIndicator) ? (this.certs.length - 1) : (-1); + for (let i = (this.certs.length - 2); i >= 0; i--, pathDepth++) { + const cert = this.certs[i]; + if (cert.extensions) { + for (let j = 0; j < cert.extensions.length; j++) { + const extension = cert.extensions[j]; + if (extension.extnID === id_CertificatePolicies) { + certPolicies[i] = extension.parsedValue; + for (let s = 0; s < allPolicies.length; s++) { + if (allPolicies[s] === id_AnyPolicy) { + delete (policiesAndCerts[s])[i]; + break; + } + } + for (let k = 0; k < extension.parsedValue.certificatePolicies.length; k++) { + let policyIndex = (-1); + const policyId = extension.parsedValue.certificatePolicies[k].policyIdentifier; + for (let s = 0; s < allPolicies.length; s++) { + if (policyId === allPolicies[s]) { + policyIndex = s; + break; + } + } + if (policyIndex === (-1)) { + allPolicies.push(policyId); + const certArray = new Array(this.certs.length - 1); + certArray[i] = true; + policiesAndCerts.push(certArray); + } + else + (policiesAndCerts[policyIndex])[i] = true; + } + } + if (extension.extnID === id_PolicyMappings) { + if (policyMappingInhibitIndicator) { + return { + result: false, + resultCode: 98, + resultMessage: "Policy mapping prohibited" + }; + } + policyMappings[i] = extension.parsedValue; + } + if (extension.extnID === id_PolicyConstraints) { + if (explicitPolicyIndicator === false) { + if (extension.parsedValue.requireExplicitPolicy === 0) { + explicitPolicyIndicator = true; + explicitPolicyStart = i; + } + else { + if (pendingConstraints[0] === false) { + pendingConstraints[0] = true; + explicitPolicyPending = extension.parsedValue.requireExplicitPolicy; + } + else + explicitPolicyPending = (explicitPolicyPending > extension.parsedValue.requireExplicitPolicy) ? extension.parsedValue.requireExplicitPolicy : explicitPolicyPending; + } + if (extension.parsedValue.inhibitPolicyMapping === 0) + policyMappingInhibitIndicator = true; + else { + if (pendingConstraints[1] === false) { + pendingConstraints[1] = true; + policyMappingInhibitPending = extension.parsedValue.inhibitPolicyMapping + 1; + } + else + policyMappingInhibitPending = (policyMappingInhibitPending > (extension.parsedValue.inhibitPolicyMapping + 1)) ? (extension.parsedValue.inhibitPolicyMapping + 1) : policyMappingInhibitPending; + } + } + } + if (extension.extnID === id_InhibitAnyPolicy) { + if (inhibitAnyPolicyIndicator === false) { + if (extension.parsedValue.valueBlock.valueDec === 0) + inhibitAnyPolicyIndicator = true; + else { + if (pendingConstraints[2] === false) { + pendingConstraints[2] = true; + inhibitAnyPolicyPending = extension.parsedValue.valueBlock.valueDec; + } + else + inhibitAnyPolicyPending = (inhibitAnyPolicyPending > extension.parsedValue.valueBlock.valueDec) ? extension.parsedValue.valueBlock.valueDec : inhibitAnyPolicyPending; + } + } + } + } + if (inhibitAnyPolicyIndicator === true) { + let policyIndex = (-1); + for (let searchAnyPolicy = 0; searchAnyPolicy < allPolicies.length; searchAnyPolicy++) { + if (allPolicies[searchAnyPolicy] === id_AnyPolicy) { + policyIndex = searchAnyPolicy; + break; + } + } + if (policyIndex !== (-1)) + delete (policiesAndCerts[0])[i]; + } + if (explicitPolicyIndicator === false) { + if (pendingConstraints[0] === true) { + explicitPolicyPending--; + if (explicitPolicyPending === 0) { + explicitPolicyIndicator = true; + explicitPolicyStart = i; + pendingConstraints[0] = false; + } + } + } + if (policyMappingInhibitIndicator === false) { + if (pendingConstraints[1] === true) { + policyMappingInhibitPending--; + if (policyMappingInhibitPending === 0) { + policyMappingInhibitIndicator = true; + pendingConstraints[1] = false; + } + } + } + if (inhibitAnyPolicyIndicator === false) { + if (pendingConstraints[2] === true) { + inhibitAnyPolicyPending--; + if (inhibitAnyPolicyPending === 0) { + inhibitAnyPolicyIndicator = true; + pendingConstraints[2] = false; + } + } + } + } + } + for (let i = 0; i < (this.certs.length - 1); i++) { + if ((i < (this.certs.length - 2)) && (typeof policyMappings[i + 1] !== "undefined")) { + for (let k = 0; k < policyMappings[i + 1].mappings.length; k++) { + if ((policyMappings[i + 1].mappings[k].issuerDomainPolicy === id_AnyPolicy) || (policyMappings[i + 1].mappings[k].subjectDomainPolicy === id_AnyPolicy)) { + return { + result: false, + resultCode: 99, + resultMessage: "The \"anyPolicy\" should not be a part of policy mapping scheme" + }; + } + let issuerDomainPolicyIndex = (-1); + let subjectDomainPolicyIndex = (-1); + for (let n = 0; n < allPolicies.length; n++) { + if (allPolicies[n] === policyMappings[i + 1].mappings[k].issuerDomainPolicy) + issuerDomainPolicyIndex = n; + if (allPolicies[n] === policyMappings[i + 1].mappings[k].subjectDomainPolicy) + subjectDomainPolicyIndex = n; + } + if (typeof (policiesAndCerts[issuerDomainPolicyIndex])[i] !== "undefined") + delete (policiesAndCerts[issuerDomainPolicyIndex])[i]; + for (let j = 0; j < certPolicies[i].certificatePolicies.length; j++) { + if (policyMappings[i + 1].mappings[k].subjectDomainPolicy === certPolicies[i].certificatePolicies[j].policyIdentifier) { + if ((issuerDomainPolicyIndex !== (-1)) && (subjectDomainPolicyIndex !== (-1))) { + for (let m = 0; m <= i; m++) { + if (typeof (policiesAndCerts[subjectDomainPolicyIndex])[m] !== "undefined") { + (policiesAndCerts[issuerDomainPolicyIndex])[m] = true; + delete (policiesAndCerts[subjectDomainPolicyIndex])[m]; + } + } + } + } + } + } + } + } + for (let i = 0; i < allPolicies.length; i++) { + if (allPolicies[i] === id_AnyPolicy) { + for (let j = 0; j < explicitPolicyStart; j++) + delete (policiesAndCerts[i])[j]; + } + } + const authConstrPolicies = []; + for (let i = 0; i < policiesAndCerts.length; i++) { + let found = true; + for (let j = 0; j < (this.certs.length - 1); j++) { + let anyPolicyFound = false; + if ((j < explicitPolicyStart) && (allPolicies[i] === id_AnyPolicy) && (allPolicies.length > 1)) { + found = false; + break; + } + if (typeof (policiesAndCerts[i])[j] === "undefined") { + if (j >= explicitPolicyStart) { + for (let k = 0; k < allPolicies.length; k++) { + if (allPolicies[k] === id_AnyPolicy) { + if ((policiesAndCerts[k])[j] === true) + anyPolicyFound = true; + break; + } + } + } + if (!anyPolicyFound) { + found = false; + break; + } + } + } + if (found === true) + authConstrPolicies.push(allPolicies[i]); + } + let userConstrPolicies = []; + if ((initialPolicySet.length === 1) && (initialPolicySet[0] === id_AnyPolicy) && (explicitPolicyIndicator === false)) + userConstrPolicies = initialPolicySet; + else { + if ((authConstrPolicies.length === 1) && (authConstrPolicies[0] === id_AnyPolicy)) + userConstrPolicies = initialPolicySet; + else { + for (let i = 0; i < authConstrPolicies.length; i++) { + for (let j = 0; j < initialPolicySet.length; j++) { + if ((initialPolicySet[j] === authConstrPolicies[i]) || (initialPolicySet[j] === id_AnyPolicy)) { + userConstrPolicies.push(authConstrPolicies[i]); + break; + } + } + } + } + } + const policyResult = { + result: (userConstrPolicies.length > 0), + resultCode: 0, + resultMessage: (userConstrPolicies.length > 0) ? EMPTY_STRING : "Zero \"userConstrPolicies\" array, no intersections with \"authConstrPolicies\"", + authConstrPolicies, + userConstrPolicies, + explicitPolicyIndicator, + policyMappings, + certificatePath: this.certs + }; + if (userConstrPolicies.length === 0) + return policyResult; + if (policyResult.result === false) + return policyResult; + pathDepth = 1; + for (let i = (this.certs.length - 2); i >= 0; i--, pathDepth++) { + const cert = this.certs[i]; + let subjectAltNames = []; + let certPermittedSubtrees = []; + let certExcludedSubtrees = []; + if (cert.extensions) { + for (let j = 0; j < cert.extensions.length; j++) { + const extension = cert.extensions[j]; + if (extension.extnID === id_NameConstraints) { + if ("permittedSubtrees" in extension.parsedValue) + certPermittedSubtrees = certPermittedSubtrees.concat(extension.parsedValue.permittedSubtrees); + if ("excludedSubtrees" in extension.parsedValue) + certExcludedSubtrees = certExcludedSubtrees.concat(extension.parsedValue.excludedSubtrees); + } + if (extension.extnID === id_SubjectAltName) + subjectAltNames = subjectAltNames.concat(extension.parsedValue.altNames); + } + } + let formFound = (requiredNameForms.length <= 0); + for (let j = 0; j < requiredNameForms.length; j++) { + switch (requiredNameForms[j].base.type) { + case 4: + { + if (requiredNameForms[j].base.value.typesAndValues.length !== cert.subject.typesAndValues.length) + continue; + formFound = true; + for (let k = 0; k < cert.subject.typesAndValues.length; k++) { + if (cert.subject.typesAndValues[k].type !== requiredNameForms[j].base.value.typesAndValues[k].type) { + formFound = false; + break; + } + } + if (formFound === true) + break; + } + break; + default: + } + } + if (formFound === false) { + policyResult.result = false; + policyResult.resultCode = 21; + policyResult.resultMessage = "No necessary name form found"; + throw policyResult; + } + const constrGroups = [ + [], + [], + [], + [], + [], + ]; + for (let j = 0; j < permittedSubtrees.length; j++) { + switch (permittedSubtrees[j].base.type) { + case 1: + constrGroups[0].push(permittedSubtrees[j]); + break; + case 2: + constrGroups[1].push(permittedSubtrees[j]); + break; + case 4: + constrGroups[2].push(permittedSubtrees[j]); + break; + case 6: + constrGroups[3].push(permittedSubtrees[j]); + break; + case 7: + constrGroups[4].push(permittedSubtrees[j]); + break; + default: + } + } + for (let p = 0; p < 5; p++) { + let groupPermitted = false; + let valueExists = false; + const group = constrGroups[p]; + for (let j = 0; j < group.length; j++) { + switch (p) { + case 0: + if (subjectAltNames.length > 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 1) { + valueExists = true; + groupPermitted = groupPermitted || compareRFC822Name(subjectAltNames[k].value, group[j].base.value); + } + } + } + else { + for (let k = 0; k < cert.subject.typesAndValues.length; k++) { + if ((cert.subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") || + (cert.subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) { + valueExists = true; + groupPermitted = groupPermitted || compareRFC822Name(cert.subject.typesAndValues[k].value.valueBlock.value, group[j].base.value); + } + } + } + break; + case 1: + if (subjectAltNames.length > 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 2) { + valueExists = true; + groupPermitted = groupPermitted || compareDNSName(subjectAltNames[k].value, group[j].base.value); + } + } + } + break; + case 2: + valueExists = true; + groupPermitted = compareDirectoryName(cert.subject, group[j].base.value); + break; + case 3: + if (subjectAltNames.length > 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 6) { + valueExists = true; + groupPermitted = groupPermitted || compareUniformResourceIdentifier(subjectAltNames[k].value, group[j].base.value); + } + } + } + break; + case 4: + if (subjectAltNames.length > 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 7) { + valueExists = true; + groupPermitted = groupPermitted || compareIPAddress(subjectAltNames[k].value, group[j].base.value); + } + } + } + break; + default: + } + if (groupPermitted) + break; + } + if ((groupPermitted === false) && (group.length > 0) && valueExists) { + policyResult.result = false; + policyResult.resultCode = 41; + policyResult.resultMessage = "Failed to meet \"permitted sub-trees\" name constraint"; + throw policyResult; + } + } + let excluded = false; + for (let j = 0; j < excludedSubtrees.length; j++) { + switch (excludedSubtrees[j].base.type) { + case 1: + if (subjectAltNames.length >= 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 1) + excluded = excluded || compareRFC822Name(subjectAltNames[k].value, excludedSubtrees[j].base.value); + } + } + else { + for (let k = 0; k < cert.subject.typesAndValues.length; k++) { + if ((cert.subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") || + (cert.subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) + excluded = excluded || compareRFC822Name(cert.subject.typesAndValues[k].value.valueBlock.value, excludedSubtrees[j].base.value); + } + } + break; + case 2: + if (subjectAltNames.length > 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 2) + excluded = excluded || compareDNSName(subjectAltNames[k].value, excludedSubtrees[j].base.value); + } + } + break; + case 4: + excluded = excluded || compareDirectoryName(cert.subject, excludedSubtrees[j].base.value); + break; + case 6: + if (subjectAltNames.length > 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 6) + excluded = excluded || compareUniformResourceIdentifier(subjectAltNames[k].value, excludedSubtrees[j].base.value); + } + } + break; + case 7: + if (subjectAltNames.length > 0) { + for (let k = 0; k < subjectAltNames.length; k++) { + if (subjectAltNames[k].type === 7) + excluded = excluded || compareIPAddress(subjectAltNames[k].value, excludedSubtrees[j].base.value); + } + } + break; + default: + } + if (excluded) + break; + } + if (excluded === true) { + policyResult.result = false; + policyResult.resultCode = 42; + policyResult.resultMessage = "Failed to meet \"excluded sub-trees\" name constraint"; + throw policyResult; + } + permittedSubtrees = permittedSubtrees.concat(certPermittedSubtrees); + excludedSubtrees = excludedSubtrees.concat(certExcludedSubtrees); + } + return policyResult; + } + catch (error) { + if (error instanceof Error) { + if (error instanceof ChainValidationError) { + return { + result: false, + resultCode: error.code, + resultMessage: error.message, + error: error, + }; + } + return { + result: false, + resultCode: ChainValidationCode.unknown, + resultMessage: error.message, + error: error, + }; + } + if (error && typeof error === "object" && "resultMessage" in error) { + return error; + } + return { + result: false, + resultCode: -1, + resultMessage: `${error}`, + }; + } + } } -const TBS_RESPONSE_DATA = "tbsResponseData"; -const SIGNATURE_ALGORITHM$3 = "signatureAlgorithm"; -const SIGNATURE$2 = "signature"; -const CERTS$1 = "certs"; -const BASIC_OCSP_RESPONSE = "BasicOCSPResponse"; -const BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA = `${BASIC_OCSP_RESPONSE}.${TBS_RESPONSE_DATA}`; -const BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM = `${BASIC_OCSP_RESPONSE}.${SIGNATURE_ALGORITHM$3}`; -const BASIC_OCSP_RESPONSE_SIGNATURE = `${BASIC_OCSP_RESPONSE}.${SIGNATURE$2}`; -const BASIC_OCSP_RESPONSE_CERTS = `${BASIC_OCSP_RESPONSE}.${CERTS$1}`; -const CLEAR_PROPS$g = [ - BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA, - BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM, - BASIC_OCSP_RESPONSE_SIGNATURE, - BASIC_OCSP_RESPONSE_CERTS -]; -class BasicOCSPResponse extends PkiObject { - constructor(parameters = {}) { - super(); - this.tbsResponseData = getParametersValue(parameters, TBS_RESPONSE_DATA, BasicOCSPResponse.defaultValues(TBS_RESPONSE_DATA)); - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$3, BasicOCSPResponse.defaultValues(SIGNATURE_ALGORITHM$3)); - this.signature = getParametersValue(parameters, SIGNATURE$2, BasicOCSPResponse.defaultValues(SIGNATURE$2)); - if (CERTS$1 in parameters) { - this.certs = getParametersValue(parameters, CERTS$1, BasicOCSPResponse.defaultValues(CERTS$1)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TBS_RESPONSE_DATA: - return new ResponseData(); - case SIGNATURE_ALGORITHM$3: - return new AlgorithmIdentifier(); - case SIGNATURE$2: - return new BitString(); - case CERTS$1: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case "type": - { - let comparisonResult = ((ResponseData.compareWithDefault("tbs", memberValue.tbs)) && - (ResponseData.compareWithDefault("responderID", memberValue.responderID)) && - (ResponseData.compareWithDefault("producedAt", memberValue.producedAt)) && - (ResponseData.compareWithDefault("responses", memberValue.responses))); - if ("responseExtensions" in memberValue) - comparisonResult = comparisonResult && (ResponseData.compareWithDefault("responseExtensions", memberValue.responseExtensions)); - return comparisonResult; - } - case SIGNATURE_ALGORITHM$3: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case SIGNATURE$2: - return (memberValue.isEqual(BasicOCSPResponse.defaultValues(memberName))); - case CERTS$1: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || BASIC_OCSP_RESPONSE), - value: [ - ResponseData.schema(names.tbsResponseData || { - names: { - blockName: BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA - } - }), - AlgorithmIdentifier.schema(names.signatureAlgorithm || { - names: { - blockName: BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM - } - }), - new BitString({ name: (names.signature || BASIC_OCSP_RESPONSE_SIGNATURE) }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Sequence({ - value: [new Repeated({ - name: BASIC_OCSP_RESPONSE_CERTS, - value: Certificate.schema(names.certs || {}) - })] - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$g); - const asn1 = compareSchema(schema, schema, BasicOCSPResponse.schema()); - AsnError.assertSchema(asn1, this.className); - this.tbsResponseData = new ResponseData({ schema: asn1.result[BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA] }); - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result[BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM] }); - this.signature = asn1.result[BASIC_OCSP_RESPONSE_SIGNATURE]; - if (BASIC_OCSP_RESPONSE_CERTS in asn1.result) { - this.certs = Array.from(asn1.result[BASIC_OCSP_RESPONSE_CERTS], element => new Certificate({ schema: element })); - } - } - toSchema() { - const outputArray = []; - outputArray.push(this.tbsResponseData.toSchema()); - outputArray.push(this.signatureAlgorithm.toSchema()); - outputArray.push(this.signature); - if (this.certs) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Sequence({ - value: Array.from(this.certs, o => o.toSchema()) - }) - ] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - tbsResponseData: this.tbsResponseData.toJSON(), - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signature: this.signature.toJSON(), - }; - if (this.certs) { - res.certs = Array.from(this.certs, o => o.toJSON()); - } - return res; - } - getCertificateStatus(certificate, issuerCertificate, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const result = { - isForCertificate: false, - status: 2 - }; - const hashesObject = {}; - const certIDs = []; - for (const response of this.tbsResponseData.responses) { - const hashAlgorithm = crypto.getAlgorithmByOID(response.certID.hashAlgorithm.algorithmId, true, "CertID.hashAlgorithm"); - if (!hashesObject[hashAlgorithm.name]) { - hashesObject[hashAlgorithm.name] = 1; - const certID = new CertID(); - certIDs.push(certID); - yield certID.createForCertificate(certificate, { - hashAlgorithm: hashAlgorithm.name, - issuerCertificate - }, crypto); - } - } - for (const response of this.tbsResponseData.responses) { - for (const id of certIDs) { - if (response.certID.isEqual(id)) { - result.isForCertificate = true; - try { - switch (response.certStatus.idBlock.isConstructed) { - case true: - if (response.certStatus.idBlock.tagNumber === 1) - result.status = 1; - break; - case false: - switch (response.certStatus.idBlock.tagNumber) { - case 0: - result.status = 0; - break; - case 2: - result.status = 2; - break; - default: - } - break; - default: - } - } - catch (ex) { - } - return result; - } - } - } - return result; - }); - } - sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - if (!privateKey) { - throw new Error("Need to provide a private key for signing"); - } - const signatureParams = yield crypto.getSignatureParameters(privateKey, hashAlgorithm); - const algorithm = signatureParams.parameters.algorithm; - if (!("name" in algorithm)) { - throw new Error("Empty algorithm"); - } - this.signatureAlgorithm = signatureParams.signatureAlgorithm; - this.tbsResponseData.tbsView = new Uint8Array(this.tbsResponseData.toSchema(true).toBER()); - const signature = yield crypto.signWithPrivateKey(this.tbsResponseData.tbsView, privateKey, { algorithm }); - this.signature = new BitString({ valueHex: signature }); - }); - } - verify(params = {}, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - let signerCert = null; - let certIndex = -1; - const trustedCerts = params.trustedCerts || []; - if (!this.certs) { - throw new Error("No certificates attached to the BasicOCSPResponse"); - } - switch (true) { - case (this.tbsResponseData.responderID instanceof RelativeDistinguishedNames): - for (const [index, certificate] of this.certs.entries()) { - if (certificate.subject.isEqual(this.tbsResponseData.responderID)) { - certIndex = index; - break; - } - } - break; - case (this.tbsResponseData.responderID instanceof OctetString): - for (const [index, cert] of this.certs.entries()) { - const hash = yield crypto.digest({ name: "sha-1" }, cert.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); - if (isEqualBuffer(hash, this.tbsResponseData.responderID.valueBlock.valueHex)) { - certIndex = index; - break; - } - } - break; - default: - throw new Error("Wrong value for responderID"); - } - if (certIndex === (-1)) - throw new Error("Correct certificate was not found in OCSP response"); - signerCert = this.certs[certIndex]; - const additionalCerts = [signerCert]; - for (const cert of this.certs) { - const caCert = yield checkCA(cert, signerCert); - if (caCert) { - additionalCerts.push(caCert); - } - } - const certChain = new CertificateChainValidationEngine({ - certs: additionalCerts, - trustedCerts, - }); - const verificationResult = yield certChain.verify({}, crypto); - if (!verificationResult.result) { - throw new Error("Validation of signer's certificate failed"); - } - return crypto.verifyWithPublicKey(this.tbsResponseData.tbsView, this.signature, this.certs[certIndex].subjectPublicKeyInfo, this.signatureAlgorithm); - }); - } -} +const TBS_RESPONSE_DATA = "tbsResponseData"; +const SIGNATURE_ALGORITHM$3 = "signatureAlgorithm"; +const SIGNATURE$2 = "signature"; +const CERTS$1 = "certs"; +const BASIC_OCSP_RESPONSE = "BasicOCSPResponse"; +const BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA = `${BASIC_OCSP_RESPONSE}.${TBS_RESPONSE_DATA}`; +const BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM = `${BASIC_OCSP_RESPONSE}.${SIGNATURE_ALGORITHM$3}`; +const BASIC_OCSP_RESPONSE_SIGNATURE = `${BASIC_OCSP_RESPONSE}.${SIGNATURE$2}`; +const BASIC_OCSP_RESPONSE_CERTS = `${BASIC_OCSP_RESPONSE}.${CERTS$1}`; +const CLEAR_PROPS$g = [ + BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA, + BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM, + BASIC_OCSP_RESPONSE_SIGNATURE, + BASIC_OCSP_RESPONSE_CERTS +]; +class BasicOCSPResponse extends PkiObject { + constructor(parameters = {}) { + super(); + this.tbsResponseData = getParametersValue(parameters, TBS_RESPONSE_DATA, BasicOCSPResponse.defaultValues(TBS_RESPONSE_DATA)); + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$3, BasicOCSPResponse.defaultValues(SIGNATURE_ALGORITHM$3)); + this.signature = getParametersValue(parameters, SIGNATURE$2, BasicOCSPResponse.defaultValues(SIGNATURE$2)); + if (CERTS$1 in parameters) { + this.certs = getParametersValue(parameters, CERTS$1, BasicOCSPResponse.defaultValues(CERTS$1)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TBS_RESPONSE_DATA: + return new ResponseData(); + case SIGNATURE_ALGORITHM$3: + return new AlgorithmIdentifier(); + case SIGNATURE$2: + return new BitString(); + case CERTS$1: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case "type": + { + let comparisonResult = ((ResponseData.compareWithDefault("tbs", memberValue.tbs)) && + (ResponseData.compareWithDefault("responderID", memberValue.responderID)) && + (ResponseData.compareWithDefault("producedAt", memberValue.producedAt)) && + (ResponseData.compareWithDefault("responses", memberValue.responses))); + if ("responseExtensions" in memberValue) + comparisonResult = comparisonResult && (ResponseData.compareWithDefault("responseExtensions", memberValue.responseExtensions)); + return comparisonResult; + } + case SIGNATURE_ALGORITHM$3: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case SIGNATURE$2: + return (memberValue.isEqual(BasicOCSPResponse.defaultValues(memberName))); + case CERTS$1: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || BASIC_OCSP_RESPONSE), + value: [ + ResponseData.schema(names.tbsResponseData || { + names: { + blockName: BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA + } + }), + AlgorithmIdentifier.schema(names.signatureAlgorithm || { + names: { + blockName: BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM + } + }), + new BitString({ name: (names.signature || BASIC_OCSP_RESPONSE_SIGNATURE) }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Sequence({ + value: [new Repeated({ + name: BASIC_OCSP_RESPONSE_CERTS, + value: Certificate.schema(names.certs || {}) + })] + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$g); + const asn1 = compareSchema(schema, schema, BasicOCSPResponse.schema()); + AsnError.assertSchema(asn1, this.className); + this.tbsResponseData = new ResponseData({ schema: asn1.result[BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA] }); + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result[BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM] }); + this.signature = asn1.result[BASIC_OCSP_RESPONSE_SIGNATURE]; + if (BASIC_OCSP_RESPONSE_CERTS in asn1.result) { + this.certs = Array.from(asn1.result[BASIC_OCSP_RESPONSE_CERTS], element => new Certificate({ schema: element })); + } + } + toSchema() { + const outputArray = []; + outputArray.push(this.tbsResponseData.toSchema()); + outputArray.push(this.signatureAlgorithm.toSchema()); + outputArray.push(this.signature); + if (this.certs) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Sequence({ + value: Array.from(this.certs, o => o.toSchema()) + }) + ] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + tbsResponseData: this.tbsResponseData.toJSON(), + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signature: this.signature.toJSON(), + }; + if (this.certs) { + res.certs = Array.from(this.certs, o => o.toJSON()); + } + return res; + } + async getCertificateStatus(certificate, issuerCertificate, crypto = getCrypto(true)) { + const result = { + isForCertificate: false, + status: 2 + }; + const hashesObject = {}; + const certIDs = []; + for (const response of this.tbsResponseData.responses) { + const hashAlgorithm = crypto.getAlgorithmByOID(response.certID.hashAlgorithm.algorithmId, true, "CertID.hashAlgorithm"); + if (!hashesObject[hashAlgorithm.name]) { + hashesObject[hashAlgorithm.name] = 1; + const certID = new CertID(); + certIDs.push(certID); + await certID.createForCertificate(certificate, { + hashAlgorithm: hashAlgorithm.name, + issuerCertificate + }, crypto); + } + } + for (const response of this.tbsResponseData.responses) { + for (const id of certIDs) { + if (response.certID.isEqual(id)) { + result.isForCertificate = true; + try { + switch (response.certStatus.idBlock.isConstructed) { + case true: + if (response.certStatus.idBlock.tagNumber === 1) + result.status = 1; + break; + case false: + switch (response.certStatus.idBlock.tagNumber) { + case 0: + result.status = 0; + break; + case 2: + result.status = 2; + break; + default: + } + break; + default: + } + } + catch { + } + return result; + } + } + } + return result; + } + async sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { + if (!privateKey) { + throw new Error("Need to provide a private key for signing"); + } + const signatureParams = await crypto.getSignatureParameters(privateKey, hashAlgorithm); + const algorithm = signatureParams.parameters.algorithm; + if (!("name" in algorithm)) { + throw new Error("Empty algorithm"); + } + this.signatureAlgorithm = signatureParams.signatureAlgorithm; + this.tbsResponseData.tbsView = new Uint8Array(this.tbsResponseData.toSchema(true).toBER()); + const signature = await crypto.signWithPrivateKey(this.tbsResponseData.tbsView, privateKey, { algorithm }); + this.signature = new BitString({ valueHex: signature }); + } + async verify(params = {}, crypto = getCrypto(true)) { + let signerCert = null; + let certIndex = -1; + const trustedCerts = params.trustedCerts || []; + if (!this.certs) { + throw new Error("No certificates attached to the BasicOCSPResponse"); + } + switch (true) { + case (this.tbsResponseData.responderID instanceof RelativeDistinguishedNames): + for (const [index, certificate] of this.certs.entries()) { + if (certificate.subject.isEqual(this.tbsResponseData.responderID)) { + certIndex = index; + break; + } + } + break; + case (this.tbsResponseData.responderID instanceof OctetString): + for (const [index, cert] of this.certs.entries()) { + const hash = await crypto.digest({ name: "sha-1" }, cert.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); + if (isEqualBuffer(hash, this.tbsResponseData.responderID.valueBlock.valueHex)) { + certIndex = index; + break; + } + } + break; + default: + throw new Error("Wrong value for responderID"); + } + if (certIndex === (-1)) + throw new Error("Correct certificate was not found in OCSP response"); + signerCert = this.certs[certIndex]; + const additionalCerts = [signerCert]; + for (const cert of this.certs) { + const caCert = await checkCA(cert, signerCert); + if (caCert) { + additionalCerts.push(caCert); + } + } + const certChain = new CertificateChainValidationEngine({ + certs: additionalCerts, + trustedCerts, + }); + const verificationResult = await certChain.verify({}, crypto); + if (!verificationResult.result) { + throw new Error("Validation of signer's certificate failed"); + } + return crypto.verifyWithPublicKey(this.tbsResponseData.tbsView, this.signature, this.certs[certIndex].subjectPublicKeyInfo, this.signatureAlgorithm); + } +} BasicOCSPResponse.CLASS_NAME = "BasicOCSPResponse"; -const TBS$1 = "tbs"; -const VERSION$6 = "version"; -const SUBJECT = "subject"; -const SPKI = "subjectPublicKeyInfo"; -const ATTRIBUTES$1 = "attributes"; -const SIGNATURE_ALGORITHM$2 = "signatureAlgorithm"; -const SIGNATURE_VALUE = "signatureValue"; -const CSR_INFO = "CertificationRequestInfo"; -const CSR_INFO_VERSION = `${CSR_INFO}.version`; -const CSR_INFO_SUBJECT = `${CSR_INFO}.subject`; -const CSR_INFO_SPKI = `${CSR_INFO}.subjectPublicKeyInfo`; -const CSR_INFO_ATTRS = `${CSR_INFO}.attributes`; -const CLEAR_PROPS$f = [ - CSR_INFO, - CSR_INFO_VERSION, - CSR_INFO_SUBJECT, - CSR_INFO_SPKI, - CSR_INFO_ATTRS, - SIGNATURE_ALGORITHM$2, - SIGNATURE_VALUE -]; -function CertificationRequestInfo(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.CertificationRequestInfo || CSR_INFO), - value: [ - new Integer({ name: (names.CertificationRequestInfoVersion || CSR_INFO_VERSION) }), - RelativeDistinguishedNames.schema(names.subject || { - names: { - blockName: CSR_INFO_SUBJECT - } - }), - PublicKeyInfo.schema({ - names: { - blockName: CSR_INFO_SPKI - } - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Repeated({ - optional: true, - name: (names.CertificationRequestInfoAttributes || CSR_INFO_ATTRS), - value: Attribute.schema(names.attributes || {}) - }) - ] - }) - ] - })); -} -class CertificationRequest extends PkiObject { - constructor(parameters = {}) { - super(); - this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$1, CertificationRequest.defaultValues(TBS$1))); - this.version = getParametersValue(parameters, VERSION$6, CertificationRequest.defaultValues(VERSION$6)); - this.subject = getParametersValue(parameters, SUBJECT, CertificationRequest.defaultValues(SUBJECT)); - this.subjectPublicKeyInfo = getParametersValue(parameters, SPKI, CertificationRequest.defaultValues(SPKI)); - if (ATTRIBUTES$1 in parameters) { - this.attributes = getParametersValue(parameters, ATTRIBUTES$1, CertificationRequest.defaultValues(ATTRIBUTES$1)); - } - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$2, CertificationRequest.defaultValues(SIGNATURE_ALGORITHM$2)); - this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE, CertificationRequest.defaultValues(SIGNATURE_VALUE)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - get tbs() { - return BufferSourceConverter.toArrayBuffer(this.tbsView); - } - set tbs(value) { - this.tbsView = new Uint8Array(value); - } - static defaultValues(memberName) { - switch (memberName) { - case TBS$1: - return EMPTY_BUFFER; - case VERSION$6: - return 0; - case SUBJECT: - return new RelativeDistinguishedNames(); - case SPKI: - return new PublicKeyInfo(); - case ATTRIBUTES$1: - return []; - case SIGNATURE_ALGORITHM$2: - return new AlgorithmIdentifier(); - case SIGNATURE_VALUE: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - value: [ - CertificationRequestInfo(names.certificationRequestInfo || {}), - new Sequence({ - name: (names.signatureAlgorithm || SIGNATURE_ALGORITHM$2), - value: [ - new ObjectIdentifier(), - new Any({ optional: true }) - ] - }), - new BitString({ name: (names.signatureValue || SIGNATURE_VALUE) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$f); - const asn1 = compareSchema(schema, schema, CertificationRequest.schema()); - AsnError.assertSchema(asn1, this.className); - this.tbsView = asn1.result.CertificationRequestInfo.valueBeforeDecodeView; - this.version = asn1.result[CSR_INFO_VERSION].valueBlock.valueDec; - this.subject = new RelativeDistinguishedNames({ schema: asn1.result[CSR_INFO_SUBJECT] }); - this.subjectPublicKeyInfo = new PublicKeyInfo({ schema: asn1.result[CSR_INFO_SPKI] }); - if (CSR_INFO_ATTRS in asn1.result) { - this.attributes = Array.from(asn1.result[CSR_INFO_ATTRS], element => new Attribute({ schema: element })); - } - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); - this.signatureValue = asn1.result.signatureValue; - } - encodeTBS() { - const outputArray = [ - new Integer({ value: this.version }), - this.subject.toSchema(), - this.subjectPublicKeyInfo.toSchema() - ]; - if (ATTRIBUTES$1 in this) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: Array.from(this.attributes || [], o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toSchema(encodeFlag = false) { - let tbsSchema; - if (encodeFlag === false) { - if (this.tbsView.byteLength === 0) { - return CertificationRequest.schema(); - } - const asn1 = fromBER(this.tbsView); - AsnError.assert(asn1, "PKCS#10 Certificate Request"); - tbsSchema = asn1.result; - } - else { - tbsSchema = this.encodeTBS(); - } - return (new Sequence({ - value: [ - tbsSchema, - this.signatureAlgorithm.toSchema(), - this.signatureValue - ] - })); - } - toJSON() { - const object = { - tbs: Convert.ToHex(this.tbsView), - version: this.version, - subject: this.subject.toJSON(), - subjectPublicKeyInfo: this.subjectPublicKeyInfo.toJSON(), - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signatureValue: this.signatureValue.toJSON(), - }; - if (ATTRIBUTES$1 in this) { - object.attributes = Array.from(this.attributes || [], o => o.toJSON()); - } - return object; - } - sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - if (!privateKey) { - throw new Error("Need to provide a private key for signing"); - } - const signatureParams = yield crypto.getSignatureParameters(privateKey, hashAlgorithm); - const parameters = signatureParams.parameters; - this.signatureAlgorithm = signatureParams.signatureAlgorithm; - this.tbsView = new Uint8Array(this.encodeTBS().toBER()); - const signature = yield crypto.signWithPrivateKey(this.tbsView, privateKey, parameters); - this.signatureValue = new BitString({ valueHex: signature }); - }); - } - verify(crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, this.subjectPublicKeyInfo, this.signatureAlgorithm); - }); - } - getPublicKey(parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - return crypto.getPublicKey(this.subjectPublicKeyInfo, this.signatureAlgorithm, parameters); - }); - } -} +const TBS$1 = "tbs"; +const VERSION$6 = "version"; +const SUBJECT = "subject"; +const SPKI = "subjectPublicKeyInfo"; +const ATTRIBUTES$1 = "attributes"; +const SIGNATURE_ALGORITHM$2 = "signatureAlgorithm"; +const SIGNATURE_VALUE = "signatureValue"; +const CSR_INFO = "CertificationRequestInfo"; +const CSR_INFO_VERSION = `${CSR_INFO}.version`; +const CSR_INFO_SUBJECT = `${CSR_INFO}.subject`; +const CSR_INFO_SPKI = `${CSR_INFO}.subjectPublicKeyInfo`; +const CSR_INFO_ATTRS = `${CSR_INFO}.attributes`; +const CLEAR_PROPS$f = [ + CSR_INFO, + CSR_INFO_VERSION, + CSR_INFO_SUBJECT, + CSR_INFO_SPKI, + CSR_INFO_ATTRS, + SIGNATURE_ALGORITHM$2, + SIGNATURE_VALUE +]; +function CertificationRequestInfo(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.CertificationRequestInfo || CSR_INFO), + value: [ + new Integer({ name: (names.CertificationRequestInfoVersion || CSR_INFO_VERSION) }), + RelativeDistinguishedNames.schema(names.subject || { + names: { + blockName: CSR_INFO_SUBJECT + } + }), + PublicKeyInfo.schema({ + names: { + blockName: CSR_INFO_SPKI + } + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Repeated({ + optional: true, + name: (names.CertificationRequestInfoAttributes || CSR_INFO_ATTRS), + value: Attribute.schema(names.attributes || {}) + }) + ] + }) + ] + })); +} +class CertificationRequest extends PkiObject { + get tbs() { + return BufferSourceConverter.toArrayBuffer(this.tbsView); + } + set tbs(value) { + this.tbsView = new Uint8Array(value); + } + constructor(parameters = {}) { + super(); + this.tbsView = new Uint8Array(getParametersValue(parameters, TBS$1, CertificationRequest.defaultValues(TBS$1))); + this.version = getParametersValue(parameters, VERSION$6, CertificationRequest.defaultValues(VERSION$6)); + this.subject = getParametersValue(parameters, SUBJECT, CertificationRequest.defaultValues(SUBJECT)); + this.subjectPublicKeyInfo = getParametersValue(parameters, SPKI, CertificationRequest.defaultValues(SPKI)); + if (ATTRIBUTES$1 in parameters) { + this.attributes = getParametersValue(parameters, ATTRIBUTES$1, CertificationRequest.defaultValues(ATTRIBUTES$1)); + } + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$2, CertificationRequest.defaultValues(SIGNATURE_ALGORITHM$2)); + this.signatureValue = getParametersValue(parameters, SIGNATURE_VALUE, CertificationRequest.defaultValues(SIGNATURE_VALUE)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TBS$1: + return EMPTY_BUFFER; + case VERSION$6: + return 0; + case SUBJECT: + return new RelativeDistinguishedNames(); + case SPKI: + return new PublicKeyInfo(); + case ATTRIBUTES$1: + return []; + case SIGNATURE_ALGORITHM$2: + return new AlgorithmIdentifier(); + case SIGNATURE_VALUE: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + value: [ + CertificationRequestInfo(names.certificationRequestInfo || {}), + new Sequence({ + name: (names.signatureAlgorithm || SIGNATURE_ALGORITHM$2), + value: [ + new ObjectIdentifier(), + new Any({ optional: true }) + ] + }), + new BitString({ name: (names.signatureValue || SIGNATURE_VALUE) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$f); + const asn1 = compareSchema(schema, schema, CertificationRequest.schema()); + AsnError.assertSchema(asn1, this.className); + this.tbsView = asn1.result.CertificationRequestInfo.valueBeforeDecodeView; + this.version = asn1.result[CSR_INFO_VERSION].valueBlock.valueDec; + this.subject = new RelativeDistinguishedNames({ schema: asn1.result[CSR_INFO_SUBJECT] }); + this.subjectPublicKeyInfo = new PublicKeyInfo({ schema: asn1.result[CSR_INFO_SPKI] }); + if (CSR_INFO_ATTRS in asn1.result) { + this.attributes = Array.from(asn1.result[CSR_INFO_ATTRS], element => new Attribute({ schema: element })); + } + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); + this.signatureValue = asn1.result.signatureValue; + } + encodeTBS() { + const outputArray = [ + new Integer({ value: this.version }), + this.subject.toSchema(), + this.subjectPublicKeyInfo.toSchema() + ]; + if (ATTRIBUTES$1 in this) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: Array.from(this.attributes || [], o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toSchema(encodeFlag = false) { + let tbsSchema; + if (encodeFlag === false) { + if (this.tbsView.byteLength === 0) { + return CertificationRequest.schema(); + } + const asn1 = fromBER(this.tbsView); + AsnError.assert(asn1, "PKCS#10 Certificate Request"); + tbsSchema = asn1.result; + } + else { + tbsSchema = this.encodeTBS(); + } + return (new Sequence({ + value: [ + tbsSchema, + this.signatureAlgorithm.toSchema(), + this.signatureValue + ] + })); + } + toJSON() { + const object = { + tbs: Convert.ToHex(this.tbsView), + version: this.version, + subject: this.subject.toJSON(), + subjectPublicKeyInfo: this.subjectPublicKeyInfo.toJSON(), + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signatureValue: this.signatureValue.toJSON(), + }; + if (ATTRIBUTES$1 in this) { + object.attributes = Array.from(this.attributes || [], o => o.toJSON()); + } + return object; + } + async sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { + if (!privateKey) { + throw new Error("Need to provide a private key for signing"); + } + const signatureParams = await crypto.getSignatureParameters(privateKey, hashAlgorithm); + const parameters = signatureParams.parameters; + this.signatureAlgorithm = signatureParams.signatureAlgorithm; + this.tbsView = new Uint8Array(this.encodeTBS().toBER()); + const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters); + this.signatureValue = new BitString({ valueHex: signature }); + } + async verify(crypto = getCrypto(true)) { + return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, this.subjectPublicKeyInfo, this.signatureAlgorithm); + } + async getPublicKey(parameters, crypto = getCrypto(true)) { + return crypto.getPublicKey(this.subjectPublicKeyInfo, this.signatureAlgorithm, parameters); + } +} CertificationRequest.CLASS_NAME = "CertificationRequest"; -const DIGEST_ALGORITHM$1 = "digestAlgorithm"; -const DIGEST = "digest"; -const CLEAR_PROPS$e = [ - DIGEST_ALGORITHM$1, - DIGEST -]; -class DigestInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.digestAlgorithm = getParametersValue(parameters, DIGEST_ALGORITHM$1, DigestInfo.defaultValues(DIGEST_ALGORITHM$1)); - this.digest = getParametersValue(parameters, DIGEST, DigestInfo.defaultValues(DIGEST)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case DIGEST_ALGORITHM$1: - return new AlgorithmIdentifier(); - case DIGEST: - return new OctetString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case DIGEST_ALGORITHM$1: - return ((AlgorithmIdentifier.compareWithDefault("algorithmId", memberValue.algorithmId)) && - (("algorithmParams" in memberValue) === false)); - case DIGEST: - return (memberValue.isEqual(DigestInfo.defaultValues(memberName))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.digestAlgorithm || { - names: { - blockName: DIGEST_ALGORITHM$1 - } - }), - new OctetString({ name: (names.digest || DIGEST) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$e); - const asn1 = compareSchema(schema, schema, DigestInfo.schema({ - names: { - digestAlgorithm: { - names: { - blockName: DIGEST_ALGORITHM$1 - } - }, - digest: DIGEST - } - })); - AsnError.assertSchema(asn1, this.className); - this.digestAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.digestAlgorithm }); - this.digest = asn1.result.digest; - } - toSchema() { - return (new Sequence({ - value: [ - this.digestAlgorithm.toSchema(), - this.digest - ] - })); - } - toJSON() { - return { - digestAlgorithm: this.digestAlgorithm.toJSON(), - digest: this.digest.toJSON(), - }; - } -} +const DIGEST_ALGORITHM$1 = "digestAlgorithm"; +const DIGEST = "digest"; +const CLEAR_PROPS$e = [ + DIGEST_ALGORITHM$1, + DIGEST +]; +class DigestInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.digestAlgorithm = getParametersValue(parameters, DIGEST_ALGORITHM$1, DigestInfo.defaultValues(DIGEST_ALGORITHM$1)); + this.digest = getParametersValue(parameters, DIGEST, DigestInfo.defaultValues(DIGEST)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case DIGEST_ALGORITHM$1: + return new AlgorithmIdentifier(); + case DIGEST: + return new OctetString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case DIGEST_ALGORITHM$1: + return ((AlgorithmIdentifier.compareWithDefault("algorithmId", memberValue.algorithmId)) && + (("algorithmParams" in memberValue) === false)); + case DIGEST: + return (memberValue.isEqual(DigestInfo.defaultValues(memberName))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.digestAlgorithm || { + names: { + blockName: DIGEST_ALGORITHM$1 + } + }), + new OctetString({ name: (names.digest || DIGEST) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$e); + const asn1 = compareSchema(schema, schema, DigestInfo.schema({ + names: { + digestAlgorithm: { + names: { + blockName: DIGEST_ALGORITHM$1 + } + }, + digest: DIGEST + } + })); + AsnError.assertSchema(asn1, this.className); + this.digestAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.digestAlgorithm }); + this.digest = asn1.result.digest; + } + toSchema() { + return (new Sequence({ + value: [ + this.digestAlgorithm.toSchema(), + this.digest + ] + })); + } + toJSON() { + return { + digestAlgorithm: this.digestAlgorithm.toJSON(), + digest: this.digest.toJSON(), + }; + } +} DigestInfo.CLASS_NAME = "DigestInfo"; -const E_CONTENT_TYPE = "eContentType"; -const E_CONTENT = "eContent"; -const CLEAR_PROPS$d = [ - E_CONTENT_TYPE, - E_CONTENT, -]; -class EncapsulatedContentInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.eContentType = getParametersValue(parameters, E_CONTENT_TYPE, EncapsulatedContentInfo.defaultValues(E_CONTENT_TYPE)); - if (E_CONTENT in parameters) { - this.eContent = getParametersValue(parameters, E_CONTENT, EncapsulatedContentInfo.defaultValues(E_CONTENT)); - if ((this.eContent.idBlock.tagClass === 1) && - (this.eContent.idBlock.tagNumber === 4)) { - if (this.eContent.idBlock.isConstructed === false) { - const constrString = new OctetString({ - idBlock: { isConstructed: true }, - isConstructed: true - }); - let offset = 0; - const viewHex = this.eContent.valueBlock.valueHexView.slice().buffer; - let length = viewHex.byteLength; - while (length > 0) { - const pieceView = new Uint8Array(viewHex, offset, ((offset + 65536) > viewHex.byteLength) ? (viewHex.byteLength - offset) : 65536); - const _array = new ArrayBuffer(pieceView.length); - const _view = new Uint8Array(_array); - for (let i = 0; i < _view.length; i++) { - _view[i] = pieceView[i]; - } - constrString.valueBlock.value.push(new OctetString({ valueHex: _array })); - length -= pieceView.length; - offset += pieceView.length; - } - this.eContent = constrString; - } - } - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case E_CONTENT_TYPE: - return EMPTY_STRING; - case E_CONTENT: - return new OctetString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case E_CONTENT_TYPE: - return (memberValue === EMPTY_STRING); - case E_CONTENT: - { - if ((memberValue.idBlock.tagClass === 1) && (memberValue.idBlock.tagNumber === 4)) - return (memberValue.isEqual(EncapsulatedContentInfo.defaultValues(E_CONTENT))); - return false; - } - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.eContentType || EMPTY_STRING) }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Any({ name: (names.eContent || EMPTY_STRING) }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$d); - const asn1 = compareSchema(schema, schema, EncapsulatedContentInfo.schema({ - names: { - eContentType: E_CONTENT_TYPE, - eContent: E_CONTENT - } - })); - AsnError.assertSchema(asn1, this.className); - this.eContentType = asn1.result.eContentType.valueBlock.toString(); - if (E_CONTENT in asn1.result) - this.eContent = asn1.result.eContent; - } - toSchema() { - const outputArray = []; - outputArray.push(new ObjectIdentifier({ value: this.eContentType })); - if (this.eContent) { - if (EncapsulatedContentInfo.compareWithDefault(E_CONTENT, this.eContent) === false) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.eContent] - })); - } - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - eContentType: this.eContentType - }; - if (this.eContent && EncapsulatedContentInfo.compareWithDefault(E_CONTENT, this.eContent) === false) { - res.eContent = this.eContent.toJSON(); - } - return res; - } -} +const E_CONTENT_TYPE = "eContentType"; +const E_CONTENT = "eContent"; +const CLEAR_PROPS$d = [ + E_CONTENT_TYPE, + E_CONTENT, +]; +class EncapsulatedContentInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.eContentType = getParametersValue(parameters, E_CONTENT_TYPE, EncapsulatedContentInfo.defaultValues(E_CONTENT_TYPE)); + if (E_CONTENT in parameters) { + this.eContent = getParametersValue(parameters, E_CONTENT, EncapsulatedContentInfo.defaultValues(E_CONTENT)); + if ((this.eContent.idBlock.tagClass === 1) && + (this.eContent.idBlock.tagNumber === 4)) { + if (this.eContent.idBlock.isConstructed === false) { + const constrString = new OctetString({ + idBlock: { isConstructed: true }, + isConstructed: true + }); + let offset = 0; + const viewHex = this.eContent.valueBlock.valueHexView.slice().buffer; + let length = viewHex.byteLength; + while (length > 0) { + const pieceView = new Uint8Array(viewHex, offset, ((offset + 65536) > viewHex.byteLength) ? (viewHex.byteLength - offset) : 65536); + const _array = new ArrayBuffer(pieceView.length); + const _view = new Uint8Array(_array); + for (let i = 0; i < _view.length; i++) { + _view[i] = pieceView[i]; + } + constrString.valueBlock.value.push(new OctetString({ valueHex: _array })); + length -= pieceView.length; + offset += pieceView.length; + } + this.eContent = constrString; + } + } + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case E_CONTENT_TYPE: + return EMPTY_STRING; + case E_CONTENT: + return new OctetString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case E_CONTENT_TYPE: + return (memberValue === EMPTY_STRING); + case E_CONTENT: + { + if ((memberValue.idBlock.tagClass === 1) && (memberValue.idBlock.tagNumber === 4)) + return (memberValue.isEqual(EncapsulatedContentInfo.defaultValues(E_CONTENT))); + return false; + } + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.eContentType || EMPTY_STRING) }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Any({ name: (names.eContent || EMPTY_STRING) }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$d); + const asn1 = compareSchema(schema, schema, EncapsulatedContentInfo.schema({ + names: { + eContentType: E_CONTENT_TYPE, + eContent: E_CONTENT + } + })); + AsnError.assertSchema(asn1, this.className); + this.eContentType = asn1.result.eContentType.valueBlock.toString(); + if (E_CONTENT in asn1.result) + this.eContent = asn1.result.eContent; + } + toSchema() { + const outputArray = []; + outputArray.push(new ObjectIdentifier({ value: this.eContentType })); + if (this.eContent) { + if (EncapsulatedContentInfo.compareWithDefault(E_CONTENT, this.eContent) === false) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.eContent] + })); + } + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + eContentType: this.eContentType + }; + if (this.eContent && EncapsulatedContentInfo.compareWithDefault(E_CONTENT, this.eContent) === false) { + res.eContent = this.eContent.toJSON(); + } + return res; + } +} EncapsulatedContentInfo.CLASS_NAME = "EncapsulatedContentInfo"; -class KeyBag extends PrivateKeyInfo { - constructor(parameters = {}) { - super(parameters); - } +class KeyBag extends PrivateKeyInfo { + constructor(parameters = {}) { + super(parameters); + } } -const MAC = "mac"; -const MAC_SALT = "macSalt"; -const ITERATIONS = "iterations"; -const CLEAR_PROPS$c = [ - MAC, - MAC_SALT, - ITERATIONS -]; -class MacData extends PkiObject { - constructor(parameters = {}) { - super(); - this.mac = getParametersValue(parameters, MAC, MacData.defaultValues(MAC)); - this.macSalt = getParametersValue(parameters, MAC_SALT, MacData.defaultValues(MAC_SALT)); - if (ITERATIONS in parameters) { - this.iterations = getParametersValue(parameters, ITERATIONS, MacData.defaultValues(ITERATIONS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case MAC: - return new DigestInfo(); - case MAC_SALT: - return new OctetString(); - case ITERATIONS: - return 1; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case MAC: - return ((DigestInfo.compareWithDefault("digestAlgorithm", memberValue.digestAlgorithm)) && - (DigestInfo.compareWithDefault("digest", memberValue.digest))); - case MAC_SALT: - return (memberValue.isEqual(MacData.defaultValues(memberName))); - case ITERATIONS: - return (memberValue === MacData.defaultValues(memberName)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - optional: (names.optional || true), - value: [ - DigestInfo.schema(names.mac || { - names: { - blockName: MAC - } - }), - new OctetString({ name: (names.macSalt || MAC_SALT) }), - new Integer({ - optional: true, - name: (names.iterations || ITERATIONS) - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$c); - const asn1 = compareSchema(schema, schema, MacData.schema({ - names: { - mac: { - names: { - blockName: MAC - } - }, - macSalt: MAC_SALT, - iterations: ITERATIONS - } - })); - AsnError.assertSchema(asn1, this.className); - this.mac = new DigestInfo({ schema: asn1.result.mac }); - this.macSalt = asn1.result.macSalt; - if (ITERATIONS in asn1.result) - this.iterations = asn1.result.iterations.valueBlock.valueDec; - } - toSchema() { - const outputArray = [ - this.mac.toSchema(), - this.macSalt - ]; - if (this.iterations !== undefined) { - outputArray.push(new Integer({ value: this.iterations })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - mac: this.mac.toJSON(), - macSalt: this.macSalt.toJSON(), - }; - if (this.iterations !== undefined) { - res.iterations = this.iterations; - } - return res; - } -} +const MAC = "mac"; +const MAC_SALT = "macSalt"; +const ITERATIONS = "iterations"; +const CLEAR_PROPS$c = [ + MAC, + MAC_SALT, + ITERATIONS +]; +class MacData extends PkiObject { + constructor(parameters = {}) { + super(); + this.mac = getParametersValue(parameters, MAC, MacData.defaultValues(MAC)); + this.macSalt = getParametersValue(parameters, MAC_SALT, MacData.defaultValues(MAC_SALT)); + if (ITERATIONS in parameters) { + this.iterations = getParametersValue(parameters, ITERATIONS, MacData.defaultValues(ITERATIONS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case MAC: + return new DigestInfo(); + case MAC_SALT: + return new OctetString(); + case ITERATIONS: + return 1; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case MAC: + return ((DigestInfo.compareWithDefault("digestAlgorithm", memberValue.digestAlgorithm)) && + (DigestInfo.compareWithDefault("digest", memberValue.digest))); + case MAC_SALT: + return (memberValue.isEqual(MacData.defaultValues(memberName))); + case ITERATIONS: + return (memberValue === MacData.defaultValues(memberName)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + optional: (names.optional || true), + value: [ + DigestInfo.schema(names.mac || { + names: { + blockName: MAC + } + }), + new OctetString({ name: (names.macSalt || MAC_SALT) }), + new Integer({ + optional: true, + name: (names.iterations || ITERATIONS) + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$c); + const asn1 = compareSchema(schema, schema, MacData.schema({ + names: { + mac: { + names: { + blockName: MAC + } + }, + macSalt: MAC_SALT, + iterations: ITERATIONS + } + })); + AsnError.assertSchema(asn1, this.className); + this.mac = new DigestInfo({ schema: asn1.result.mac }); + this.macSalt = asn1.result.macSalt; + if (ITERATIONS in asn1.result) + this.iterations = asn1.result.iterations.valueBlock.valueDec; + } + toSchema() { + const outputArray = [ + this.mac.toSchema(), + this.macSalt + ]; + if (this.iterations !== undefined) { + outputArray.push(new Integer({ value: this.iterations })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + mac: this.mac.toJSON(), + macSalt: this.macSalt.toJSON(), + }; + if (this.iterations !== undefined) { + res.iterations = this.iterations; + } + return res; + } +} MacData.CLASS_NAME = "MacData"; -const HASH_ALGORITHM = "hashAlgorithm"; -const HASHED_MESSAGE = "hashedMessage"; -const CLEAR_PROPS$b = [ - HASH_ALGORITHM, - HASHED_MESSAGE, -]; -class MessageImprint extends PkiObject { - constructor(parameters = {}) { - super(); - this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM, MessageImprint.defaultValues(HASH_ALGORITHM)); - this.hashedMessage = getParametersValue(parameters, HASHED_MESSAGE, MessageImprint.defaultValues(HASHED_MESSAGE)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static create(hashAlgorithm, message, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const hashAlgorithmOID = crypto.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); - const hashedMessage = yield crypto.digest(hashAlgorithm, message); - const res = new MessageImprint({ - hashAlgorithm: new AlgorithmIdentifier({ - algorithmId: hashAlgorithmOID, - algorithmParams: new Null(), - }), - hashedMessage: new OctetString({ valueHex: hashedMessage }) - }); - return res; - }); - } - static defaultValues(memberName) { - switch (memberName) { - case HASH_ALGORITHM: - return new AlgorithmIdentifier(); - case HASHED_MESSAGE: - return new OctetString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case HASH_ALGORITHM: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case HASHED_MESSAGE: - return (memberValue.isEqual(MessageImprint.defaultValues(memberName)) === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.hashAlgorithm || {}), - new OctetString({ name: (names.hashedMessage || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$b); - const asn1 = compareSchema(schema, schema, MessageImprint.schema({ - names: { - hashAlgorithm: { - names: { - blockName: HASH_ALGORITHM - } - }, - hashedMessage: HASHED_MESSAGE - } - })); - AsnError.assertSchema(asn1, this.className); - this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); - this.hashedMessage = asn1.result.hashedMessage; - } - toSchema() { - return (new Sequence({ - value: [ - this.hashAlgorithm.toSchema(), - this.hashedMessage - ] - })); - } - toJSON() { - return { - hashAlgorithm: this.hashAlgorithm.toJSON(), - hashedMessage: this.hashedMessage.toJSON(), - }; - } -} +const HASH_ALGORITHM = "hashAlgorithm"; +const HASHED_MESSAGE = "hashedMessage"; +const CLEAR_PROPS$b = [ + HASH_ALGORITHM, + HASHED_MESSAGE, +]; +class MessageImprint extends PkiObject { + static async create(hashAlgorithm, message, crypto = getCrypto(true)) { + const hashAlgorithmOID = crypto.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); + const hashedMessage = await crypto.digest(hashAlgorithm, message); + const res = new MessageImprint({ + hashAlgorithm: new AlgorithmIdentifier({ + algorithmId: hashAlgorithmOID, + algorithmParams: new Null(), + }), + hashedMessage: new OctetString({ valueHex: hashedMessage }) + }); + return res; + } + constructor(parameters = {}) { + super(); + this.hashAlgorithm = getParametersValue(parameters, HASH_ALGORITHM, MessageImprint.defaultValues(HASH_ALGORITHM)); + this.hashedMessage = getParametersValue(parameters, HASHED_MESSAGE, MessageImprint.defaultValues(HASHED_MESSAGE)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case HASH_ALGORITHM: + return new AlgorithmIdentifier(); + case HASHED_MESSAGE: + return new OctetString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case HASH_ALGORITHM: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case HASHED_MESSAGE: + return (memberValue.isEqual(MessageImprint.defaultValues(memberName)) === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.hashAlgorithm || {}), + new OctetString({ name: (names.hashedMessage || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$b); + const asn1 = compareSchema(schema, schema, MessageImprint.schema({ + names: { + hashAlgorithm: { + names: { + blockName: HASH_ALGORITHM + } + }, + hashedMessage: HASHED_MESSAGE + } + })); + AsnError.assertSchema(asn1, this.className); + this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm }); + this.hashedMessage = asn1.result.hashedMessage; + } + toSchema() { + return (new Sequence({ + value: [ + this.hashAlgorithm.toSchema(), + this.hashedMessage + ] + })); + } + toJSON() { + return { + hashAlgorithm: this.hashAlgorithm.toJSON(), + hashedMessage: this.hashedMessage.toJSON(), + }; + } +} MessageImprint.CLASS_NAME = "MessageImprint"; -const REQ_CERT = "reqCert"; -const SINGLE_REQUEST_EXTENSIONS = "singleRequestExtensions"; -const CLEAR_PROPS$a = [ - REQ_CERT, - SINGLE_REQUEST_EXTENSIONS, -]; -class Request extends PkiObject { - constructor(parameters = {}) { - super(); - this.reqCert = getParametersValue(parameters, REQ_CERT, Request.defaultValues(REQ_CERT)); - if (SINGLE_REQUEST_EXTENSIONS in parameters) { - this.singleRequestExtensions = getParametersValue(parameters, SINGLE_REQUEST_EXTENSIONS, Request.defaultValues(SINGLE_REQUEST_EXTENSIONS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case REQ_CERT: - return new CertID(); - case SINGLE_REQUEST_EXTENSIONS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case REQ_CERT: - return (memberValue.isEqual(Request.defaultValues(memberName))); - case SINGLE_REQUEST_EXTENSIONS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - CertID.schema(names.reqCert || {}), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [Extension.schema(names.extensions || { - names: { - blockName: (names.singleRequestExtensions || EMPTY_STRING) - } - })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$a); - const asn1 = compareSchema(schema, schema, Request.schema({ - names: { - reqCert: { - names: { - blockName: REQ_CERT - } - }, - extensions: { - names: { - blockName: SINGLE_REQUEST_EXTENSIONS - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.reqCert = new CertID({ schema: asn1.result.reqCert }); - if (SINGLE_REQUEST_EXTENSIONS in asn1.result) { - this.singleRequestExtensions = Array.from(asn1.result.singleRequestExtensions.valueBlock.value, element => new Extension({ schema: element })); - } - } - toSchema() { - const outputArray = []; - outputArray.push(this.reqCert.toSchema()); - if (this.singleRequestExtensions) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Sequence({ - value: Array.from(this.singleRequestExtensions, o => o.toSchema()) - }) - ] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - reqCert: this.reqCert.toJSON() - }; - if (this.singleRequestExtensions) { - res.singleRequestExtensions = Array.from(this.singleRequestExtensions, o => o.toJSON()); - } - return res; - } -} +const REQ_CERT = "reqCert"; +const SINGLE_REQUEST_EXTENSIONS = "singleRequestExtensions"; +const CLEAR_PROPS$a = [ + REQ_CERT, + SINGLE_REQUEST_EXTENSIONS, +]; +class Request extends PkiObject { + constructor(parameters = {}) { + super(); + this.reqCert = getParametersValue(parameters, REQ_CERT, Request.defaultValues(REQ_CERT)); + if (SINGLE_REQUEST_EXTENSIONS in parameters) { + this.singleRequestExtensions = getParametersValue(parameters, SINGLE_REQUEST_EXTENSIONS, Request.defaultValues(SINGLE_REQUEST_EXTENSIONS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case REQ_CERT: + return new CertID(); + case SINGLE_REQUEST_EXTENSIONS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case REQ_CERT: + return (memberValue.isEqual(Request.defaultValues(memberName))); + case SINGLE_REQUEST_EXTENSIONS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + CertID.schema(names.reqCert || {}), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [Extensions.schema(names.extensions || { + names: { + blockName: (names.singleRequestExtensions || EMPTY_STRING) + } + })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$a); + const asn1 = compareSchema(schema, schema, Request.schema({ + names: { + reqCert: { + names: { + blockName: REQ_CERT + } + }, + extensions: { + names: { + blockName: SINGLE_REQUEST_EXTENSIONS + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.reqCert = new CertID({ schema: asn1.result.reqCert }); + if (SINGLE_REQUEST_EXTENSIONS in asn1.result) { + this.singleRequestExtensions = Array.from(asn1.result.singleRequestExtensions.valueBlock.value, element => new Extension({ schema: element })); + } + } + toSchema() { + const outputArray = []; + outputArray.push(this.reqCert.toSchema()); + if (this.singleRequestExtensions) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Sequence({ + value: Array.from(this.singleRequestExtensions, o => o.toSchema()) + }) + ] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + reqCert: this.reqCert.toJSON() + }; + if (this.singleRequestExtensions) { + res.singleRequestExtensions = Array.from(this.singleRequestExtensions, o => o.toJSON()); + } + return res; + } +} Request.CLASS_NAME = "Request"; -const TBS = "tbs"; -const VERSION$5 = "version"; -const REQUESTOR_NAME = "requestorName"; -const REQUEST_LIST = "requestList"; -const REQUEST_EXTENSIONS = "requestExtensions"; -const TBS_REQUEST$1 = "TBSRequest"; -const TBS_REQUEST_VERSION = `${TBS_REQUEST$1}.${VERSION$5}`; -const TBS_REQUEST_REQUESTOR_NAME = `${TBS_REQUEST$1}.${REQUESTOR_NAME}`; -const TBS_REQUEST_REQUESTS = `${TBS_REQUEST$1}.requests`; -const TBS_REQUEST_REQUEST_EXTENSIONS = `${TBS_REQUEST$1}.${REQUEST_EXTENSIONS}`; -const CLEAR_PROPS$9 = [ - TBS_REQUEST$1, - TBS_REQUEST_VERSION, - TBS_REQUEST_REQUESTOR_NAME, - TBS_REQUEST_REQUESTS, - TBS_REQUEST_REQUEST_EXTENSIONS -]; -class TBSRequest extends PkiObject { - constructor(parameters = {}) { - super(); - this.tbsView = new Uint8Array(getParametersValue(parameters, TBS, TBSRequest.defaultValues(TBS))); - if (VERSION$5 in parameters) { - this.version = getParametersValue(parameters, VERSION$5, TBSRequest.defaultValues(VERSION$5)); - } - if (REQUESTOR_NAME in parameters) { - this.requestorName = getParametersValue(parameters, REQUESTOR_NAME, TBSRequest.defaultValues(REQUESTOR_NAME)); - } - this.requestList = getParametersValue(parameters, REQUEST_LIST, TBSRequest.defaultValues(REQUEST_LIST)); - if (REQUEST_EXTENSIONS in parameters) { - this.requestExtensions = getParametersValue(parameters, REQUEST_EXTENSIONS, TBSRequest.defaultValues(REQUEST_EXTENSIONS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - get tbs() { - return BufferSourceConverter.toArrayBuffer(this.tbsView); - } - set tbs(value) { - this.tbsView = new Uint8Array(value); - } - static defaultValues(memberName) { - switch (memberName) { - case TBS: - return EMPTY_BUFFER; - case VERSION$5: - return 0; - case REQUESTOR_NAME: - return new GeneralName(); - case REQUEST_LIST: - case REQUEST_EXTENSIONS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TBS: - return (memberValue.byteLength === 0); - case VERSION$5: - return (memberValue === TBSRequest.defaultValues(memberName)); - case REQUESTOR_NAME: - return ((memberValue.type === GeneralName.defaultValues("type")) && (Object.keys(memberValue.value).length === 0)); - case REQUEST_LIST: - case REQUEST_EXTENSIONS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || TBS_REQUEST$1), - value: [ - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Integer({ name: (names.TBSRequestVersion || TBS_REQUEST_VERSION) })] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [GeneralName.schema(names.requestorName || { - names: { - blockName: TBS_REQUEST_REQUESTOR_NAME - } - })] - }), - new Sequence({ - name: (names.requestList || "TBSRequest.requestList"), - value: [ - new Repeated({ - name: (names.requests || TBS_REQUEST_REQUESTS), - value: Request.schema(names.requestNames || {}) - }) - ] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [Extensions.schema(names.extensions || { - names: { - blockName: (names.requestExtensions || TBS_REQUEST_REQUEST_EXTENSIONS) - } - })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$9); - const asn1 = compareSchema(schema, schema, TBSRequest.schema()); - AsnError.assertSchema(asn1, this.className); - this.tbsView = asn1.result.TBSRequest.valueBeforeDecodeView; - if (TBS_REQUEST_VERSION in asn1.result) - this.version = asn1.result[TBS_REQUEST_VERSION].valueBlock.valueDec; - if (TBS_REQUEST_REQUESTOR_NAME in asn1.result) - this.requestorName = new GeneralName({ schema: asn1.result[TBS_REQUEST_REQUESTOR_NAME] }); - this.requestList = Array.from(asn1.result[TBS_REQUEST_REQUESTS], element => new Request({ schema: element })); - if (TBS_REQUEST_REQUEST_EXTENSIONS in asn1.result) - this.requestExtensions = Array.from(asn1.result[TBS_REQUEST_REQUEST_EXTENSIONS].valueBlock.value, element => new Extension({ schema: element })); - } - toSchema(encodeFlag = false) { - let tbsSchema; - if (encodeFlag === false) { - if (this.tbsView.byteLength === 0) - return TBSRequest.schema(); - const asn1 = fromBER(this.tbsView); - AsnError.assert(asn1, "TBS Request"); - if (!(asn1.result instanceof Sequence)) { - throw new Error("ASN.1 result should be SEQUENCE"); - } - tbsSchema = asn1.result; - } - else { - const outputArray = []; - if (this.version !== undefined) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Integer({ value: this.version })] - })); - } - if (this.requestorName) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [this.requestorName.toSchema()] - })); - } - outputArray.push(new Sequence({ - value: Array.from(this.requestList, o => o.toSchema()) - })); - if (this.requestExtensions) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 2 - }, - value: [ - new Sequence({ - value: Array.from(this.requestExtensions, o => o.toSchema()) - }) - ] - })); - } - tbsSchema = new Sequence({ - value: outputArray - }); - } - return tbsSchema; - } - toJSON() { - const res = {}; - if (this.version != undefined) - res.version = this.version; - if (this.requestorName) { - res.requestorName = this.requestorName.toJSON(); - } - res.requestList = Array.from(this.requestList, o => o.toJSON()); - if (this.requestExtensions) { - res.requestExtensions = Array.from(this.requestExtensions, o => o.toJSON()); - } - return res; - } -} +const TBS = "tbs"; +const VERSION$5 = "version"; +const REQUESTOR_NAME = "requestorName"; +const REQUEST_LIST = "requestList"; +const REQUEST_EXTENSIONS = "requestExtensions"; +const TBS_REQUEST$1 = "TBSRequest"; +const TBS_REQUEST_VERSION = `${TBS_REQUEST$1}.${VERSION$5}`; +const TBS_REQUEST_REQUESTOR_NAME = `${TBS_REQUEST$1}.${REQUESTOR_NAME}`; +const TBS_REQUEST_REQUESTS = `${TBS_REQUEST$1}.requests`; +const TBS_REQUEST_REQUEST_EXTENSIONS = `${TBS_REQUEST$1}.${REQUEST_EXTENSIONS}`; +const CLEAR_PROPS$9 = [ + TBS_REQUEST$1, + TBS_REQUEST_VERSION, + TBS_REQUEST_REQUESTOR_NAME, + TBS_REQUEST_REQUESTS, + TBS_REQUEST_REQUEST_EXTENSIONS +]; +class TBSRequest extends PkiObject { + get tbs() { + return BufferSourceConverter.toArrayBuffer(this.tbsView); + } + set tbs(value) { + this.tbsView = new Uint8Array(value); + } + constructor(parameters = {}) { + super(); + this.tbsView = new Uint8Array(getParametersValue(parameters, TBS, TBSRequest.defaultValues(TBS))); + if (VERSION$5 in parameters) { + this.version = getParametersValue(parameters, VERSION$5, TBSRequest.defaultValues(VERSION$5)); + } + if (REQUESTOR_NAME in parameters) { + this.requestorName = getParametersValue(parameters, REQUESTOR_NAME, TBSRequest.defaultValues(REQUESTOR_NAME)); + } + this.requestList = getParametersValue(parameters, REQUEST_LIST, TBSRequest.defaultValues(REQUEST_LIST)); + if (REQUEST_EXTENSIONS in parameters) { + this.requestExtensions = getParametersValue(parameters, REQUEST_EXTENSIONS, TBSRequest.defaultValues(REQUEST_EXTENSIONS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TBS: + return EMPTY_BUFFER; + case VERSION$5: + return 0; + case REQUESTOR_NAME: + return new GeneralName(); + case REQUEST_LIST: + case REQUEST_EXTENSIONS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TBS: + return (memberValue.byteLength === 0); + case VERSION$5: + return (memberValue === TBSRequest.defaultValues(memberName)); + case REQUESTOR_NAME: + return ((memberValue.type === GeneralName.defaultValues("type")) && (Object.keys(memberValue.value).length === 0)); + case REQUEST_LIST: + case REQUEST_EXTENSIONS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || TBS_REQUEST$1), + value: [ + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Integer({ name: (names.TBSRequestVersion || TBS_REQUEST_VERSION) })] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [GeneralName.schema(names.requestorName || { + names: { + blockName: TBS_REQUEST_REQUESTOR_NAME + } + })] + }), + new Sequence({ + name: (names.requestList || "TBSRequest.requestList"), + value: [ + new Repeated({ + name: (names.requests || TBS_REQUEST_REQUESTS), + value: Request.schema(names.requestNames || {}) + }) + ] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [Extensions.schema(names.extensions || { + names: { + blockName: (names.requestExtensions || TBS_REQUEST_REQUEST_EXTENSIONS) + } + })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$9); + const asn1 = compareSchema(schema, schema, TBSRequest.schema()); + AsnError.assertSchema(asn1, this.className); + this.tbsView = asn1.result.TBSRequest.valueBeforeDecodeView; + if (TBS_REQUEST_VERSION in asn1.result) + this.version = asn1.result[TBS_REQUEST_VERSION].valueBlock.valueDec; + if (TBS_REQUEST_REQUESTOR_NAME in asn1.result) + this.requestorName = new GeneralName({ schema: asn1.result[TBS_REQUEST_REQUESTOR_NAME] }); + this.requestList = Array.from(asn1.result[TBS_REQUEST_REQUESTS], element => new Request({ schema: element })); + if (TBS_REQUEST_REQUEST_EXTENSIONS in asn1.result) + this.requestExtensions = Array.from(asn1.result[TBS_REQUEST_REQUEST_EXTENSIONS].valueBlock.value, element => new Extension({ schema: element })); + } + toSchema(encodeFlag = false) { + let tbsSchema; + if (encodeFlag === false) { + if (this.tbsView.byteLength === 0) + return TBSRequest.schema(); + const asn1 = fromBER(this.tbsView); + AsnError.assert(asn1, "TBS Request"); + if (!(asn1.result instanceof Sequence)) { + throw new Error("ASN.1 result should be SEQUENCE"); + } + tbsSchema = asn1.result; + } + else { + const outputArray = []; + if (this.version !== undefined) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Integer({ value: this.version })] + })); + } + if (this.requestorName) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [this.requestorName.toSchema()] + })); + } + outputArray.push(new Sequence({ + value: Array.from(this.requestList, o => o.toSchema()) + })); + if (this.requestExtensions) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 2 + }, + value: [ + new Sequence({ + value: Array.from(this.requestExtensions, o => o.toSchema()) + }) + ] + })); + } + tbsSchema = new Sequence({ + value: outputArray + }); + } + return tbsSchema; + } + toJSON() { + const res = {}; + if (this.version != undefined) + res.version = this.version; + if (this.requestorName) { + res.requestorName = this.requestorName.toJSON(); + } + res.requestList = Array.from(this.requestList, o => o.toJSON()); + if (this.requestExtensions) { + res.requestExtensions = Array.from(this.requestExtensions, o => o.toJSON()); + } + return res; + } +} TBSRequest.CLASS_NAME = "TBSRequest"; -const SIGNATURE_ALGORITHM$1 = "signatureAlgorithm"; -const SIGNATURE$1 = "signature"; -const CERTS = "certs"; -class Signature extends PkiObject { - constructor(parameters = {}) { - super(); - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$1, Signature.defaultValues(SIGNATURE_ALGORITHM$1)); - this.signature = getParametersValue(parameters, SIGNATURE$1, Signature.defaultValues(SIGNATURE$1)); - if (CERTS in parameters) { - this.certs = getParametersValue(parameters, CERTS, Signature.defaultValues(CERTS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case SIGNATURE_ALGORITHM$1: - return new AlgorithmIdentifier(); - case SIGNATURE$1: - return new BitString(); - case CERTS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case SIGNATURE_ALGORITHM$1: - return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); - case SIGNATURE$1: - return (memberValue.isEqual(Signature.defaultValues(memberName))); - case CERTS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - AlgorithmIdentifier.schema(names.signatureAlgorithm || {}), - new BitString({ name: (names.signature || EMPTY_STRING) }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Sequence({ - value: [new Repeated({ - name: (names.certs || EMPTY_STRING), - value: Certificate.schema({}) - })] - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - SIGNATURE_ALGORITHM$1, - SIGNATURE$1, - CERTS - ]); - const asn1 = compareSchema(schema, schema, Signature.schema({ - names: { - signatureAlgorithm: { - names: { - blockName: SIGNATURE_ALGORITHM$1 - } - }, - signature: SIGNATURE$1, - certs: CERTS - } - })); - AsnError.assertSchema(asn1, this.className); - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); - this.signature = asn1.result.signature; - if (CERTS in asn1.result) - this.certs = Array.from(asn1.result.certs, element => new Certificate({ schema: element })); - } - toSchema() { - const outputArray = []; - outputArray.push(this.signatureAlgorithm.toSchema()); - outputArray.push(this.signature); - if (this.certs) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - new Sequence({ - value: Array.from(this.certs, o => o.toSchema()) - }) - ] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signature: this.signature.toJSON(), - }; - if (this.certs) { - res.certs = Array.from(this.certs, o => o.toJSON()); - } - return res; - } -} +const SIGNATURE_ALGORITHM$1 = "signatureAlgorithm"; +const SIGNATURE$1 = "signature"; +const CERTS = "certs"; +class Signature extends PkiObject { + constructor(parameters = {}) { + super(); + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM$1, Signature.defaultValues(SIGNATURE_ALGORITHM$1)); + this.signature = getParametersValue(parameters, SIGNATURE$1, Signature.defaultValues(SIGNATURE$1)); + if (CERTS in parameters) { + this.certs = getParametersValue(parameters, CERTS, Signature.defaultValues(CERTS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case SIGNATURE_ALGORITHM$1: + return new AlgorithmIdentifier(); + case SIGNATURE$1: + return new BitString(); + case CERTS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case SIGNATURE_ALGORITHM$1: + return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false)); + case SIGNATURE$1: + return (memberValue.isEqual(Signature.defaultValues(memberName))); + case CERTS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + AlgorithmIdentifier.schema(names.signatureAlgorithm || {}), + new BitString({ name: (names.signature || EMPTY_STRING) }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Sequence({ + value: [new Repeated({ + name: (names.certs || EMPTY_STRING), + value: Certificate.schema({}) + })] + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + SIGNATURE_ALGORITHM$1, + SIGNATURE$1, + CERTS + ]); + const asn1 = compareSchema(schema, schema, Signature.schema({ + names: { + signatureAlgorithm: { + names: { + blockName: SIGNATURE_ALGORITHM$1 + } + }, + signature: SIGNATURE$1, + certs: CERTS + } + })); + AsnError.assertSchema(asn1, this.className); + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm }); + this.signature = asn1.result.signature; + if (CERTS in asn1.result) + this.certs = Array.from(asn1.result.certs, element => new Certificate({ schema: element })); + } + toSchema() { + const outputArray = []; + outputArray.push(this.signatureAlgorithm.toSchema()); + outputArray.push(this.signature); + if (this.certs) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + new Sequence({ + value: Array.from(this.certs, o => o.toSchema()) + }) + ] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signature: this.signature.toJSON(), + }; + if (this.certs) { + res.certs = Array.from(this.certs, o => o.toJSON()); + } + return res; + } +} Signature.CLASS_NAME = "Signature"; -const TBS_REQUEST = "tbsRequest"; -const OPTIONAL_SIGNATURE = "optionalSignature"; -const CLEAR_PROPS$8 = [ - TBS_REQUEST, - OPTIONAL_SIGNATURE -]; -class OCSPRequest extends PkiObject { - constructor(parameters = {}) { - super(); - this.tbsRequest = getParametersValue(parameters, TBS_REQUEST, OCSPRequest.defaultValues(TBS_REQUEST)); - if (OPTIONAL_SIGNATURE in parameters) { - this.optionalSignature = getParametersValue(parameters, OPTIONAL_SIGNATURE, OCSPRequest.defaultValues(OPTIONAL_SIGNATURE)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TBS_REQUEST: - return new TBSRequest(); - case OPTIONAL_SIGNATURE: - return new Signature(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TBS_REQUEST: - return ((TBSRequest.compareWithDefault("tbs", memberValue.tbs)) && - (TBSRequest.compareWithDefault("version", memberValue.version)) && - (TBSRequest.compareWithDefault("requestorName", memberValue.requestorName)) && - (TBSRequest.compareWithDefault("requestList", memberValue.requestList)) && - (TBSRequest.compareWithDefault("requestExtensions", memberValue.requestExtensions))); - case OPTIONAL_SIGNATURE: - return ((Signature.compareWithDefault("signatureAlgorithm", memberValue.signatureAlgorithm)) && - (Signature.compareWithDefault("signature", memberValue.signature)) && - (Signature.compareWithDefault("certs", memberValue.certs))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: names.blockName || "OCSPRequest", - value: [ - TBSRequest.schema(names.tbsRequest || { - names: { - blockName: TBS_REQUEST - } - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - Signature.schema(names.optionalSignature || { - names: { - blockName: OPTIONAL_SIGNATURE - } - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$8); - const asn1 = compareSchema(schema, schema, OCSPRequest.schema()); - AsnError.assertSchema(asn1, this.className); - this.tbsRequest = new TBSRequest({ schema: asn1.result.tbsRequest }); - if (OPTIONAL_SIGNATURE in asn1.result) - this.optionalSignature = new Signature({ schema: asn1.result.optionalSignature }); - } - toSchema(encodeFlag = false) { - const outputArray = []; - outputArray.push(this.tbsRequest.toSchema(encodeFlag)); - if (this.optionalSignature) - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - this.optionalSignature.toSchema() - ] - })); - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - tbsRequest: this.tbsRequest.toJSON() - }; - if (this.optionalSignature) { - res.optionalSignature = this.optionalSignature.toJSON(); - } - return res; - } - createForCertificate(certificate, parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - const certID = new CertID(); - yield certID.createForCertificate(certificate, parameters, crypto); - this.tbsRequest.requestList.push(new Request({ - reqCert: certID, - })); - }); - } - sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - ParameterError.assertEmpty(privateKey, "privateKey", "OCSPRequest.sign method"); - if (!this.optionalSignature) { - throw new Error("Need to create \"optionalSignature\" field before signing"); - } - const signatureParams = yield crypto.getSignatureParameters(privateKey, hashAlgorithm); - const parameters = signatureParams.parameters; - this.optionalSignature.signatureAlgorithm = signatureParams.signatureAlgorithm; - const tbs = this.tbsRequest.toSchema(true).toBER(false); - const signature = yield crypto.signWithPrivateKey(tbs, privateKey, parameters); - this.optionalSignature.signature = new BitString({ valueHex: signature }); - }); - } - verify() { - } -} +const TBS_REQUEST = "tbsRequest"; +const OPTIONAL_SIGNATURE = "optionalSignature"; +const CLEAR_PROPS$8 = [ + TBS_REQUEST, + OPTIONAL_SIGNATURE +]; +class OCSPRequest extends PkiObject { + constructor(parameters = {}) { + super(); + this.tbsRequest = getParametersValue(parameters, TBS_REQUEST, OCSPRequest.defaultValues(TBS_REQUEST)); + if (OPTIONAL_SIGNATURE in parameters) { + this.optionalSignature = getParametersValue(parameters, OPTIONAL_SIGNATURE, OCSPRequest.defaultValues(OPTIONAL_SIGNATURE)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TBS_REQUEST: + return new TBSRequest(); + case OPTIONAL_SIGNATURE: + return new Signature(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TBS_REQUEST: + return ((TBSRequest.compareWithDefault("tbs", memberValue.tbs)) && + (TBSRequest.compareWithDefault("version", memberValue.version)) && + (TBSRequest.compareWithDefault("requestorName", memberValue.requestorName)) && + (TBSRequest.compareWithDefault("requestList", memberValue.requestList)) && + (TBSRequest.compareWithDefault("requestExtensions", memberValue.requestExtensions))); + case OPTIONAL_SIGNATURE: + return ((Signature.compareWithDefault("signatureAlgorithm", memberValue.signatureAlgorithm)) && + (Signature.compareWithDefault("signature", memberValue.signature)) && + (Signature.compareWithDefault("certs", memberValue.certs))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: names.blockName || "OCSPRequest", + value: [ + TBSRequest.schema(names.tbsRequest || { + names: { + blockName: TBS_REQUEST + } + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + Signature.schema(names.optionalSignature || { + names: { + blockName: OPTIONAL_SIGNATURE + } + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$8); + const asn1 = compareSchema(schema, schema, OCSPRequest.schema()); + AsnError.assertSchema(asn1, this.className); + this.tbsRequest = new TBSRequest({ schema: asn1.result.tbsRequest }); + if (OPTIONAL_SIGNATURE in asn1.result) + this.optionalSignature = new Signature({ schema: asn1.result.optionalSignature }); + } + toSchema(encodeFlag = false) { + const outputArray = []; + outputArray.push(this.tbsRequest.toSchema(encodeFlag)); + if (this.optionalSignature) + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + this.optionalSignature.toSchema() + ] + })); + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + tbsRequest: this.tbsRequest.toJSON() + }; + if (this.optionalSignature) { + res.optionalSignature = this.optionalSignature.toJSON(); + } + return res; + } + async createForCertificate(certificate, parameters, crypto = getCrypto(true)) { + const certID = new CertID(); + await certID.createForCertificate(certificate, parameters, crypto); + this.tbsRequest.requestList.push(new Request({ + reqCert: certID, + })); + } + async sign(privateKey, hashAlgorithm = "SHA-1", crypto = getCrypto(true)) { + ParameterError.assertEmpty(privateKey, "privateKey", "OCSPRequest.sign method"); + if (!this.optionalSignature) { + throw new Error("Need to create \"optionalSignature\" field before signing"); + } + const signatureParams = await crypto.getSignatureParameters(privateKey, hashAlgorithm); + const parameters = signatureParams.parameters; + this.optionalSignature.signatureAlgorithm = signatureParams.signatureAlgorithm; + const tbs = this.tbsRequest.toSchema(true).toBER(false); + const signature = await crypto.signWithPrivateKey(tbs, privateKey, parameters); + this.optionalSignature.signature = new BitString({ valueHex: signature }); + } + verify() { + } +} OCSPRequest.CLASS_NAME = "OCSPRequest"; -const RESPONSE_TYPE = "responseType"; -const RESPONSE = "response"; -const CLEAR_PROPS$7 = [ - RESPONSE_TYPE, - RESPONSE -]; -class ResponseBytes extends PkiObject { - constructor(parameters = {}) { - super(); - this.responseType = getParametersValue(parameters, RESPONSE_TYPE, ResponseBytes.defaultValues(RESPONSE_TYPE)); - this.response = getParametersValue(parameters, RESPONSE, ResponseBytes.defaultValues(RESPONSE)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case RESPONSE_TYPE: - return EMPTY_STRING; - case RESPONSE: - return new OctetString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case RESPONSE_TYPE: - return (memberValue === EMPTY_STRING); - case RESPONSE: - return (memberValue.isEqual(ResponseBytes.defaultValues(memberName))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new ObjectIdentifier({ name: (names.responseType || EMPTY_STRING) }), - new OctetString({ name: (names.response || EMPTY_STRING) }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$7); - const asn1 = compareSchema(schema, schema, ResponseBytes.schema({ - names: { - responseType: RESPONSE_TYPE, - response: RESPONSE - } - })); - AsnError.assertSchema(asn1, this.className); - this.responseType = asn1.result.responseType.valueBlock.toString(); - this.response = asn1.result.response; - } - toSchema() { - return (new Sequence({ - value: [ - new ObjectIdentifier({ value: this.responseType }), - this.response - ] - })); - } - toJSON() { - return { - responseType: this.responseType, - response: this.response.toJSON(), - }; - } -} +const RESPONSE_TYPE = "responseType"; +const RESPONSE = "response"; +const CLEAR_PROPS$7 = [ + RESPONSE_TYPE, + RESPONSE +]; +class ResponseBytes extends PkiObject { + constructor(parameters = {}) { + super(); + this.responseType = getParametersValue(parameters, RESPONSE_TYPE, ResponseBytes.defaultValues(RESPONSE_TYPE)); + this.response = getParametersValue(parameters, RESPONSE, ResponseBytes.defaultValues(RESPONSE)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case RESPONSE_TYPE: + return EMPTY_STRING; + case RESPONSE: + return new OctetString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case RESPONSE_TYPE: + return (memberValue === EMPTY_STRING); + case RESPONSE: + return (memberValue.isEqual(ResponseBytes.defaultValues(memberName))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new ObjectIdentifier({ name: (names.responseType || EMPTY_STRING) }), + new OctetString({ name: (names.response || EMPTY_STRING) }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$7); + const asn1 = compareSchema(schema, schema, ResponseBytes.schema({ + names: { + responseType: RESPONSE_TYPE, + response: RESPONSE + } + })); + AsnError.assertSchema(asn1, this.className); + this.responseType = asn1.result.responseType.valueBlock.toString(); + this.response = asn1.result.response; + } + toSchema() { + return (new Sequence({ + value: [ + new ObjectIdentifier({ value: this.responseType }), + this.response + ] + })); + } + toJSON() { + return { + responseType: this.responseType, + response: this.response.toJSON(), + }; + } +} ResponseBytes.CLASS_NAME = "ResponseBytes"; -const RESPONSE_STATUS = "responseStatus"; -const RESPONSE_BYTES = "responseBytes"; -class OCSPResponse extends PkiObject { - constructor(parameters = {}) { - super(); - this.responseStatus = getParametersValue(parameters, RESPONSE_STATUS, OCSPResponse.defaultValues(RESPONSE_STATUS)); - if (RESPONSE_BYTES in parameters) { - this.responseBytes = getParametersValue(parameters, RESPONSE_BYTES, OCSPResponse.defaultValues(RESPONSE_BYTES)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case RESPONSE_STATUS: - return new Enumerated(); - case RESPONSE_BYTES: - return new ResponseBytes(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case RESPONSE_STATUS: - return (memberValue.isEqual(OCSPResponse.defaultValues(memberName))); - case RESPONSE_BYTES: - return ((ResponseBytes.compareWithDefault("responseType", memberValue.responseType)) && - (ResponseBytes.compareWithDefault("response", memberValue.response))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || "OCSPResponse"), - value: [ - new Enumerated({ name: (names.responseStatus || RESPONSE_STATUS) }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [ - ResponseBytes.schema(names.responseBytes || { - names: { - blockName: RESPONSE_BYTES - } - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, [ - RESPONSE_STATUS, - RESPONSE_BYTES - ]); - const asn1 = compareSchema(schema, schema, OCSPResponse.schema()); - AsnError.assertSchema(asn1, this.className); - this.responseStatus = asn1.result.responseStatus; - if (RESPONSE_BYTES in asn1.result) - this.responseBytes = new ResponseBytes({ schema: asn1.result.responseBytes }); - } - toSchema() { - const outputArray = []; - outputArray.push(this.responseStatus); - if (this.responseBytes) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.responseBytes.toSchema()] - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - responseStatus: this.responseStatus.toJSON() - }; - if (this.responseBytes) { - res.responseBytes = this.responseBytes.toJSON(); - } - return res; - } - getCertificateStatus(certificate, issuerCertificate, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - let basicResponse; - const result = { - isForCertificate: false, - status: 2 - }; - if (!this.responseBytes) - return result; - if (this.responseBytes.responseType !== id_PKIX_OCSP_Basic) - return result; - try { - const asn1Basic = fromBER(this.responseBytes.response.valueBlock.valueHexView); - AsnError.assert(asn1Basic, "Basic OCSP response"); - basicResponse = new BasicOCSPResponse({ schema: asn1Basic.result }); - } - catch (ex) { - return result; - } - return basicResponse.getCertificateStatus(certificate, issuerCertificate, crypto); - }); - } - sign(privateKey, hashAlgorithm, crypto = getCrypto(true)) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (this.responseBytes && this.responseBytes.responseType === id_PKIX_OCSP_Basic) { - const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView); - return basicResponse.sign(privateKey, hashAlgorithm, crypto); - } - throw new Error(`Unknown ResponseBytes type: ${((_a = this.responseBytes) === null || _a === void 0 ? void 0 : _a.responseType) || "Unknown"}`); - }); - } - verify(issuerCertificate = null, crypto = getCrypto(true)) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if ((RESPONSE_BYTES in this) === false) - throw new Error("Empty ResponseBytes field"); - if (this.responseBytes && this.responseBytes.responseType === id_PKIX_OCSP_Basic) { - const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView); - if (issuerCertificate !== null) { - if (!basicResponse.certs) { - basicResponse.certs = []; - } - basicResponse.certs.push(issuerCertificate); - } - return basicResponse.verify({}, crypto); - } - throw new Error(`Unknown ResponseBytes type: ${((_a = this.responseBytes) === null || _a === void 0 ? void 0 : _a.responseType) || "Unknown"}`); - }); - } -} +const RESPONSE_STATUS = "responseStatus"; +const RESPONSE_BYTES = "responseBytes"; +class OCSPResponse extends PkiObject { + constructor(parameters = {}) { + super(); + this.responseStatus = getParametersValue(parameters, RESPONSE_STATUS, OCSPResponse.defaultValues(RESPONSE_STATUS)); + if (RESPONSE_BYTES in parameters) { + this.responseBytes = getParametersValue(parameters, RESPONSE_BYTES, OCSPResponse.defaultValues(RESPONSE_BYTES)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case RESPONSE_STATUS: + return new Enumerated(); + case RESPONSE_BYTES: + return new ResponseBytes(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case RESPONSE_STATUS: + return (memberValue.isEqual(OCSPResponse.defaultValues(memberName))); + case RESPONSE_BYTES: + return ((ResponseBytes.compareWithDefault("responseType", memberValue.responseType)) && + (ResponseBytes.compareWithDefault("response", memberValue.response))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || "OCSPResponse"), + value: [ + new Enumerated({ name: (names.responseStatus || RESPONSE_STATUS) }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [ + ResponseBytes.schema(names.responseBytes || { + names: { + blockName: RESPONSE_BYTES + } + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, [ + RESPONSE_STATUS, + RESPONSE_BYTES + ]); + const asn1 = compareSchema(schema, schema, OCSPResponse.schema()); + AsnError.assertSchema(asn1, this.className); + this.responseStatus = asn1.result.responseStatus; + if (RESPONSE_BYTES in asn1.result) + this.responseBytes = new ResponseBytes({ schema: asn1.result.responseBytes }); + } + toSchema() { + const outputArray = []; + outputArray.push(this.responseStatus); + if (this.responseBytes) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.responseBytes.toSchema()] + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + responseStatus: this.responseStatus.toJSON() + }; + if (this.responseBytes) { + res.responseBytes = this.responseBytes.toJSON(); + } + return res; + } + async getCertificateStatus(certificate, issuerCertificate, crypto = getCrypto(true)) { + let basicResponse; + const result = { + isForCertificate: false, + status: 2 + }; + if (!this.responseBytes) + return result; + if (this.responseBytes.responseType !== id_PKIX_OCSP_Basic) + return result; + try { + const asn1Basic = fromBER(this.responseBytes.response.valueBlock.valueHexView); + AsnError.assert(asn1Basic, "Basic OCSP response"); + basicResponse = new BasicOCSPResponse({ schema: asn1Basic.result }); + } + catch { + return result; + } + return basicResponse.getCertificateStatus(certificate, issuerCertificate, crypto); + } + async sign(privateKey, hashAlgorithm, crypto = getCrypto(true)) { + var _a; + if (this.responseBytes && this.responseBytes.responseType === id_PKIX_OCSP_Basic) { + const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView); + return basicResponse.sign(privateKey, hashAlgorithm, crypto); + } + throw new Error(`Unknown ResponseBytes type: ${((_a = this.responseBytes) === null || _a === void 0 ? void 0 : _a.responseType) || "Unknown"}`); + } + async verify(issuerCertificate = null, crypto = getCrypto(true)) { + var _a; + if ((RESPONSE_BYTES in this) === false) + throw new Error("Empty ResponseBytes field"); + if (this.responseBytes && this.responseBytes.responseType === id_PKIX_OCSP_Basic) { + const basicResponse = BasicOCSPResponse.fromBER(this.responseBytes.response.valueBlock.valueHexView); + if (issuerCertificate !== null) { + if (!basicResponse.certs) { + basicResponse.certs = []; + } + basicResponse.certs.push(issuerCertificate); + } + return basicResponse.verify({}, crypto); + } + throw new Error(`Unknown ResponseBytes type: ${((_a = this.responseBytes) === null || _a === void 0 ? void 0 : _a.responseType) || "Unknown"}`); + } +} OCSPResponse.CLASS_NAME = "OCSPResponse"; -const TYPE = "type"; -const ATTRIBUTES = "attributes"; -const ENCODED_VALUE = "encodedValue"; -const CLEAR_PROPS$6 = [ - ATTRIBUTES -]; -class SignedAndUnsignedAttributes extends PkiObject { - constructor(parameters = {}) { - super(); - this.type = getParametersValue(parameters, TYPE, SignedAndUnsignedAttributes.defaultValues(TYPE)); - this.attributes = getParametersValue(parameters, ATTRIBUTES, SignedAndUnsignedAttributes.defaultValues(ATTRIBUTES)); - this.encodedValue = getParametersValue(parameters, ENCODED_VALUE, SignedAndUnsignedAttributes.defaultValues(ENCODED_VALUE)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case TYPE: - return (-1); - case ATTRIBUTES: - return []; - case ENCODED_VALUE: - return EMPTY_BUFFER; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case TYPE: - return (memberValue === SignedAndUnsignedAttributes.defaultValues(TYPE)); - case ATTRIBUTES: - return (memberValue.length === 0); - case ENCODED_VALUE: - return (memberValue.byteLength === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Constructed({ - name: (names.blockName || EMPTY_STRING), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: names.tagNumber || 0 - }, - value: [ - new Repeated({ - name: (names.attributes || EMPTY_STRING), - value: Attribute.schema() - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$6); - const asn1 = compareSchema(schema, schema, SignedAndUnsignedAttributes.schema({ - names: { - tagNumber: this.type, - attributes: ATTRIBUTES - } - })); - AsnError.assertSchema(asn1, this.className); - this.type = asn1.result.idBlock.tagNumber; - this.encodedValue = BufferSourceConverter.toArrayBuffer(asn1.result.valueBeforeDecodeView); - const encodedView = new Uint8Array(this.encodedValue); - encodedView[0] = 0x31; - if ((ATTRIBUTES in asn1.result) === false) { - if (this.type === 0) - throw new Error("Wrong structure of SignedUnsignedAttributes"); - else - return; - } - this.attributes = Array.from(asn1.result.attributes, element => new Attribute({ schema: element })); - } - toSchema() { - if (SignedAndUnsignedAttributes.compareWithDefault(TYPE, this.type) || SignedAndUnsignedAttributes.compareWithDefault(ATTRIBUTES, this.attributes)) - throw new Error("Incorrectly initialized \"SignedAndUnsignedAttributes\" class"); - return (new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: this.type - }, - value: Array.from(this.attributes, o => o.toSchema()) - })); - } - toJSON() { - if (SignedAndUnsignedAttributes.compareWithDefault(TYPE, this.type) || SignedAndUnsignedAttributes.compareWithDefault(ATTRIBUTES, this.attributes)) - throw new Error("Incorrectly initialized \"SignedAndUnsignedAttributes\" class"); - return { - type: this.type, - attributes: Array.from(this.attributes, o => o.toJSON()) - }; - } -} +const TYPE = "type"; +const ATTRIBUTES = "attributes"; +const ENCODED_VALUE = "encodedValue"; +const CLEAR_PROPS$6 = [ + ATTRIBUTES +]; +class SignedAndUnsignedAttributes extends PkiObject { + constructor(parameters = {}) { + super(); + this.type = getParametersValue(parameters, TYPE, SignedAndUnsignedAttributes.defaultValues(TYPE)); + this.attributes = getParametersValue(parameters, ATTRIBUTES, SignedAndUnsignedAttributes.defaultValues(ATTRIBUTES)); + this.encodedValue = getParametersValue(parameters, ENCODED_VALUE, SignedAndUnsignedAttributes.defaultValues(ENCODED_VALUE)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case TYPE: + return (-1); + case ATTRIBUTES: + return []; + case ENCODED_VALUE: + return EMPTY_BUFFER; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case TYPE: + return (memberValue === SignedAndUnsignedAttributes.defaultValues(TYPE)); + case ATTRIBUTES: + return (memberValue.length === 0); + case ENCODED_VALUE: + return (memberValue.byteLength === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Constructed({ + name: (names.blockName || EMPTY_STRING), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: names.tagNumber || 0 + }, + value: [ + new Repeated({ + name: (names.attributes || EMPTY_STRING), + value: Attribute.schema() + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$6); + const asn1 = compareSchema(schema, schema, SignedAndUnsignedAttributes.schema({ + names: { + tagNumber: this.type, + attributes: ATTRIBUTES + } + })); + AsnError.assertSchema(asn1, this.className); + this.type = asn1.result.idBlock.tagNumber; + this.encodedValue = BufferSourceConverter.toArrayBuffer(asn1.result.valueBeforeDecodeView); + const encodedView = new Uint8Array(this.encodedValue); + encodedView[0] = 0x31; + if ((ATTRIBUTES in asn1.result) === false) { + if (this.type === 0) + throw new Error("Wrong structure of SignedUnsignedAttributes"); + else + return; + } + this.attributes = Array.from(asn1.result.attributes, element => new Attribute({ schema: element })); + } + toSchema() { + if (SignedAndUnsignedAttributes.compareWithDefault(TYPE, this.type) || SignedAndUnsignedAttributes.compareWithDefault(ATTRIBUTES, this.attributes)) + throw new Error("Incorrectly initialized \"SignedAndUnsignedAttributes\" class"); + return (new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: this.type + }, + value: Array.from(this.attributes, o => o.toSchema()) + })); + } + toJSON() { + if (SignedAndUnsignedAttributes.compareWithDefault(TYPE, this.type) || SignedAndUnsignedAttributes.compareWithDefault(ATTRIBUTES, this.attributes)) + throw new Error("Incorrectly initialized \"SignedAndUnsignedAttributes\" class"); + return { + type: this.type, + attributes: Array.from(this.attributes, o => o.toJSON()) + }; + } +} SignedAndUnsignedAttributes.CLASS_NAME = "SignedAndUnsignedAttributes"; -const VERSION$4 = "version"; -const SID = "sid"; -const DIGEST_ALGORITHM = "digestAlgorithm"; -const SIGNED_ATTRS = "signedAttrs"; -const SIGNATURE_ALGORITHM = "signatureAlgorithm"; -const SIGNATURE = "signature"; -const UNSIGNED_ATTRS = "unsignedAttrs"; -const SIGNER_INFO = "SignerInfo"; -const SIGNER_INFO_VERSION = `${SIGNER_INFO}.${VERSION$4}`; -const SIGNER_INFO_SID = `${SIGNER_INFO}.${SID}`; -const SIGNER_INFO_DIGEST_ALGORITHM = `${SIGNER_INFO}.${DIGEST_ALGORITHM}`; -const SIGNER_INFO_SIGNED_ATTRS = `${SIGNER_INFO}.${SIGNED_ATTRS}`; -const SIGNER_INFO_SIGNATURE_ALGORITHM = `${SIGNER_INFO}.${SIGNATURE_ALGORITHM}`; -const SIGNER_INFO_SIGNATURE = `${SIGNER_INFO}.${SIGNATURE}`; -const SIGNER_INFO_UNSIGNED_ATTRS = `${SIGNER_INFO}.${UNSIGNED_ATTRS}`; -const CLEAR_PROPS$5 = [ - SIGNER_INFO_VERSION, - SIGNER_INFO_SID, - SIGNER_INFO_DIGEST_ALGORITHM, - SIGNER_INFO_SIGNED_ATTRS, - SIGNER_INFO_SIGNATURE_ALGORITHM, - SIGNER_INFO_SIGNATURE, - SIGNER_INFO_UNSIGNED_ATTRS -]; -class SignerInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$4, SignerInfo.defaultValues(VERSION$4)); - this.sid = getParametersValue(parameters, SID, SignerInfo.defaultValues(SID)); - this.digestAlgorithm = getParametersValue(parameters, DIGEST_ALGORITHM, SignerInfo.defaultValues(DIGEST_ALGORITHM)); - if (SIGNED_ATTRS in parameters) { - this.signedAttrs = getParametersValue(parameters, SIGNED_ATTRS, SignerInfo.defaultValues(SIGNED_ATTRS)); - } - this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM, SignerInfo.defaultValues(SIGNATURE_ALGORITHM)); - this.signature = getParametersValue(parameters, SIGNATURE, SignerInfo.defaultValues(SIGNATURE)); - if (UNSIGNED_ATTRS in parameters) { - this.unsignedAttrs = getParametersValue(parameters, UNSIGNED_ATTRS, SignerInfo.defaultValues(UNSIGNED_ATTRS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$4: - return 0; - case SID: - return new Any(); - case DIGEST_ALGORITHM: - return new AlgorithmIdentifier(); - case SIGNED_ATTRS: - return new SignedAndUnsignedAttributes({ type: 0 }); - case SIGNATURE_ALGORITHM: - return new AlgorithmIdentifier(); - case SIGNATURE: - return new OctetString(); - case UNSIGNED_ATTRS: - return new SignedAndUnsignedAttributes({ type: 1 }); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$4: - return (SignerInfo.defaultValues(VERSION$4) === memberValue); - case SID: - return (memberValue instanceof Any); - case DIGEST_ALGORITHM: - if ((memberValue instanceof AlgorithmIdentifier) === false) - return false; - return memberValue.isEqual(SignerInfo.defaultValues(DIGEST_ALGORITHM)); - case SIGNED_ATTRS: - return ((SignedAndUnsignedAttributes.compareWithDefault("type", memberValue.type)) - && (SignedAndUnsignedAttributes.compareWithDefault("attributes", memberValue.attributes)) - && (SignedAndUnsignedAttributes.compareWithDefault("encodedValue", memberValue.encodedValue))); - case SIGNATURE_ALGORITHM: - if ((memberValue instanceof AlgorithmIdentifier) === false) - return false; - return memberValue.isEqual(SignerInfo.defaultValues(SIGNATURE_ALGORITHM)); - case SIGNATURE: - case UNSIGNED_ATTRS: - return ((SignedAndUnsignedAttributes.compareWithDefault("type", memberValue.type)) - && (SignedAndUnsignedAttributes.compareWithDefault("attributes", memberValue.attributes)) - && (SignedAndUnsignedAttributes.compareWithDefault("encodedValue", memberValue.encodedValue))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: SIGNER_INFO, - value: [ - new Integer({ name: (names.version || SIGNER_INFO_VERSION) }), - new Choice({ - value: [ - IssuerAndSerialNumber.schema(names.sidSchema || { - names: { - blockName: SIGNER_INFO_SID - } - }), - new Choice({ - value: [ - new Constructed({ - optional: true, - name: (names.sid || SIGNER_INFO_SID), - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new OctetString()] - }), - new Primitive({ - optional: true, - name: (names.sid || SIGNER_INFO_SID), - idBlock: { - tagClass: 3, - tagNumber: 0 - } - }), - ] - }), - ] - }), - AlgorithmIdentifier.schema(names.digestAlgorithm || { - names: { - blockName: SIGNER_INFO_DIGEST_ALGORITHM - } - }), - SignedAndUnsignedAttributes.schema(names.signedAttrs || { - names: { - blockName: SIGNER_INFO_SIGNED_ATTRS, - tagNumber: 0 - } - }), - AlgorithmIdentifier.schema(names.signatureAlgorithm || { - names: { - blockName: SIGNER_INFO_SIGNATURE_ALGORITHM - } - }), - new OctetString({ name: (names.signature || SIGNER_INFO_SIGNATURE) }), - SignedAndUnsignedAttributes.schema(names.unsignedAttrs || { - names: { - blockName: SIGNER_INFO_UNSIGNED_ATTRS, - tagNumber: 1 - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$5); - const asn1 = compareSchema(schema, schema, SignerInfo.schema()); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result[SIGNER_INFO_VERSION].valueBlock.valueDec; - const currentSid = asn1.result[SIGNER_INFO_SID]; - if (currentSid.idBlock.tagClass === 1) - this.sid = new IssuerAndSerialNumber({ schema: currentSid }); - else - this.sid = currentSid; - this.digestAlgorithm = new AlgorithmIdentifier({ schema: asn1.result[SIGNER_INFO_DIGEST_ALGORITHM] }); - if (SIGNER_INFO_SIGNED_ATTRS in asn1.result) - this.signedAttrs = new SignedAndUnsignedAttributes({ type: 0, schema: asn1.result[SIGNER_INFO_SIGNED_ATTRS] }); - this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result[SIGNER_INFO_SIGNATURE_ALGORITHM] }); - this.signature = asn1.result[SIGNER_INFO_SIGNATURE]; - if (SIGNER_INFO_UNSIGNED_ATTRS in asn1.result) - this.unsignedAttrs = new SignedAndUnsignedAttributes({ type: 1, schema: asn1.result[SIGNER_INFO_UNSIGNED_ATTRS] }); - } - toSchema() { - if (SignerInfo.compareWithDefault(SID, this.sid)) - throw new Error("Incorrectly initialized \"SignerInfo\" class"); - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - if (this.sid instanceof IssuerAndSerialNumber) - outputArray.push(this.sid.toSchema()); - else - outputArray.push(this.sid); - outputArray.push(this.digestAlgorithm.toSchema()); - if (this.signedAttrs) { - if (SignerInfo.compareWithDefault(SIGNED_ATTRS, this.signedAttrs) === false) - outputArray.push(this.signedAttrs.toSchema()); - } - outputArray.push(this.signatureAlgorithm.toSchema()); - outputArray.push(this.signature); - if (this.unsignedAttrs) { - if (SignerInfo.compareWithDefault(UNSIGNED_ATTRS, this.unsignedAttrs) === false) - outputArray.push(this.unsignedAttrs.toSchema()); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - if (SignerInfo.compareWithDefault(SID, this.sid)) { - throw new Error("Incorrectly initialized \"SignerInfo\" class"); - } - const res = { - version: this.version, - digestAlgorithm: this.digestAlgorithm.toJSON(), - signatureAlgorithm: this.signatureAlgorithm.toJSON(), - signature: this.signature.toJSON(), - }; - if (!(this.sid instanceof Any)) - res.sid = this.sid.toJSON(); - if (this.signedAttrs && SignerInfo.compareWithDefault(SIGNED_ATTRS, this.signedAttrs) === false) { - res.signedAttrs = this.signedAttrs.toJSON(); - } - if (this.unsignedAttrs && SignerInfo.compareWithDefault(UNSIGNED_ATTRS, this.unsignedAttrs) === false) { - res.unsignedAttrs = this.unsignedAttrs.toJSON(); - } - return res; - } -} +const VERSION$4 = "version"; +const SID = "sid"; +const DIGEST_ALGORITHM = "digestAlgorithm"; +const SIGNED_ATTRS = "signedAttrs"; +const SIGNATURE_ALGORITHM = "signatureAlgorithm"; +const SIGNATURE = "signature"; +const UNSIGNED_ATTRS = "unsignedAttrs"; +const SIGNER_INFO = "SignerInfo"; +const SIGNER_INFO_VERSION = `${SIGNER_INFO}.${VERSION$4}`; +const SIGNER_INFO_SID = `${SIGNER_INFO}.${SID}`; +const SIGNER_INFO_DIGEST_ALGORITHM = `${SIGNER_INFO}.${DIGEST_ALGORITHM}`; +const SIGNER_INFO_SIGNED_ATTRS = `${SIGNER_INFO}.${SIGNED_ATTRS}`; +const SIGNER_INFO_SIGNATURE_ALGORITHM = `${SIGNER_INFO}.${SIGNATURE_ALGORITHM}`; +const SIGNER_INFO_SIGNATURE = `${SIGNER_INFO}.${SIGNATURE}`; +const SIGNER_INFO_UNSIGNED_ATTRS = `${SIGNER_INFO}.${UNSIGNED_ATTRS}`; +const CLEAR_PROPS$5 = [ + SIGNER_INFO_VERSION, + SIGNER_INFO_SID, + SIGNER_INFO_DIGEST_ALGORITHM, + SIGNER_INFO_SIGNED_ATTRS, + SIGNER_INFO_SIGNATURE_ALGORITHM, + SIGNER_INFO_SIGNATURE, + SIGNER_INFO_UNSIGNED_ATTRS +]; +class SignerInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$4, SignerInfo.defaultValues(VERSION$4)); + this.sid = getParametersValue(parameters, SID, SignerInfo.defaultValues(SID)); + this.digestAlgorithm = getParametersValue(parameters, DIGEST_ALGORITHM, SignerInfo.defaultValues(DIGEST_ALGORITHM)); + if (SIGNED_ATTRS in parameters) { + this.signedAttrs = getParametersValue(parameters, SIGNED_ATTRS, SignerInfo.defaultValues(SIGNED_ATTRS)); + } + this.signatureAlgorithm = getParametersValue(parameters, SIGNATURE_ALGORITHM, SignerInfo.defaultValues(SIGNATURE_ALGORITHM)); + this.signature = getParametersValue(parameters, SIGNATURE, SignerInfo.defaultValues(SIGNATURE)); + if (UNSIGNED_ATTRS in parameters) { + this.unsignedAttrs = getParametersValue(parameters, UNSIGNED_ATTRS, SignerInfo.defaultValues(UNSIGNED_ATTRS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$4: + return 0; + case SID: + return new Any(); + case DIGEST_ALGORITHM: + return new AlgorithmIdentifier(); + case SIGNED_ATTRS: + return new SignedAndUnsignedAttributes({ type: 0 }); + case SIGNATURE_ALGORITHM: + return new AlgorithmIdentifier(); + case SIGNATURE: + return new OctetString(); + case UNSIGNED_ATTRS: + return new SignedAndUnsignedAttributes({ type: 1 }); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$4: + return (SignerInfo.defaultValues(VERSION$4) === memberValue); + case SID: + return (memberValue instanceof Any); + case DIGEST_ALGORITHM: + if ((memberValue instanceof AlgorithmIdentifier) === false) + return false; + return memberValue.isEqual(SignerInfo.defaultValues(DIGEST_ALGORITHM)); + case SIGNED_ATTRS: + return ((SignedAndUnsignedAttributes.compareWithDefault("type", memberValue.type)) + && (SignedAndUnsignedAttributes.compareWithDefault("attributes", memberValue.attributes)) + && (SignedAndUnsignedAttributes.compareWithDefault("encodedValue", memberValue.encodedValue))); + case SIGNATURE_ALGORITHM: + if ((memberValue instanceof AlgorithmIdentifier) === false) + return false; + return memberValue.isEqual(SignerInfo.defaultValues(SIGNATURE_ALGORITHM)); + case SIGNATURE: + case UNSIGNED_ATTRS: + return ((SignedAndUnsignedAttributes.compareWithDefault("type", memberValue.type)) + && (SignedAndUnsignedAttributes.compareWithDefault("attributes", memberValue.attributes)) + && (SignedAndUnsignedAttributes.compareWithDefault("encodedValue", memberValue.encodedValue))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: SIGNER_INFO, + value: [ + new Integer({ name: (names.version || SIGNER_INFO_VERSION) }), + new Choice({ + value: [ + IssuerAndSerialNumber.schema(names.sidSchema || { + names: { + blockName: SIGNER_INFO_SID + } + }), + new Choice({ + value: [ + new Constructed({ + optional: true, + name: (names.sid || SIGNER_INFO_SID), + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new OctetString()] + }), + new Primitive({ + optional: true, + name: (names.sid || SIGNER_INFO_SID), + idBlock: { + tagClass: 3, + tagNumber: 0 + } + }), + ] + }), + ] + }), + AlgorithmIdentifier.schema(names.digestAlgorithm || { + names: { + blockName: SIGNER_INFO_DIGEST_ALGORITHM + } + }), + SignedAndUnsignedAttributes.schema(names.signedAttrs || { + names: { + blockName: SIGNER_INFO_SIGNED_ATTRS, + tagNumber: 0 + } + }), + AlgorithmIdentifier.schema(names.signatureAlgorithm || { + names: { + blockName: SIGNER_INFO_SIGNATURE_ALGORITHM + } + }), + new OctetString({ name: (names.signature || SIGNER_INFO_SIGNATURE) }), + SignedAndUnsignedAttributes.schema(names.unsignedAttrs || { + names: { + blockName: SIGNER_INFO_UNSIGNED_ATTRS, + tagNumber: 1 + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$5); + const asn1 = compareSchema(schema, schema, SignerInfo.schema()); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result[SIGNER_INFO_VERSION].valueBlock.valueDec; + const currentSid = asn1.result[SIGNER_INFO_SID]; + if (currentSid.idBlock.tagClass === 1) + this.sid = new IssuerAndSerialNumber({ schema: currentSid }); + else + this.sid = currentSid; + this.digestAlgorithm = new AlgorithmIdentifier({ schema: asn1.result[SIGNER_INFO_DIGEST_ALGORITHM] }); + if (SIGNER_INFO_SIGNED_ATTRS in asn1.result) + this.signedAttrs = new SignedAndUnsignedAttributes({ type: 0, schema: asn1.result[SIGNER_INFO_SIGNED_ATTRS] }); + this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result[SIGNER_INFO_SIGNATURE_ALGORITHM] }); + this.signature = asn1.result[SIGNER_INFO_SIGNATURE]; + if (SIGNER_INFO_UNSIGNED_ATTRS in asn1.result) + this.unsignedAttrs = new SignedAndUnsignedAttributes({ type: 1, schema: asn1.result[SIGNER_INFO_UNSIGNED_ATTRS] }); + } + toSchema() { + if (SignerInfo.compareWithDefault(SID, this.sid)) + throw new Error("Incorrectly initialized \"SignerInfo\" class"); + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + if (this.sid instanceof IssuerAndSerialNumber) + outputArray.push(this.sid.toSchema()); + else + outputArray.push(this.sid); + outputArray.push(this.digestAlgorithm.toSchema()); + if (this.signedAttrs) { + if (SignerInfo.compareWithDefault(SIGNED_ATTRS, this.signedAttrs) === false) + outputArray.push(this.signedAttrs.toSchema()); + } + outputArray.push(this.signatureAlgorithm.toSchema()); + outputArray.push(this.signature); + if (this.unsignedAttrs) { + if (SignerInfo.compareWithDefault(UNSIGNED_ATTRS, this.unsignedAttrs) === false) + outputArray.push(this.unsignedAttrs.toSchema()); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + if (SignerInfo.compareWithDefault(SID, this.sid)) { + throw new Error("Incorrectly initialized \"SignerInfo\" class"); + } + const res = { + version: this.version, + digestAlgorithm: this.digestAlgorithm.toJSON(), + signatureAlgorithm: this.signatureAlgorithm.toJSON(), + signature: this.signature.toJSON(), + }; + if (!(this.sid instanceof Any)) + res.sid = this.sid.toJSON(); + if (this.signedAttrs && SignerInfo.compareWithDefault(SIGNED_ATTRS, this.signedAttrs) === false) { + res.signedAttrs = this.signedAttrs.toJSON(); + } + if (this.unsignedAttrs && SignerInfo.compareWithDefault(UNSIGNED_ATTRS, this.unsignedAttrs) === false) { + res.unsignedAttrs = this.unsignedAttrs.toJSON(); + } + return res; + } +} SignerInfo.CLASS_NAME = "SignerInfo"; -const VERSION$3 = "version"; -const POLICY = "policy"; -const MESSAGE_IMPRINT$1 = "messageImprint"; -const SERIAL_NUMBER = "serialNumber"; -const GEN_TIME = "genTime"; -const ORDERING = "ordering"; -const NONCE$1 = "nonce"; -const ACCURACY = "accuracy"; -const TSA = "tsa"; -const EXTENSIONS$1 = "extensions"; -const TST_INFO = "TSTInfo"; -const TST_INFO_VERSION = `${TST_INFO}.${VERSION$3}`; -const TST_INFO_POLICY = `${TST_INFO}.${POLICY}`; -const TST_INFO_MESSAGE_IMPRINT = `${TST_INFO}.${MESSAGE_IMPRINT$1}`; -const TST_INFO_SERIAL_NUMBER = `${TST_INFO}.${SERIAL_NUMBER}`; -const TST_INFO_GEN_TIME = `${TST_INFO}.${GEN_TIME}`; -const TST_INFO_ACCURACY = `${TST_INFO}.${ACCURACY}`; -const TST_INFO_ORDERING = `${TST_INFO}.${ORDERING}`; -const TST_INFO_NONCE = `${TST_INFO}.${NONCE$1}`; -const TST_INFO_TSA = `${TST_INFO}.${TSA}`; -const TST_INFO_EXTENSIONS = `${TST_INFO}.${EXTENSIONS$1}`; -const CLEAR_PROPS$4 = [ - TST_INFO_VERSION, - TST_INFO_POLICY, - TST_INFO_MESSAGE_IMPRINT, - TST_INFO_SERIAL_NUMBER, - TST_INFO_GEN_TIME, - TST_INFO_ACCURACY, - TST_INFO_ORDERING, - TST_INFO_NONCE, - TST_INFO_TSA, - TST_INFO_EXTENSIONS -]; -class TSTInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$3, TSTInfo.defaultValues(VERSION$3)); - this.policy = getParametersValue(parameters, POLICY, TSTInfo.defaultValues(POLICY)); - this.messageImprint = getParametersValue(parameters, MESSAGE_IMPRINT$1, TSTInfo.defaultValues(MESSAGE_IMPRINT$1)); - this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER, TSTInfo.defaultValues(SERIAL_NUMBER)); - this.genTime = getParametersValue(parameters, GEN_TIME, TSTInfo.defaultValues(GEN_TIME)); - if (ACCURACY in parameters) { - this.accuracy = getParametersValue(parameters, ACCURACY, TSTInfo.defaultValues(ACCURACY)); - } - if (ORDERING in parameters) { - this.ordering = getParametersValue(parameters, ORDERING, TSTInfo.defaultValues(ORDERING)); - } - if (NONCE$1 in parameters) { - this.nonce = getParametersValue(parameters, NONCE$1, TSTInfo.defaultValues(NONCE$1)); - } - if (TSA in parameters) { - this.tsa = getParametersValue(parameters, TSA, TSTInfo.defaultValues(TSA)); - } - if (EXTENSIONS$1 in parameters) { - this.extensions = getParametersValue(parameters, EXTENSIONS$1, TSTInfo.defaultValues(EXTENSIONS$1)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$3: - return 0; - case POLICY: - return EMPTY_STRING; - case MESSAGE_IMPRINT$1: - return new MessageImprint(); - case SERIAL_NUMBER: - return new Integer(); - case GEN_TIME: - return new Date(0, 0, 0); - case ACCURACY: - return new Accuracy(); - case ORDERING: - return false; - case NONCE$1: - return new Integer(); - case TSA: - return new GeneralName(); - case EXTENSIONS$1: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$3: - case POLICY: - case GEN_TIME: - case ORDERING: - return (memberValue === TSTInfo.defaultValues(ORDERING)); - case MESSAGE_IMPRINT$1: - return ((MessageImprint.compareWithDefault(HASH_ALGORITHM, memberValue.hashAlgorithm)) && - (MessageImprint.compareWithDefault(HASHED_MESSAGE, memberValue.hashedMessage))); - case SERIAL_NUMBER: - case NONCE$1: - return (memberValue.isEqual(TSTInfo.defaultValues(NONCE$1))); - case ACCURACY: - return ((Accuracy.compareWithDefault(SECONDS, memberValue.seconds)) && - (Accuracy.compareWithDefault(MILLIS, memberValue.millis)) && - (Accuracy.compareWithDefault(MICROS, memberValue.micros))); - case TSA: - return ((GeneralName.compareWithDefault(TYPE$4, memberValue.type)) && - (GeneralName.compareWithDefault(VALUE$5, memberValue.value))); - case EXTENSIONS$1: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || TST_INFO), - value: [ - new Integer({ name: (names.version || TST_INFO_VERSION) }), - new ObjectIdentifier({ name: (names.policy || TST_INFO_POLICY) }), - MessageImprint.schema(names.messageImprint || { - names: { - blockName: TST_INFO_MESSAGE_IMPRINT - } - }), - new Integer({ name: (names.serialNumber || TST_INFO_SERIAL_NUMBER) }), - new GeneralizedTime({ name: (names.genTime || TST_INFO_GEN_TIME) }), - Accuracy.schema(names.accuracy || { - names: { - blockName: TST_INFO_ACCURACY - } - }), - new Boolean({ - name: (names.ordering || TST_INFO_ORDERING), - optional: true - }), - new Integer({ - name: (names.nonce || TST_INFO_NONCE), - optional: true - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [GeneralName.schema(names.tsa || { - names: { - blockName: TST_INFO_TSA - } - })] - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: [ - new Repeated({ - name: (names.extensions || TST_INFO_EXTENSIONS), - value: Extension.schema(names.extension || {}) - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$4); - const asn1 = compareSchema(schema, schema, TSTInfo.schema()); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result[TST_INFO_VERSION].valueBlock.valueDec; - this.policy = asn1.result[TST_INFO_POLICY].valueBlock.toString(); - this.messageImprint = new MessageImprint({ schema: asn1.result[TST_INFO_MESSAGE_IMPRINT] }); - this.serialNumber = asn1.result[TST_INFO_SERIAL_NUMBER]; - this.genTime = asn1.result[TST_INFO_GEN_TIME].toDate(); - if (TST_INFO_ACCURACY in asn1.result) - this.accuracy = new Accuracy({ schema: asn1.result[TST_INFO_ACCURACY] }); - if (TST_INFO_ORDERING in asn1.result) - this.ordering = asn1.result[TST_INFO_ORDERING].valueBlock.value; - if (TST_INFO_NONCE in asn1.result) - this.nonce = asn1.result[TST_INFO_NONCE]; - if (TST_INFO_TSA in asn1.result) - this.tsa = new GeneralName({ schema: asn1.result[TST_INFO_TSA] }); - if (TST_INFO_EXTENSIONS in asn1.result) - this.extensions = Array.from(asn1.result[TST_INFO_EXTENSIONS], element => new Extension({ schema: element })); - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - outputArray.push(new ObjectIdentifier({ value: this.policy })); - outputArray.push(this.messageImprint.toSchema()); - outputArray.push(this.serialNumber); - outputArray.push(new GeneralizedTime({ valueDate: this.genTime })); - if (this.accuracy) - outputArray.push(this.accuracy.toSchema()); - if (this.ordering !== undefined) - outputArray.push(new Boolean({ value: this.ordering })); - if (this.nonce) - outputArray.push(this.nonce); - if (this.tsa) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [this.tsa.toSchema()] - })); - } - if (this.extensions) { - outputArray.push(new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: Array.from(this.extensions, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - version: this.version, - policy: this.policy, - messageImprint: this.messageImprint.toJSON(), - serialNumber: this.serialNumber.toJSON(), - genTime: this.genTime - }; - if (this.accuracy) - res.accuracy = this.accuracy.toJSON(); - if (this.ordering !== undefined) - res.ordering = this.ordering; - if (this.nonce) - res.nonce = this.nonce.toJSON(); - if (this.tsa) - res.tsa = this.tsa.toJSON(); - if (this.extensions) - res.extensions = Array.from(this.extensions, o => o.toJSON()); - return res; - } - verify(params, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - if (!params.data) { - throw new Error("\"data\" is a mandatory attribute for TST_INFO verification"); - } - const data = params.data; - if (params.notBefore) { - if (this.genTime < params.notBefore) - throw new Error("Generation time for TSTInfo object is less than notBefore value"); - } - if (params.notAfter) { - if (this.genTime > params.notAfter) - throw new Error("Generation time for TSTInfo object is more than notAfter value"); - } - const shaAlgorithm = crypto.getAlgorithmByOID(this.messageImprint.hashAlgorithm.algorithmId, true, "MessageImprint.hashAlgorithm"); - const hash = yield crypto.digest(shaAlgorithm.name, new Uint8Array(data)); - return BufferSourceConverter.isEqual(hash, this.messageImprint.hashedMessage.valueBlock.valueHexView); - }); - } -} +const VERSION$3 = "version"; +const POLICY = "policy"; +const MESSAGE_IMPRINT$1 = "messageImprint"; +const SERIAL_NUMBER = "serialNumber"; +const GEN_TIME = "genTime"; +const ORDERING = "ordering"; +const NONCE$1 = "nonce"; +const ACCURACY = "accuracy"; +const TSA = "tsa"; +const EXTENSIONS$1 = "extensions"; +const TST_INFO = "TSTInfo"; +const TST_INFO_VERSION = `${TST_INFO}.${VERSION$3}`; +const TST_INFO_POLICY = `${TST_INFO}.${POLICY}`; +const TST_INFO_MESSAGE_IMPRINT = `${TST_INFO}.${MESSAGE_IMPRINT$1}`; +const TST_INFO_SERIAL_NUMBER = `${TST_INFO}.${SERIAL_NUMBER}`; +const TST_INFO_GEN_TIME = `${TST_INFO}.${GEN_TIME}`; +const TST_INFO_ACCURACY = `${TST_INFO}.${ACCURACY}`; +const TST_INFO_ORDERING = `${TST_INFO}.${ORDERING}`; +const TST_INFO_NONCE = `${TST_INFO}.${NONCE$1}`; +const TST_INFO_TSA = `${TST_INFO}.${TSA}`; +const TST_INFO_EXTENSIONS = `${TST_INFO}.${EXTENSIONS$1}`; +const CLEAR_PROPS$4 = [ + TST_INFO_VERSION, + TST_INFO_POLICY, + TST_INFO_MESSAGE_IMPRINT, + TST_INFO_SERIAL_NUMBER, + TST_INFO_GEN_TIME, + TST_INFO_ACCURACY, + TST_INFO_ORDERING, + TST_INFO_NONCE, + TST_INFO_TSA, + TST_INFO_EXTENSIONS +]; +class TSTInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$3, TSTInfo.defaultValues(VERSION$3)); + this.policy = getParametersValue(parameters, POLICY, TSTInfo.defaultValues(POLICY)); + this.messageImprint = getParametersValue(parameters, MESSAGE_IMPRINT$1, TSTInfo.defaultValues(MESSAGE_IMPRINT$1)); + this.serialNumber = getParametersValue(parameters, SERIAL_NUMBER, TSTInfo.defaultValues(SERIAL_NUMBER)); + this.genTime = getParametersValue(parameters, GEN_TIME, TSTInfo.defaultValues(GEN_TIME)); + if (ACCURACY in parameters) { + this.accuracy = getParametersValue(parameters, ACCURACY, TSTInfo.defaultValues(ACCURACY)); + } + if (ORDERING in parameters) { + this.ordering = getParametersValue(parameters, ORDERING, TSTInfo.defaultValues(ORDERING)); + } + if (NONCE$1 in parameters) { + this.nonce = getParametersValue(parameters, NONCE$1, TSTInfo.defaultValues(NONCE$1)); + } + if (TSA in parameters) { + this.tsa = getParametersValue(parameters, TSA, TSTInfo.defaultValues(TSA)); + } + if (EXTENSIONS$1 in parameters) { + this.extensions = getParametersValue(parameters, EXTENSIONS$1, TSTInfo.defaultValues(EXTENSIONS$1)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$3: + return 0; + case POLICY: + return EMPTY_STRING; + case MESSAGE_IMPRINT$1: + return new MessageImprint(); + case SERIAL_NUMBER: + return new Integer(); + case GEN_TIME: + return new Date(0, 0, 0); + case ACCURACY: + return new Accuracy(); + case ORDERING: + return false; + case NONCE$1: + return new Integer(); + case TSA: + return new GeneralName(); + case EXTENSIONS$1: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$3: + case POLICY: + case GEN_TIME: + case ORDERING: + return (memberValue === TSTInfo.defaultValues(ORDERING)); + case MESSAGE_IMPRINT$1: + return ((MessageImprint.compareWithDefault(HASH_ALGORITHM, memberValue.hashAlgorithm)) && + (MessageImprint.compareWithDefault(HASHED_MESSAGE, memberValue.hashedMessage))); + case SERIAL_NUMBER: + case NONCE$1: + return (memberValue.isEqual(TSTInfo.defaultValues(NONCE$1))); + case ACCURACY: + return ((Accuracy.compareWithDefault(SECONDS, memberValue.seconds)) && + (Accuracy.compareWithDefault(MILLIS, memberValue.millis)) && + (Accuracy.compareWithDefault(MICROS, memberValue.micros))); + case TSA: + return ((GeneralName.compareWithDefault(TYPE$4, memberValue.type)) && + (GeneralName.compareWithDefault(VALUE$5, memberValue.value))); + case EXTENSIONS$1: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || TST_INFO), + value: [ + new Integer({ name: (names.version || TST_INFO_VERSION) }), + new ObjectIdentifier({ name: (names.policy || TST_INFO_POLICY) }), + MessageImprint.schema(names.messageImprint || { + names: { + blockName: TST_INFO_MESSAGE_IMPRINT + } + }), + new Integer({ name: (names.serialNumber || TST_INFO_SERIAL_NUMBER) }), + new GeneralizedTime({ name: (names.genTime || TST_INFO_GEN_TIME) }), + Accuracy.schema(names.accuracy || { + names: { + blockName: TST_INFO_ACCURACY + } + }), + new Boolean({ + name: (names.ordering || TST_INFO_ORDERING), + optional: true + }), + new Integer({ + name: (names.nonce || TST_INFO_NONCE), + optional: true + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [GeneralName.schema(names.tsa || { + names: { + blockName: TST_INFO_TSA + } + })] + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: [ + new Repeated({ + name: (names.extensions || TST_INFO_EXTENSIONS), + value: Extension.schema(names.extension || {}) + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$4); + const asn1 = compareSchema(schema, schema, TSTInfo.schema()); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result[TST_INFO_VERSION].valueBlock.valueDec; + this.policy = asn1.result[TST_INFO_POLICY].valueBlock.toString(); + this.messageImprint = new MessageImprint({ schema: asn1.result[TST_INFO_MESSAGE_IMPRINT] }); + this.serialNumber = asn1.result[TST_INFO_SERIAL_NUMBER]; + this.genTime = asn1.result[TST_INFO_GEN_TIME].toDate(); + if (TST_INFO_ACCURACY in asn1.result) + this.accuracy = new Accuracy({ schema: asn1.result[TST_INFO_ACCURACY] }); + if (TST_INFO_ORDERING in asn1.result) + this.ordering = asn1.result[TST_INFO_ORDERING].valueBlock.value; + if (TST_INFO_NONCE in asn1.result) + this.nonce = asn1.result[TST_INFO_NONCE]; + if (TST_INFO_TSA in asn1.result) + this.tsa = new GeneralName({ schema: asn1.result[TST_INFO_TSA] }); + if (TST_INFO_EXTENSIONS in asn1.result) + this.extensions = Array.from(asn1.result[TST_INFO_EXTENSIONS], element => new Extension({ schema: element })); + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + outputArray.push(new ObjectIdentifier({ value: this.policy })); + outputArray.push(this.messageImprint.toSchema()); + outputArray.push(this.serialNumber); + outputArray.push(new GeneralizedTime({ valueDate: this.genTime })); + if (this.accuracy) + outputArray.push(this.accuracy.toSchema()); + if (this.ordering !== undefined) + outputArray.push(new Boolean({ value: this.ordering })); + if (this.nonce) + outputArray.push(this.nonce); + if (this.tsa) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [this.tsa.toSchema()] + })); + } + if (this.extensions) { + outputArray.push(new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: Array.from(this.extensions, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + version: this.version, + policy: this.policy, + messageImprint: this.messageImprint.toJSON(), + serialNumber: this.serialNumber.toJSON(), + genTime: this.genTime + }; + if (this.accuracy) + res.accuracy = this.accuracy.toJSON(); + if (this.ordering !== undefined) + res.ordering = this.ordering; + if (this.nonce) + res.nonce = this.nonce.toJSON(); + if (this.tsa) + res.tsa = this.tsa.toJSON(); + if (this.extensions) + res.extensions = Array.from(this.extensions, o => o.toJSON()); + return res; + } + async verify(params, crypto = getCrypto(true)) { + if (!params.data) { + throw new Error("\"data\" is a mandatory attribute for TST_INFO verification"); + } + const data = params.data; + if (params.notBefore) { + if (this.genTime < params.notBefore) + throw new Error("Generation time for TSTInfo object is less than notBefore value"); + } + if (params.notAfter) { + if (this.genTime > params.notAfter) + throw new Error("Generation time for TSTInfo object is more than notAfter value"); + } + const shaAlgorithm = crypto.getAlgorithmByOID(this.messageImprint.hashAlgorithm.algorithmId, true, "MessageImprint.hashAlgorithm"); + const hash = await crypto.digest(shaAlgorithm.name, new Uint8Array(data)); + return BufferSourceConverter.isEqual(hash, this.messageImprint.hashedMessage.valueBlock.valueHexView); + } +} TSTInfo.CLASS_NAME = "TSTInfo"; -const VERSION$2 = "version"; -const DIGEST_ALGORITHMS = "digestAlgorithms"; -const ENCAP_CONTENT_INFO = "encapContentInfo"; -const CERTIFICATES = "certificates"; -const CRLS = "crls"; -const SIGNER_INFOS = "signerInfos"; -const OCSPS = "ocsps"; -const SIGNED_DATA = "SignedData"; -const SIGNED_DATA_VERSION = `${SIGNED_DATA}.${VERSION$2}`; -const SIGNED_DATA_DIGEST_ALGORITHMS = `${SIGNED_DATA}.${DIGEST_ALGORITHMS}`; -const SIGNED_DATA_ENCAP_CONTENT_INFO = `${SIGNED_DATA}.${ENCAP_CONTENT_INFO}`; -const SIGNED_DATA_CERTIFICATES = `${SIGNED_DATA}.${CERTIFICATES}`; -const SIGNED_DATA_CRLS = `${SIGNED_DATA}.${CRLS}`; -const SIGNED_DATA_SIGNER_INFOS = `${SIGNED_DATA}.${SIGNER_INFOS}`; -const CLEAR_PROPS$3 = [ - SIGNED_DATA_VERSION, - SIGNED_DATA_DIGEST_ALGORITHMS, - SIGNED_DATA_ENCAP_CONTENT_INFO, - SIGNED_DATA_CERTIFICATES, - SIGNED_DATA_CRLS, - SIGNED_DATA_SIGNER_INFOS -]; -class SignedDataVerifyError extends Error { - constructor({ message, code = 0, date = new Date(), signatureVerified = null, signerCertificate = null, signerCertificateVerified = null, timestampSerial = null, certificatePath = [], }) { - super(message); - this.name = "SignedDataVerifyError"; - this.date = date; - this.code = code; - this.timestampSerial = timestampSerial; - this.signatureVerified = signatureVerified; - this.signerCertificate = signerCertificate; - this.signerCertificateVerified = signerCertificateVerified; - this.certificatePath = certificatePath; - } -} -class SignedData extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$2, SignedData.defaultValues(VERSION$2)); - this.digestAlgorithms = getParametersValue(parameters, DIGEST_ALGORITHMS, SignedData.defaultValues(DIGEST_ALGORITHMS)); - this.encapContentInfo = getParametersValue(parameters, ENCAP_CONTENT_INFO, SignedData.defaultValues(ENCAP_CONTENT_INFO)); - if (CERTIFICATES in parameters) { - this.certificates = getParametersValue(parameters, CERTIFICATES, SignedData.defaultValues(CERTIFICATES)); - } - if (CRLS in parameters) { - this.crls = getParametersValue(parameters, CRLS, SignedData.defaultValues(CRLS)); - } - if (OCSPS in parameters) { - this.ocsps = getParametersValue(parameters, OCSPS, SignedData.defaultValues(OCSPS)); - } - this.signerInfos = getParametersValue(parameters, SIGNER_INFOS, SignedData.defaultValues(SIGNER_INFOS)); - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$2: - return 0; - case DIGEST_ALGORITHMS: - return []; - case ENCAP_CONTENT_INFO: - return new EncapsulatedContentInfo(); - case CERTIFICATES: - return []; - case CRLS: - return []; - case OCSPS: - return []; - case SIGNER_INFOS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$2: - return (memberValue === SignedData.defaultValues(VERSION$2)); - case ENCAP_CONTENT_INFO: - return EncapsulatedContentInfo.compareWithDefault("eContentType", memberValue.eContentType) && - EncapsulatedContentInfo.compareWithDefault("eContent", memberValue.eContent); - case DIGEST_ALGORITHMS: - case CERTIFICATES: - case CRLS: - case OCSPS: - case SIGNER_INFOS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - if (names.optional === undefined) { - names.optional = false; - } - return (new Sequence({ - name: (names.blockName || SIGNED_DATA), - optional: names.optional, - value: [ - new Integer({ name: (names.version || SIGNED_DATA_VERSION) }), - new Set({ - value: [ - new Repeated({ - name: (names.digestAlgorithms || SIGNED_DATA_DIGEST_ALGORITHMS), - value: AlgorithmIdentifier.schema() - }) - ] - }), - EncapsulatedContentInfo.schema(names.encapContentInfo || { - names: { - blockName: SIGNED_DATA_ENCAP_CONTENT_INFO - } - }), - new Constructed({ - name: (names.certificates || SIGNED_DATA_CERTIFICATES), - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: CertificateSet.schema().valueBlock.value - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: RevocationInfoChoices.schema(names.crls || { - names: { - crls: SIGNED_DATA_CRLS - } - }).valueBlock.value - }), - new Set({ - value: [ - new Repeated({ - name: (names.signerInfos || SIGNED_DATA_SIGNER_INFOS), - value: SignerInfo.schema() - }) - ] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$3); - const asn1 = compareSchema(schema, schema, SignedData.schema()); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result[SIGNED_DATA_VERSION].valueBlock.valueDec; - if (SIGNED_DATA_DIGEST_ALGORITHMS in asn1.result) - this.digestAlgorithms = Array.from(asn1.result[SIGNED_DATA_DIGEST_ALGORITHMS], algorithm => new AlgorithmIdentifier({ schema: algorithm })); - this.encapContentInfo = new EncapsulatedContentInfo({ schema: asn1.result[SIGNED_DATA_ENCAP_CONTENT_INFO] }); - if (SIGNED_DATA_CERTIFICATES in asn1.result) { - const certificateSet = new CertificateSet({ - schema: new Set({ - value: asn1.result[SIGNED_DATA_CERTIFICATES].valueBlock.value - }) - }); - this.certificates = certificateSet.certificates.slice(0); - } - if (SIGNED_DATA_CRLS in asn1.result) { - this.crls = Array.from(asn1.result[SIGNED_DATA_CRLS], (crl) => { - if (crl.idBlock.tagClass === 1) - return new CertificateRevocationList({ schema: crl }); - crl.idBlock.tagClass = 1; - crl.idBlock.tagNumber = 16; - return new OtherRevocationInfoFormat({ schema: crl }); - }); - } - if (SIGNED_DATA_SIGNER_INFOS in asn1.result) - this.signerInfos = Array.from(asn1.result[SIGNED_DATA_SIGNER_INFOS], signerInfoSchema => new SignerInfo({ schema: signerInfoSchema })); - } - toSchema(encodeFlag = false) { - const outputArray = []; - if ((this.certificates && this.certificates.length && this.certificates.some(o => o instanceof OtherCertificateFormat)) - || (this.crls && this.crls.length && this.crls.some(o => o instanceof OtherRevocationInfoFormat))) { - this.version = 5; - } - else if (this.certificates && this.certificates.length && this.certificates.some(o => o instanceof AttributeCertificateV2)) { - this.version = 4; - } - else if ((this.certificates && this.certificates.length && this.certificates.some(o => o instanceof AttributeCertificateV1)) - || this.signerInfos.some(o => o.version === 3) - || this.encapContentInfo.eContentType !== SignedData.ID_DATA) { - this.version = 3; - } - else { - this.version = 1; - } - outputArray.push(new Integer({ value: this.version })); - outputArray.push(new Set({ - value: Array.from(this.digestAlgorithms, algorithm => algorithm.toSchema()) - })); - outputArray.push(this.encapContentInfo.toSchema()); - if (this.certificates) { - const certificateSet = new CertificateSet({ certificates: this.certificates }); - const certificateSetSchema = certificateSet.toSchema(); - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: certificateSetSchema.valueBlock.value - })); - } - if (this.crls) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 1 - }, - value: Array.from(this.crls, crl => { - if (crl instanceof OtherRevocationInfoFormat) { - const crlSchema = crl.toSchema(); - crlSchema.idBlock.tagClass = 3; - crlSchema.idBlock.tagNumber = 1; - return crlSchema; - } - return crl.toSchema(encodeFlag); - }) - })); - } - outputArray.push(new Set({ - value: Array.from(this.signerInfos, signerInfo => signerInfo.toSchema()) - })); - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - version: this.version, - digestAlgorithms: Array.from(this.digestAlgorithms, algorithm => algorithm.toJSON()), - encapContentInfo: this.encapContentInfo.toJSON(), - signerInfos: Array.from(this.signerInfos, signerInfo => signerInfo.toJSON()), - }; - if (this.certificates) { - res.certificates = Array.from(this.certificates, certificate => certificate.toJSON()); - } - if (this.crls) { - res.crls = Array.from(this.crls, crl => crl.toJSON()); - } - return res; - } - verify({ signer = (-1), data = (EMPTY_BUFFER), trustedCerts = [], checkDate = (new Date()), checkChain = false, passedWhenNotRevValues = false, extendedMode = false, findOrigin = null, findIssuer = null } = {}, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - let signerCert = null; - let timestampSerial = null; - try { - let messageDigestValue = EMPTY_BUFFER; - let shaAlgorithm = EMPTY_STRING; - let certificatePath = []; - const signerInfo = this.signerInfos[signer]; - if (!signerInfo) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 1, - message: "Unable to get signer by supplied index", - }); - } - if (!this.certificates) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 2, - message: "No certificates attached to this signed data", - }); - } - if (signerInfo.sid instanceof IssuerAndSerialNumber) { - for (const certificate of this.certificates) { - if (!(certificate instanceof Certificate)) - continue; - if ((certificate.issuer.isEqual(signerInfo.sid.issuer)) && - (certificate.serialNumber.isEqual(signerInfo.sid.serialNumber))) { - signerCert = certificate; - break; - } - } - } - else { - const sid = signerInfo.sid; - const keyId = sid.idBlock.isConstructed - ? sid.valueBlock.value[0].valueBlock.valueHex - : sid.valueBlock.valueHex; - for (const certificate of this.certificates) { - if (!(certificate instanceof Certificate)) { - continue; - } - const digest = yield crypto.digest({ name: "sha-1" }, certificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); - if (isEqualBuffer(digest, keyId)) { - signerCert = certificate; - break; - } - } - } - if (!signerCert) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 3, - message: "Unable to find signer certificate", - }); - } - if (this.encapContentInfo.eContentType === id_eContentType_TSTInfo) { - if (!this.encapContentInfo.eContent) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 15, - message: "Error during verification: TSTInfo eContent is empty", - signatureVerified: null, - signerCertificate: signerCert, - timestampSerial, - signerCertificateVerified: true - }); - } - let tstInfo; - try { - tstInfo = TSTInfo.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView); - } - catch (ex) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 15, - message: "Error during verification: TSTInfo wrong ASN.1 schema ", - signatureVerified: null, - signerCertificate: signerCert, - timestampSerial, - signerCertificateVerified: true - }); - } - checkDate = tstInfo.genTime; - timestampSerial = tstInfo.serialNumber.valueBlock.valueHexView.slice(); - if (data.byteLength === 0) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 4, - message: "Missed detached data input array", - }); - } - if (!(yield tstInfo.verify({ data }, crypto))) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 15, - message: "Error during verification: TSTInfo verification is failed", - signatureVerified: false, - signerCertificate: signerCert, - timestampSerial, - signerCertificateVerified: true - }); - } - } - if (checkChain) { - const certs = this.certificates.filter(certificate => (certificate instanceof Certificate && !!checkCA(certificate, signerCert))); - const chainParams = { - checkDate, - certs, - trustedCerts, - }; - if (findIssuer) { - chainParams.findIssuer = findIssuer; - } - if (findOrigin) { - chainParams.findOrigin = findOrigin; - } - const chainEngine = new CertificateChainValidationEngine(chainParams); - chainEngine.certs.push(signerCert); - if (this.crls) { - for (const crl of this.crls) { - if ("thisUpdate" in crl) - chainEngine.crls.push(crl); - else { - if (crl.otherRevInfoFormat === id_PKIX_OCSP_Basic) - chainEngine.ocsps.push(new BasicOCSPResponse({ schema: crl.otherRevInfo })); - } - } - } - if (this.ocsps) { - chainEngine.ocsps.push(...(this.ocsps)); - } - const verificationResult = yield chainEngine.verify({ passedWhenNotRevValues }, crypto) - .catch(e => { - throw new SignedDataVerifyError({ - date: checkDate, - code: 5, - message: `Validation of signer's certificate failed with error: ${((e instanceof Object) ? e.resultMessage : e)}`, - signerCertificate: signerCert, - signerCertificateVerified: false - }); - }); - if (verificationResult.certificatePath) { - certificatePath = verificationResult.certificatePath; - } - if (!verificationResult.result) - throw new SignedDataVerifyError({ - date: checkDate, - code: 5, - message: `Validation of signer's certificate failed: ${verificationResult.resultMessage}`, - signerCertificate: signerCert, - signerCertificateVerified: false - }); - } - const signerInfoHashAlgorithm = crypto.getAlgorithmByOID(signerInfo.digestAlgorithm.algorithmId); - if (!("name" in signerInfoHashAlgorithm)) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 7, - message: `Unsupported signature algorithm: ${signerInfo.digestAlgorithm.algorithmId}`, - signerCertificate: signerCert, - signerCertificateVerified: true - }); - } - shaAlgorithm = signerInfoHashAlgorithm.name; - const eContent = this.encapContentInfo.eContent; - if (eContent) { - if ((eContent.idBlock.tagClass === 1) && - (eContent.idBlock.tagNumber === 4)) { - data = eContent.getValue(); - } - else - data = eContent.valueBlock.valueBeforeDecodeView; - } - else { - if (data.byteLength === 0) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 8, - message: "Missed detached data input array", - signerCertificate: signerCert, - signerCertificateVerified: true - }); - } - } - if (signerInfo.signedAttrs) { - let foundContentType = false; - let foundMessageDigest = false; - for (const attribute of signerInfo.signedAttrs.attributes) { - if (attribute.type === "1.2.840.113549.1.9.3") - foundContentType = true; - if (attribute.type === "1.2.840.113549.1.9.4") { - foundMessageDigest = true; - messageDigestValue = attribute.values[0].valueBlock.valueHex; - } - if (foundContentType && foundMessageDigest) - break; - } - if (foundContentType === false) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 9, - message: "Attribute \"content-type\" is a mandatory attribute for \"signed attributes\"", - signerCertificate: signerCert, - signerCertificateVerified: true - }); - } - if (foundMessageDigest === false) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 10, - message: "Attribute \"message-digest\" is a mandatory attribute for \"signed attributes\"", - signatureVerified: null, - signerCertificate: signerCert, - signerCertificateVerified: true - }); - } - } - if (signerInfo.signedAttrs) { - const messageDigest = yield crypto.digest(shaAlgorithm, new Uint8Array(data)); - if (!isEqualBuffer(messageDigest, messageDigestValue)) { - throw new SignedDataVerifyError({ - date: checkDate, - code: 15, - message: "Error during verification: Message digest doesn't match", - signatureVerified: null, - signerCertificate: signerCert, - timestampSerial, - signerCertificateVerified: true - }); - } - data = signerInfo.signedAttrs.encodedValue; - } - const verifyResult = yield crypto.verifyWithPublicKey(data, signerInfo.signature, signerCert.subjectPublicKeyInfo, signerCert.signatureAlgorithm, shaAlgorithm); - if (extendedMode) { - return { - date: checkDate, - code: 14, - message: EMPTY_STRING, - signatureVerified: verifyResult, - signerCertificate: signerCert, - timestampSerial, - signerCertificateVerified: true, - certificatePath - }; - } - else { - return verifyResult; - } - } - catch (e) { - if (e instanceof SignedDataVerifyError) { - throw e; - } - throw new SignedDataVerifyError({ - date: checkDate, - code: 15, - message: `Error during verification: ${e instanceof Error ? e.message : e}`, - signatureVerified: null, - signerCertificate: signerCert, - timestampSerial, - signerCertificateVerified: true - }); - } - }); - } - sign(privateKey, signerIndex, hashAlgorithm = "SHA-1", data = (EMPTY_BUFFER), crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - if (!privateKey) - throw new Error("Need to provide a private key for signing"); - const hashAlgorithmOID = crypto.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); - if ((this.digestAlgorithms.filter(algorithm => algorithm.algorithmId === hashAlgorithmOID)).length === 0) { - this.digestAlgorithms.push(new AlgorithmIdentifier({ - algorithmId: hashAlgorithmOID, - algorithmParams: new Null() - })); - } - const signerInfo = this.signerInfos[signerIndex]; - if (!signerInfo) { - throw new RangeError("SignerInfo index is out of range"); - } - signerInfo.digestAlgorithm = new AlgorithmIdentifier({ - algorithmId: hashAlgorithmOID, - algorithmParams: new Null() - }); - const signatureParams = yield crypto.getSignatureParameters(privateKey, hashAlgorithm); - const parameters = signatureParams.parameters; - signerInfo.signatureAlgorithm = signatureParams.signatureAlgorithm; - if (signerInfo.signedAttrs) { - if (signerInfo.signedAttrs.encodedValue.byteLength !== 0) - data = signerInfo.signedAttrs.encodedValue; - else { - data = signerInfo.signedAttrs.toSchema().toBER(); - const view = BufferSourceConverter.toUint8Array(data); - view[0] = 0x31; - } - } - else { - const eContent = this.encapContentInfo.eContent; - if (eContent) { - if ((eContent.idBlock.tagClass === 1) && - (eContent.idBlock.tagNumber === 4)) { - data = eContent.getValue(); - } - else - data = eContent.valueBlock.valueBeforeDecodeView; - } - else { - if (data.byteLength === 0) - throw new Error("Missed detached data input array"); - } - } - const signature = yield crypto.signWithPrivateKey(data, privateKey, parameters); - signerInfo.signature = new OctetString({ valueHex: signature }); - }); - } -} -SignedData.CLASS_NAME = "SignedData"; +const VERSION$2 = "version"; +const DIGEST_ALGORITHMS = "digestAlgorithms"; +const ENCAP_CONTENT_INFO = "encapContentInfo"; +const CERTIFICATES = "certificates"; +const CRLS = "crls"; +const SIGNER_INFOS = "signerInfos"; +const OCSPS = "ocsps"; +const SIGNED_DATA = "SignedData"; +const SIGNED_DATA_VERSION = `${SIGNED_DATA}.${VERSION$2}`; +const SIGNED_DATA_DIGEST_ALGORITHMS = `${SIGNED_DATA}.${DIGEST_ALGORITHMS}`; +const SIGNED_DATA_ENCAP_CONTENT_INFO = `${SIGNED_DATA}.${ENCAP_CONTENT_INFO}`; +const SIGNED_DATA_CERTIFICATES = `${SIGNED_DATA}.${CERTIFICATES}`; +const SIGNED_DATA_CRLS = `${SIGNED_DATA}.${CRLS}`; +const SIGNED_DATA_SIGNER_INFOS = `${SIGNED_DATA}.${SIGNER_INFOS}`; +const CLEAR_PROPS$3 = [ + SIGNED_DATA_VERSION, + SIGNED_DATA_DIGEST_ALGORITHMS, + SIGNED_DATA_ENCAP_CONTENT_INFO, + SIGNED_DATA_CERTIFICATES, + SIGNED_DATA_CRLS, + SIGNED_DATA_SIGNER_INFOS +]; +class SignedDataVerifyError extends Error { + constructor({ message, code = 0, date = new Date(), signatureVerified = null, signerCertificate = null, signerCertificateVerified = null, timestampSerial = null, certificatePath = [], }) { + super(message); + this.name = "SignedDataVerifyError"; + this.date = date; + this.code = code; + this.timestampSerial = timestampSerial; + this.signatureVerified = signatureVerified; + this.signerCertificate = signerCertificate; + this.signerCertificateVerified = signerCertificateVerified; + this.certificatePath = certificatePath; + } +} +class SignedData extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$2, SignedData.defaultValues(VERSION$2)); + this.digestAlgorithms = getParametersValue(parameters, DIGEST_ALGORITHMS, SignedData.defaultValues(DIGEST_ALGORITHMS)); + this.encapContentInfo = getParametersValue(parameters, ENCAP_CONTENT_INFO, SignedData.defaultValues(ENCAP_CONTENT_INFO)); + if (CERTIFICATES in parameters) { + this.certificates = getParametersValue(parameters, CERTIFICATES, SignedData.defaultValues(CERTIFICATES)); + } + if (CRLS in parameters) { + this.crls = getParametersValue(parameters, CRLS, SignedData.defaultValues(CRLS)); + } + if (OCSPS in parameters) { + this.ocsps = getParametersValue(parameters, OCSPS, SignedData.defaultValues(OCSPS)); + } + this.signerInfos = getParametersValue(parameters, SIGNER_INFOS, SignedData.defaultValues(SIGNER_INFOS)); + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$2: + return 0; + case DIGEST_ALGORITHMS: + return []; + case ENCAP_CONTENT_INFO: + return new EncapsulatedContentInfo(); + case CERTIFICATES: + return []; + case CRLS: + return []; + case OCSPS: + return []; + case SIGNER_INFOS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$2: + return (memberValue === SignedData.defaultValues(VERSION$2)); + case ENCAP_CONTENT_INFO: + return EncapsulatedContentInfo.compareWithDefault("eContentType", memberValue.eContentType) && + EncapsulatedContentInfo.compareWithDefault("eContent", memberValue.eContent); + case DIGEST_ALGORITHMS: + case CERTIFICATES: + case CRLS: + case OCSPS: + case SIGNER_INFOS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + if (names.optional === undefined) { + names.optional = false; + } + return (new Sequence({ + name: (names.blockName || SIGNED_DATA), + optional: names.optional, + value: [ + new Integer({ name: (names.version || SIGNED_DATA_VERSION) }), + new Set({ + value: [ + new Repeated({ + name: (names.digestAlgorithms || SIGNED_DATA_DIGEST_ALGORITHMS), + value: AlgorithmIdentifier.schema() + }) + ] + }), + EncapsulatedContentInfo.schema(names.encapContentInfo || { + names: { + blockName: SIGNED_DATA_ENCAP_CONTENT_INFO + } + }), + new Constructed({ + name: (names.certificates || SIGNED_DATA_CERTIFICATES), + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: CertificateSet.schema().valueBlock.value + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: RevocationInfoChoices.schema(names.crls || { + names: { + crls: SIGNED_DATA_CRLS + } + }).valueBlock.value + }), + new Set({ + value: [ + new Repeated({ + name: (names.signerInfos || SIGNED_DATA_SIGNER_INFOS), + value: SignerInfo.schema() + }) + ] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$3); + const asn1 = compareSchema(schema, schema, SignedData.schema()); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result[SIGNED_DATA_VERSION].valueBlock.valueDec; + if (SIGNED_DATA_DIGEST_ALGORITHMS in asn1.result) + this.digestAlgorithms = Array.from(asn1.result[SIGNED_DATA_DIGEST_ALGORITHMS], algorithm => new AlgorithmIdentifier({ schema: algorithm })); + this.encapContentInfo = new EncapsulatedContentInfo({ schema: asn1.result[SIGNED_DATA_ENCAP_CONTENT_INFO] }); + if (SIGNED_DATA_CERTIFICATES in asn1.result) { + const certificateSet = new CertificateSet({ + schema: new Set({ + value: asn1.result[SIGNED_DATA_CERTIFICATES].valueBlock.value + }) + }); + this.certificates = certificateSet.certificates.slice(0); + } + if (SIGNED_DATA_CRLS in asn1.result) { + this.crls = Array.from(asn1.result[SIGNED_DATA_CRLS], (crl) => { + if (crl.idBlock.tagClass === 1) + return new CertificateRevocationList({ schema: crl }); + crl.idBlock.tagClass = 1; + crl.idBlock.tagNumber = 16; + return new OtherRevocationInfoFormat({ schema: crl }); + }); + } + if (SIGNED_DATA_SIGNER_INFOS in asn1.result) + this.signerInfos = Array.from(asn1.result[SIGNED_DATA_SIGNER_INFOS], signerInfoSchema => new SignerInfo({ schema: signerInfoSchema })); + } + toSchema(encodeFlag = false) { + const outputArray = []; + if ((this.certificates && this.certificates.length && this.certificates.some(o => o instanceof OtherCertificateFormat)) + || (this.crls && this.crls.length && this.crls.some(o => o instanceof OtherRevocationInfoFormat))) { + this.version = 5; + } + else if (this.certificates && this.certificates.length && this.certificates.some(o => o instanceof AttributeCertificateV2)) { + this.version = 4; + } + else if ((this.certificates && this.certificates.length && this.certificates.some(o => o instanceof AttributeCertificateV1)) + || this.signerInfos.some(o => o.version === 3) + || this.encapContentInfo.eContentType !== SignedData.ID_DATA) { + this.version = 3; + } + else { + this.version = 1; + } + outputArray.push(new Integer({ value: this.version })); + outputArray.push(new Set({ + value: Array.from(this.digestAlgorithms, algorithm => algorithm.toSchema()) + })); + outputArray.push(this.encapContentInfo.toSchema()); + if (this.certificates) { + const certificateSet = new CertificateSet({ certificates: this.certificates }); + const certificateSetSchema = certificateSet.toSchema(); + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: certificateSetSchema.valueBlock.value + })); + } + if (this.crls) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 1 + }, + value: Array.from(this.crls, crl => { + if (crl instanceof OtherRevocationInfoFormat) { + const crlSchema = crl.toSchema(); + crlSchema.idBlock.tagClass = 3; + crlSchema.idBlock.tagNumber = 1; + return crlSchema; + } + return crl.toSchema(encodeFlag); + }) + })); + } + outputArray.push(new Set({ + value: Array.from(this.signerInfos, signerInfo => signerInfo.toSchema()) + })); + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + version: this.version, + digestAlgorithms: Array.from(this.digestAlgorithms, algorithm => algorithm.toJSON()), + encapContentInfo: this.encapContentInfo.toJSON(), + signerInfos: Array.from(this.signerInfos, signerInfo => signerInfo.toJSON()), + }; + if (this.certificates) { + res.certificates = Array.from(this.certificates, certificate => certificate.toJSON()); + } + if (this.crls) { + res.crls = Array.from(this.crls, crl => crl.toJSON()); + } + return res; + } + async verify({ signer = (-1), data = (EMPTY_BUFFER), trustedCerts = [], checkDate = (new Date()), checkChain = false, passedWhenNotRevValues = false, extendedMode = false, findOrigin = null, findIssuer = null } = {}, crypto = getCrypto(true)) { + let signerCert = null; + let timestampSerial = null; + try { + let messageDigestValue = EMPTY_BUFFER; + let shaAlgorithm = EMPTY_STRING; + let certificatePath = []; + const signerInfo = this.signerInfos[signer]; + if (!signerInfo) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 1, + message: "Unable to get signer by supplied index", + }); + } + if (!this.certificates) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 2, + message: "No certificates attached to this signed data", + }); + } + if (signerInfo.sid instanceof IssuerAndSerialNumber) { + for (const certificate of this.certificates) { + if (!(certificate instanceof Certificate)) + continue; + if ((certificate.issuer.isEqual(signerInfo.sid.issuer)) && + (certificate.serialNumber.isEqual(signerInfo.sid.serialNumber))) { + signerCert = certificate; + break; + } + } + } + else { + const sid = signerInfo.sid; + const keyId = sid.idBlock.isConstructed + ? sid.valueBlock.value[0].valueBlock.valueHex + : sid.valueBlock.valueHex; + for (const certificate of this.certificates) { + if (!(certificate instanceof Certificate)) { + continue; + } + const digest = await crypto.digest({ name: "sha-1" }, certificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView); + if (isEqualBuffer(digest, keyId)) { + signerCert = certificate; + break; + } + } + } + if (!signerCert) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 3, + message: "Unable to find signer certificate", + }); + } + if (this.encapContentInfo.eContentType === id_eContentType_TSTInfo) { + if (!this.encapContentInfo.eContent) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 15, + message: "Error during verification: TSTInfo eContent is empty", + signatureVerified: null, + signerCertificate: signerCert, + timestampSerial, + signerCertificateVerified: true + }); + } + let tstInfo; + try { + tstInfo = TSTInfo.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView); + } + catch { + throw new SignedDataVerifyError({ + date: checkDate, + code: 15, + message: "Error during verification: TSTInfo wrong ASN.1 schema ", + signatureVerified: null, + signerCertificate: signerCert, + timestampSerial, + signerCertificateVerified: true + }); + } + checkDate = tstInfo.genTime; + timestampSerial = tstInfo.serialNumber.valueBlock.valueHexView.slice().buffer; + if (data.byteLength === 0) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 4, + message: "Missed detached data input array", + }); + } + if (!(await tstInfo.verify({ data }, crypto))) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 15, + message: "Error during verification: TSTInfo verification is failed", + signatureVerified: false, + signerCertificate: signerCert, + timestampSerial, + signerCertificateVerified: true + }); + } + } + if (checkChain) { + const certs = this.certificates.filter(certificate => (certificate instanceof Certificate && !!checkCA(certificate, signerCert))); + const chainParams = { + checkDate, + certs, + trustedCerts, + }; + if (findIssuer) { + chainParams.findIssuer = findIssuer; + } + if (findOrigin) { + chainParams.findOrigin = findOrigin; + } + const chainEngine = new CertificateChainValidationEngine(chainParams); + chainEngine.certs.push(signerCert); + if (this.crls) { + for (const crl of this.crls) { + if ("thisUpdate" in crl) + chainEngine.crls.push(crl); + else { + if (crl.otherRevInfoFormat === id_PKIX_OCSP_Basic) + chainEngine.ocsps.push(new BasicOCSPResponse({ schema: crl.otherRevInfo })); + } + } + } + if (this.ocsps) { + chainEngine.ocsps.push(...(this.ocsps)); + } + const verificationResult = await chainEngine.verify({ passedWhenNotRevValues }, crypto) + .catch(e => { + throw new SignedDataVerifyError({ + date: checkDate, + code: 5, + message: `Validation of signer's certificate failed with error: ${((e instanceof Object) ? e.resultMessage : e)}`, + signerCertificate: signerCert, + signerCertificateVerified: false + }); + }); + if (verificationResult.certificatePath) { + certificatePath = verificationResult.certificatePath; + } + if (!verificationResult.result) + throw new SignedDataVerifyError({ + date: checkDate, + code: 5, + message: `Validation of signer's certificate failed: ${verificationResult.resultMessage}`, + signerCertificate: signerCert, + signerCertificateVerified: false + }); + } + const signerInfoHashAlgorithm = crypto.getAlgorithmByOID(signerInfo.digestAlgorithm.algorithmId); + if (!("name" in signerInfoHashAlgorithm)) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 7, + message: `Unsupported signature algorithm: ${signerInfo.digestAlgorithm.algorithmId}`, + signerCertificate: signerCert, + signerCertificateVerified: true + }); + } + shaAlgorithm = signerInfoHashAlgorithm.name; + const eContent = this.encapContentInfo.eContent; + if (eContent) { + if ((eContent.idBlock.tagClass === 1) && + (eContent.idBlock.tagNumber === 4)) { + data = eContent.getValue(); + } + else + data = eContent.valueBlock.valueBeforeDecodeView.slice().buffer; + } + else { + if (data.byteLength === 0) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 8, + message: "Missed detached data input array", + signerCertificate: signerCert, + signerCertificateVerified: true + }); + } + } + if (signerInfo.signedAttrs) { + let foundContentType = false; + let foundMessageDigest = false; + for (const attribute of signerInfo.signedAttrs.attributes) { + if (attribute.type === "1.2.840.113549.1.9.3") + foundContentType = true; + if (attribute.type === "1.2.840.113549.1.9.4") { + foundMessageDigest = true; + messageDigestValue = attribute.values[0].valueBlock.valueHex; + } + if (foundContentType && foundMessageDigest) + break; + } + if (foundContentType === false) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 9, + message: "Attribute \"content-type\" is a mandatory attribute for \"signed attributes\"", + signerCertificate: signerCert, + signerCertificateVerified: true + }); + } + if (foundMessageDigest === false) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 10, + message: "Attribute \"message-digest\" is a mandatory attribute for \"signed attributes\"", + signatureVerified: null, + signerCertificate: signerCert, + signerCertificateVerified: true + }); + } + } + if (signerInfo.signedAttrs) { + const messageDigest = await crypto.digest(shaAlgorithm, new Uint8Array(data)); + if (!isEqualBuffer(messageDigest, messageDigestValue)) { + throw new SignedDataVerifyError({ + date: checkDate, + code: 15, + message: "Error during verification: Message digest doesn't match", + signatureVerified: null, + signerCertificate: signerCert, + timestampSerial, + signerCertificateVerified: true + }); + } + data = signerInfo.signedAttrs.encodedValue; + } + const verifyResult = signerInfo.signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.1" + ? await crypto.verifyWithPublicKey(data, signerInfo.signature, signerCert.subjectPublicKeyInfo, signerInfo.signatureAlgorithm, shaAlgorithm) + : await crypto.verifyWithPublicKey(data, signerInfo.signature, signerCert.subjectPublicKeyInfo, signerInfo.signatureAlgorithm); + if (extendedMode) { + return { + date: checkDate, + code: 14, + message: EMPTY_STRING, + signatureVerified: verifyResult, + signerCertificate: signerCert, + timestampSerial, + signerCertificateVerified: true, + certificatePath + }; + } + else { + return verifyResult; + } + } + catch (e) { + if (e instanceof SignedDataVerifyError) { + throw e; + } + throw new SignedDataVerifyError({ + date: checkDate, + code: 15, + message: `Error during verification: ${e instanceof Error ? e.message : e}`, + signatureVerified: null, + signerCertificate: signerCert, + timestampSerial, + signerCertificateVerified: true + }); + } + } + async sign(privateKey, signerIndex, hashAlgorithm = "SHA-1", data = (EMPTY_BUFFER), crypto = getCrypto(true)) { + var _a; + if (!privateKey) + throw new Error("Need to provide a private key for signing"); + const signerInfo = this.signerInfos[signerIndex]; + if (!signerInfo) { + throw new RangeError("SignerInfo index is out of range"); + } + if (!((_a = signerInfo.signedAttrs) === null || _a === void 0 ? void 0 : _a.attributes.length) && "hash" in privateKey.algorithm && "hash" in privateKey.algorithm && privateKey.algorithm.hash) { + hashAlgorithm = privateKey.algorithm.hash.name; + } + const hashAlgorithmOID = crypto.getOIDByAlgorithm({ name: hashAlgorithm }, true, "hashAlgorithm"); + if ((this.digestAlgorithms.filter(algorithm => algorithm.algorithmId === hashAlgorithmOID)).length === 0) { + this.digestAlgorithms.push(new AlgorithmIdentifier({ + algorithmId: hashAlgorithmOID, + algorithmParams: new Null() + })); + } + signerInfo.digestAlgorithm = new AlgorithmIdentifier({ + algorithmId: hashAlgorithmOID, + algorithmParams: new Null() + }); + const signatureParams = await crypto.getSignatureParameters(privateKey, hashAlgorithm); + const parameters = signatureParams.parameters; + signerInfo.signatureAlgorithm = signatureParams.signatureAlgorithm; + if (signerInfo.signedAttrs) { + if (signerInfo.signedAttrs.encodedValue.byteLength !== 0) + data = signerInfo.signedAttrs.encodedValue; + else { + data = signerInfo.signedAttrs.toSchema().toBER(); + const view = BufferSourceConverter.toUint8Array(data); + view[0] = 0x31; + } + } + else { + const eContent = this.encapContentInfo.eContent; + if (eContent) { + if ((eContent.idBlock.tagClass === 1) && + (eContent.idBlock.tagNumber === 4)) { + data = eContent.getValue(); + } + else + data = eContent.valueBlock.valueBeforeDecodeView.slice().buffer; + } + else { + if (data.byteLength === 0) + throw new Error("Missed detached data input array"); + } + } + const signature = await crypto.signWithPrivateKey(data, privateKey, parameters); + signerInfo.signature = new OctetString({ valueHex: signature }); + } +} +SignedData.CLASS_NAME = "SignedData"; SignedData.ID_DATA = id_ContentType_Data; -const VERSION$1 = "version"; -const AUTH_SAFE = "authSafe"; -const MAC_DATA = "macData"; -const PARSED_VALUE = "parsedValue"; -const CLERA_PROPS = [ - VERSION$1, - AUTH_SAFE, - MAC_DATA -]; -class PFX extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION$1, PFX.defaultValues(VERSION$1)); - this.authSafe = getParametersValue(parameters, AUTH_SAFE, PFX.defaultValues(AUTH_SAFE)); - if (MAC_DATA in parameters) { - this.macData = getParametersValue(parameters, MAC_DATA, PFX.defaultValues(MAC_DATA)); - } - if (PARSED_VALUE in parameters) { - this.parsedValue = getParametersValue(parameters, PARSED_VALUE, PFX.defaultValues(PARSED_VALUE)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION$1: - return 3; - case AUTH_SAFE: - return (new ContentInfo()); - case MAC_DATA: - return (new MacData()); - case PARSED_VALUE: - return {}; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION$1: - return (memberValue === PFX.defaultValues(memberName)); - case AUTH_SAFE: - return ((ContentInfo.compareWithDefault("contentType", memberValue.contentType)) && - (ContentInfo.compareWithDefault("content", memberValue.content))); - case MAC_DATA: - return ((MacData.compareWithDefault("mac", memberValue.mac)) && - (MacData.compareWithDefault("macSalt", memberValue.macSalt)) && - (MacData.compareWithDefault("iterations", memberValue.iterations))); - case PARSED_VALUE: - return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.version || VERSION$1) }), - ContentInfo.schema(names.authSafe || { - names: { - blockName: AUTH_SAFE - } - }), - MacData.schema(names.macData || { - names: { - blockName: MAC_DATA, - optional: true - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLERA_PROPS); - const asn1 = compareSchema(schema, schema, PFX.schema({ - names: { - version: VERSION$1, - authSafe: { - names: { - blockName: AUTH_SAFE - } - }, - macData: { - names: { - blockName: MAC_DATA - } - } - } - })); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result.version.valueBlock.valueDec; - this.authSafe = new ContentInfo({ schema: asn1.result.authSafe }); - if (MAC_DATA in asn1.result) - this.macData = new MacData({ schema: asn1.result.macData }); - } - toSchema() { - const outputArray = [ - new Integer({ value: this.version }), - this.authSafe.toSchema() - ]; - if (this.macData) { - outputArray.push(this.macData.toSchema()); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const output = { - version: this.version, - authSafe: this.authSafe.toJSON() - }; - if (this.macData) { - output.macData = this.macData.toJSON(); - } - return output; - } - makeInternalValues(parameters = {}, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - ArgumentError.assert(parameters, "parameters", "object"); - if (!this.parsedValue) { - throw new Error("Please call \"parseValues\" function first in order to make \"parsedValue\" data"); - } - ParameterError.assertEmpty(this.parsedValue.integrityMode, "integrityMode", "parsedValue"); - ParameterError.assertEmpty(this.parsedValue.authenticatedSafe, "authenticatedSafe", "parsedValue"); - switch (this.parsedValue.integrityMode) { - case 0: - { - if (!("iterations" in parameters)) - throw new ParameterError("iterations"); - ParameterError.assertEmpty(parameters.pbkdf2HashAlgorithm, "pbkdf2HashAlgorithm"); - ParameterError.assertEmpty(parameters.hmacHashAlgorithm, "hmacHashAlgorithm"); - ParameterError.assertEmpty(parameters.password, "password"); - const saltBuffer = new ArrayBuffer(64); - const saltView = new Uint8Array(saltBuffer); - crypto.getRandomValues(saltView); - const data = this.parsedValue.authenticatedSafe.toSchema().toBER(false); - this.authSafe = new ContentInfo({ - contentType: ContentInfo.DATA, - content: new OctetString({ valueHex: data }) - }); - const result = yield crypto.stampDataWithPassword({ - password: parameters.password, - hashAlgorithm: parameters.hmacHashAlgorithm, - salt: saltBuffer, - iterationCount: parameters.iterations, - contentToStamp: data - }); - this.macData = new MacData({ - mac: new DigestInfo({ - digestAlgorithm: new AlgorithmIdentifier({ - algorithmId: crypto.getOIDByAlgorithm({ name: parameters.hmacHashAlgorithm }, true, "hmacHashAlgorithm"), - }), - digest: new OctetString({ valueHex: result }) - }), - macSalt: new OctetString({ valueHex: saltBuffer }), - iterations: parameters.iterations - }); - } - break; - case 1: - { - if (!("signingCertificate" in parameters)) { - throw new ParameterError("signingCertificate"); - } - ParameterError.assertEmpty(parameters.privateKey, "privateKey"); - ParameterError.assertEmpty(parameters.hashAlgorithm, "hashAlgorithm"); - const toBeSigned = this.parsedValue.authenticatedSafe.toSchema().toBER(false); - const cmsSigned = new SignedData({ - version: 1, - encapContentInfo: new EncapsulatedContentInfo({ - eContentType: "1.2.840.113549.1.7.1", - eContent: new OctetString({ valueHex: toBeSigned }) - }), - certificates: [parameters.signingCertificate] - }); - const result = yield crypto.digest({ name: parameters.hashAlgorithm }, new Uint8Array(toBeSigned)); - const signedAttr = []; - signedAttr.push(new Attribute({ - type: "1.2.840.113549.1.9.3", - values: [ - new ObjectIdentifier({ value: "1.2.840.113549.1.7.1" }) - ] - })); - signedAttr.push(new Attribute({ - type: "1.2.840.113549.1.9.5", - values: [ - new UTCTime({ valueDate: new Date() }) - ] - })); - signedAttr.push(new Attribute({ - type: "1.2.840.113549.1.9.4", - values: [ - new OctetString({ valueHex: result }) - ] - })); - cmsSigned.signerInfos.push(new SignerInfo({ - version: 1, - sid: new IssuerAndSerialNumber({ - issuer: parameters.signingCertificate.issuer, - serialNumber: parameters.signingCertificate.serialNumber - }), - signedAttrs: new SignedAndUnsignedAttributes({ - type: 0, - attributes: signedAttr - }) - })); - yield cmsSigned.sign(parameters.privateKey, 0, parameters.hashAlgorithm, undefined, crypto); - this.authSafe = new ContentInfo({ - contentType: "1.2.840.113549.1.7.2", - content: cmsSigned.toSchema(true) - }); - } - break; - default: - throw new Error(`Parameter "integrityMode" has unknown value: ${this.parsedValue.integrityMode}`); - } - }); - } - parseInternalValues(parameters, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - ArgumentError.assert(parameters, "parameters", "object"); - if (parameters.checkIntegrity === undefined) { - parameters.checkIntegrity = true; - } - this.parsedValue = {}; - switch (this.authSafe.contentType) { - case ContentInfo.DATA: - { - ParameterError.assertEmpty(parameters.password, "password"); - this.parsedValue.integrityMode = 0; - ArgumentError.assert(this.authSafe.content, "authSafe.content", OctetString); - const authSafeContent = this.authSafe.content.getValue(); - this.parsedValue.authenticatedSafe = AuthenticatedSafe.fromBER(authSafeContent); - if (parameters.checkIntegrity) { - if (!this.macData) { - throw new Error("Absent \"macData\" value, can not check PKCS#12 data integrity"); - } - const hashAlgorithm = crypto.getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId, true, "digestAlgorithm"); - const result = yield crypto.verifyDataStampedWithPassword({ - password: parameters.password, - hashAlgorithm: hashAlgorithm.name, - salt: BufferSourceConverter.toArrayBuffer(this.macData.macSalt.valueBlock.valueHexView), - iterationCount: this.macData.iterations || 1, - contentToVerify: authSafeContent, - signatureToVerify: BufferSourceConverter.toArrayBuffer(this.macData.mac.digest.valueBlock.valueHexView), - }); - if (!result) { - throw new Error("Integrity for the PKCS#12 data is broken!"); - } - } - } - break; - case ContentInfo.SIGNED_DATA: - { - this.parsedValue.integrityMode = 1; - const cmsSigned = new SignedData({ schema: this.authSafe.content }); - const eContent = cmsSigned.encapContentInfo.eContent; - ParameterError.assert(eContent, "eContent", "cmsSigned.encapContentInfo"); - ArgumentError.assert(eContent, "eContent", OctetString); - const data = eContent.getValue(); - this.parsedValue.authenticatedSafe = AuthenticatedSafe.fromBER(data); - const ok = yield cmsSigned.verify({ signer: 0, checkChain: false }, crypto); - if (!ok) { - throw new Error("Integrity for the PKCS#12 data is broken!"); - } - } - break; - default: - throw new Error(`Incorrect value for "this.authSafe.contentType": ${this.authSafe.contentType}`); - } - }); - } -} +const VERSION$1 = "version"; +const AUTH_SAFE = "authSafe"; +const MAC_DATA = "macData"; +const PARSED_VALUE = "parsedValue"; +const CLERA_PROPS = [ + VERSION$1, + AUTH_SAFE, + MAC_DATA +]; +class PFX extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION$1, PFX.defaultValues(VERSION$1)); + this.authSafe = getParametersValue(parameters, AUTH_SAFE, PFX.defaultValues(AUTH_SAFE)); + if (MAC_DATA in parameters) { + this.macData = getParametersValue(parameters, MAC_DATA, PFX.defaultValues(MAC_DATA)); + } + if (PARSED_VALUE in parameters) { + this.parsedValue = getParametersValue(parameters, PARSED_VALUE, PFX.defaultValues(PARSED_VALUE)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION$1: + return 3; + case AUTH_SAFE: + return (new ContentInfo()); + case MAC_DATA: + return (new MacData()); + case PARSED_VALUE: + return {}; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION$1: + return (memberValue === PFX.defaultValues(memberName)); + case AUTH_SAFE: + return ((ContentInfo.compareWithDefault("contentType", memberValue.contentType)) && + (ContentInfo.compareWithDefault("content", memberValue.content))); + case MAC_DATA: + return ((MacData.compareWithDefault("mac", memberValue.mac)) && + (MacData.compareWithDefault("macSalt", memberValue.macSalt)) && + (MacData.compareWithDefault("iterations", memberValue.iterations))); + case PARSED_VALUE: + return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.version || VERSION$1) }), + ContentInfo.schema(names.authSafe || { + names: { + blockName: AUTH_SAFE + } + }), + MacData.schema(names.macData || { + names: { + blockName: MAC_DATA, + optional: true + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLERA_PROPS); + const asn1 = compareSchema(schema, schema, PFX.schema({ + names: { + version: VERSION$1, + authSafe: { + names: { + blockName: AUTH_SAFE + } + }, + macData: { + names: { + blockName: MAC_DATA + } + } + } + })); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result.version.valueBlock.valueDec; + this.authSafe = new ContentInfo({ schema: asn1.result.authSafe }); + if (MAC_DATA in asn1.result) + this.macData = new MacData({ schema: asn1.result.macData }); + } + toSchema() { + const outputArray = [ + new Integer({ value: this.version }), + this.authSafe.toSchema() + ]; + if (this.macData) { + outputArray.push(this.macData.toSchema()); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const output = { + version: this.version, + authSafe: this.authSafe.toJSON() + }; + if (this.macData) { + output.macData = this.macData.toJSON(); + } + return output; + } + async makeInternalValues(parameters = {}, crypto = getCrypto(true)) { + ArgumentError.assert(parameters, "parameters", "object"); + if (!this.parsedValue) { + throw new Error("Please call \"parseValues\" function first in order to make \"parsedValue\" data"); + } + ParameterError.assertEmpty(this.parsedValue.integrityMode, "integrityMode", "parsedValue"); + ParameterError.assertEmpty(this.parsedValue.authenticatedSafe, "authenticatedSafe", "parsedValue"); + switch (this.parsedValue.integrityMode) { + case 0: + { + if (!("iterations" in parameters)) + throw new ParameterError("iterations"); + ParameterError.assertEmpty(parameters.pbkdf2HashAlgorithm, "pbkdf2HashAlgorithm"); + ParameterError.assertEmpty(parameters.hmacHashAlgorithm, "hmacHashAlgorithm"); + ParameterError.assertEmpty(parameters.password, "password"); + const saltBuffer = new ArrayBuffer(64); + const saltView = new Uint8Array(saltBuffer); + crypto.getRandomValues(saltView); + const data = this.parsedValue.authenticatedSafe.toSchema().toBER(false); + this.authSafe = new ContentInfo({ + contentType: ContentInfo.DATA, + content: new OctetString({ valueHex: data }) + }); + const result = await crypto.stampDataWithPassword({ + password: parameters.password, + hashAlgorithm: parameters.hmacHashAlgorithm, + salt: saltBuffer, + iterationCount: parameters.iterations, + contentToStamp: data + }); + this.macData = new MacData({ + mac: new DigestInfo({ + digestAlgorithm: new AlgorithmIdentifier({ + algorithmId: crypto.getOIDByAlgorithm({ name: parameters.hmacHashAlgorithm }, true, "hmacHashAlgorithm"), + }), + digest: new OctetString({ valueHex: result }) + }), + macSalt: new OctetString({ valueHex: saltBuffer }), + iterations: parameters.iterations + }); + } + break; + case 1: + { + if (!("signingCertificate" in parameters)) { + throw new ParameterError("signingCertificate"); + } + ParameterError.assertEmpty(parameters.privateKey, "privateKey"); + ParameterError.assertEmpty(parameters.hashAlgorithm, "hashAlgorithm"); + const toBeSigned = this.parsedValue.authenticatedSafe.toSchema().toBER(false); + const cmsSigned = new SignedData({ + version: 1, + encapContentInfo: new EncapsulatedContentInfo({ + eContentType: "1.2.840.113549.1.7.1", + eContent: new OctetString({ valueHex: toBeSigned }) + }), + certificates: [parameters.signingCertificate] + }); + const result = await crypto.digest({ name: parameters.hashAlgorithm }, new Uint8Array(toBeSigned)); + const signedAttr = []; + signedAttr.push(new Attribute({ + type: "1.2.840.113549.1.9.3", + values: [ + new ObjectIdentifier({ value: "1.2.840.113549.1.7.1" }) + ] + })); + signedAttr.push(new Attribute({ + type: "1.2.840.113549.1.9.5", + values: [ + new UTCTime({ valueDate: new Date() }) + ] + })); + signedAttr.push(new Attribute({ + type: "1.2.840.113549.1.9.4", + values: [ + new OctetString({ valueHex: result }) + ] + })); + cmsSigned.signerInfos.push(new SignerInfo({ + version: 1, + sid: new IssuerAndSerialNumber({ + issuer: parameters.signingCertificate.issuer, + serialNumber: parameters.signingCertificate.serialNumber + }), + signedAttrs: new SignedAndUnsignedAttributes({ + type: 0, + attributes: signedAttr + }) + })); + await cmsSigned.sign(parameters.privateKey, 0, parameters.hashAlgorithm, undefined, crypto); + this.authSafe = new ContentInfo({ + contentType: "1.2.840.113549.1.7.2", + content: cmsSigned.toSchema(true) + }); + } + break; + default: + throw new Error(`Parameter "integrityMode" has unknown value: ${this.parsedValue.integrityMode}`); + } + } + async parseInternalValues(parameters, crypto = getCrypto(true)) { + ArgumentError.assert(parameters, "parameters", "object"); + if (parameters.checkIntegrity === undefined) { + parameters.checkIntegrity = true; + } + this.parsedValue = {}; + switch (this.authSafe.contentType) { + case ContentInfo.DATA: + { + ParameterError.assertEmpty(parameters.password, "password"); + this.parsedValue.integrityMode = 0; + ArgumentError.assert(this.authSafe.content, "authSafe.content", OctetString); + const authSafeContent = this.authSafe.content.getValue(); + this.parsedValue.authenticatedSafe = AuthenticatedSafe.fromBER(authSafeContent); + if (parameters.checkIntegrity) { + if (!this.macData) { + throw new Error("Absent \"macData\" value, can not check PKCS#12 data integrity"); + } + const hashAlgorithm = crypto.getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId, true, "digestAlgorithm"); + const result = await crypto.verifyDataStampedWithPassword({ + password: parameters.password, + hashAlgorithm: hashAlgorithm.name, + salt: BufferSourceConverter.toArrayBuffer(this.macData.macSalt.valueBlock.valueHexView), + iterationCount: this.macData.iterations || 1, + contentToVerify: authSafeContent, + signatureToVerify: BufferSourceConverter.toArrayBuffer(this.macData.mac.digest.valueBlock.valueHexView), + }); + if (!result) { + throw new Error("Integrity for the PKCS#12 data is broken!"); + } + } + } + break; + case ContentInfo.SIGNED_DATA: + { + this.parsedValue.integrityMode = 1; + const cmsSigned = new SignedData({ schema: this.authSafe.content }); + const eContent = cmsSigned.encapContentInfo.eContent; + ParameterError.assert(eContent, "eContent", "cmsSigned.encapContentInfo"); + ArgumentError.assert(eContent, "eContent", OctetString); + const data = eContent.getValue(); + this.parsedValue.authenticatedSafe = AuthenticatedSafe.fromBER(data); + const ok = await cmsSigned.verify({ signer: 0, checkChain: false }, crypto); + if (!ok) { + throw new Error("Integrity for the PKCS#12 data is broken!"); + } + } + break; + default: + throw new Error(`Incorrect value for "this.authSafe.contentType": ${this.authSafe.contentType}`); + } + } +} PFX.CLASS_NAME = "PFX"; -const STATUS$1 = "status"; -const STATUS_STRINGS = "statusStrings"; -const FAIL_INFO = "failInfo"; -const CLEAR_PROPS$2 = [ - STATUS$1, - STATUS_STRINGS, - FAIL_INFO -]; -var PKIStatus; -(function (PKIStatus) { - PKIStatus[PKIStatus["granted"] = 0] = "granted"; - PKIStatus[PKIStatus["grantedWithMods"] = 1] = "grantedWithMods"; - PKIStatus[PKIStatus["rejection"] = 2] = "rejection"; - PKIStatus[PKIStatus["waiting"] = 3] = "waiting"; - PKIStatus[PKIStatus["revocationWarning"] = 4] = "revocationWarning"; - PKIStatus[PKIStatus["revocationNotification"] = 5] = "revocationNotification"; -})(PKIStatus || (PKIStatus = {})); -class PKIStatusInfo extends PkiObject { - constructor(parameters = {}) { - super(); - this.status = getParametersValue(parameters, STATUS$1, PKIStatusInfo.defaultValues(STATUS$1)); - if (STATUS_STRINGS in parameters) { - this.statusStrings = getParametersValue(parameters, STATUS_STRINGS, PKIStatusInfo.defaultValues(STATUS_STRINGS)); - } - if (FAIL_INFO in parameters) { - this.failInfo = getParametersValue(parameters, FAIL_INFO, PKIStatusInfo.defaultValues(FAIL_INFO)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case STATUS$1: - return 2; - case STATUS_STRINGS: - return []; - case FAIL_INFO: - return new BitString(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case STATUS$1: - return (memberValue === PKIStatusInfo.defaultValues(memberName)); - case STATUS_STRINGS: - return (memberValue.length === 0); - case FAIL_INFO: - return (memberValue.isEqual(PKIStatusInfo.defaultValues(memberName))); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || EMPTY_STRING), - value: [ - new Integer({ name: (names.status || EMPTY_STRING) }), - new Sequence({ - optional: true, - value: [ - new Repeated({ - name: (names.statusStrings || EMPTY_STRING), - value: new Utf8String() - }) - ] - }), - new BitString({ - name: (names.failInfo || EMPTY_STRING), - optional: true - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$2); - const asn1 = compareSchema(schema, schema, PKIStatusInfo.schema({ - names: { - status: STATUS$1, - statusStrings: STATUS_STRINGS, - failInfo: FAIL_INFO - } - })); - AsnError.assertSchema(asn1, this.className); - const _status = asn1.result.status; - if ((_status.valueBlock.isHexOnly === true) || - (_status.valueBlock.valueDec < 0) || - (_status.valueBlock.valueDec > 5)) - throw new Error("PKIStatusInfo \"status\" has invalid value"); - this.status = _status.valueBlock.valueDec; - if (STATUS_STRINGS in asn1.result) - this.statusStrings = asn1.result.statusStrings; - if (FAIL_INFO in asn1.result) - this.failInfo = asn1.result.failInfo; - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.status })); - if (this.statusStrings) { - outputArray.push(new Sequence({ - optional: true, - value: this.statusStrings - })); - } - if (this.failInfo) { - outputArray.push(this.failInfo); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - status: this.status - }; - if (this.statusStrings) { - res.statusStrings = Array.from(this.statusStrings, o => o.toJSON()); - } - if (this.failInfo) { - res.failInfo = this.failInfo.toJSON(); - } - return res; - } -} +const STATUS$1 = "status"; +const STATUS_STRINGS = "statusStrings"; +const FAIL_INFO = "failInfo"; +const CLEAR_PROPS$2 = [ + STATUS$1, + STATUS_STRINGS, + FAIL_INFO +]; +var PKIStatus; +(function (PKIStatus) { + PKIStatus[PKIStatus["granted"] = 0] = "granted"; + PKIStatus[PKIStatus["grantedWithMods"] = 1] = "grantedWithMods"; + PKIStatus[PKIStatus["rejection"] = 2] = "rejection"; + PKIStatus[PKIStatus["waiting"] = 3] = "waiting"; + PKIStatus[PKIStatus["revocationWarning"] = 4] = "revocationWarning"; + PKIStatus[PKIStatus["revocationNotification"] = 5] = "revocationNotification"; +})(PKIStatus || (PKIStatus = {})); +class PKIStatusInfo extends PkiObject { + constructor(parameters = {}) { + super(); + this.status = getParametersValue(parameters, STATUS$1, PKIStatusInfo.defaultValues(STATUS$1)); + if (STATUS_STRINGS in parameters) { + this.statusStrings = getParametersValue(parameters, STATUS_STRINGS, PKIStatusInfo.defaultValues(STATUS_STRINGS)); + } + if (FAIL_INFO in parameters) { + this.failInfo = getParametersValue(parameters, FAIL_INFO, PKIStatusInfo.defaultValues(FAIL_INFO)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case STATUS$1: + return 2; + case STATUS_STRINGS: + return []; + case FAIL_INFO: + return new BitString(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case STATUS$1: + return (memberValue === PKIStatusInfo.defaultValues(memberName)); + case STATUS_STRINGS: + return (memberValue.length === 0); + case FAIL_INFO: + return (memberValue.isEqual(PKIStatusInfo.defaultValues(memberName))); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || EMPTY_STRING), + value: [ + new Integer({ name: (names.status || EMPTY_STRING) }), + new Sequence({ + optional: true, + value: [ + new Repeated({ + name: (names.statusStrings || EMPTY_STRING), + value: new Utf8String() + }) + ] + }), + new BitString({ + name: (names.failInfo || EMPTY_STRING), + optional: true + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$2); + const asn1 = compareSchema(schema, schema, PKIStatusInfo.schema({ + names: { + status: STATUS$1, + statusStrings: STATUS_STRINGS, + failInfo: FAIL_INFO + } + })); + AsnError.assertSchema(asn1, this.className); + const _status = asn1.result.status; + if ((_status.valueBlock.isHexOnly === true) || + (_status.valueBlock.valueDec < 0) || + (_status.valueBlock.valueDec > 5)) + throw new Error("PKIStatusInfo \"status\" has invalid value"); + this.status = _status.valueBlock.valueDec; + if (STATUS_STRINGS in asn1.result) + this.statusStrings = asn1.result.statusStrings; + if (FAIL_INFO in asn1.result) + this.failInfo = asn1.result.failInfo; + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.status })); + if (this.statusStrings) { + outputArray.push(new Sequence({ + optional: true, + value: this.statusStrings + })); + } + if (this.failInfo) { + outputArray.push(this.failInfo); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + status: this.status + }; + if (this.statusStrings) { + res.statusStrings = Array.from(this.statusStrings, o => o.toJSON()); + } + if (this.failInfo) { + res.failInfo = this.failInfo.toJSON(); + } + return res; + } +} PKIStatusInfo.CLASS_NAME = "PKIStatusInfo"; -const VERSION = "version"; -const MESSAGE_IMPRINT = "messageImprint"; -const REQ_POLICY = "reqPolicy"; -const NONCE = "nonce"; -const CERT_REQ = "certReq"; -const EXTENSIONS = "extensions"; -const TIME_STAMP_REQ = "TimeStampReq"; -const TIME_STAMP_REQ_VERSION = `${TIME_STAMP_REQ}.${VERSION}`; -const TIME_STAMP_REQ_MESSAGE_IMPRINT = `${TIME_STAMP_REQ}.${MESSAGE_IMPRINT}`; -const TIME_STAMP_REQ_POLICY = `${TIME_STAMP_REQ}.${REQ_POLICY}`; -const TIME_STAMP_REQ_NONCE = `${TIME_STAMP_REQ}.${NONCE}`; -const TIME_STAMP_REQ_CERT_REQ = `${TIME_STAMP_REQ}.${CERT_REQ}`; -const TIME_STAMP_REQ_EXTENSIONS = `${TIME_STAMP_REQ}.${EXTENSIONS}`; -const CLEAR_PROPS$1 = [ - TIME_STAMP_REQ_VERSION, - TIME_STAMP_REQ_MESSAGE_IMPRINT, - TIME_STAMP_REQ_POLICY, - TIME_STAMP_REQ_NONCE, - TIME_STAMP_REQ_CERT_REQ, - TIME_STAMP_REQ_EXTENSIONS, -]; -class TimeStampReq extends PkiObject { - constructor(parameters = {}) { - super(); - this.version = getParametersValue(parameters, VERSION, TimeStampReq.defaultValues(VERSION)); - this.messageImprint = getParametersValue(parameters, MESSAGE_IMPRINT, TimeStampReq.defaultValues(MESSAGE_IMPRINT)); - if (REQ_POLICY in parameters) { - this.reqPolicy = getParametersValue(parameters, REQ_POLICY, TimeStampReq.defaultValues(REQ_POLICY)); - } - if (NONCE in parameters) { - this.nonce = getParametersValue(parameters, NONCE, TimeStampReq.defaultValues(NONCE)); - } - if (CERT_REQ in parameters) { - this.certReq = getParametersValue(parameters, CERT_REQ, TimeStampReq.defaultValues(CERT_REQ)); - } - if (EXTENSIONS in parameters) { - this.extensions = getParametersValue(parameters, EXTENSIONS, TimeStampReq.defaultValues(EXTENSIONS)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case VERSION: - return 0; - case MESSAGE_IMPRINT: - return new MessageImprint(); - case REQ_POLICY: - return EMPTY_STRING; - case NONCE: - return new Integer(); - case CERT_REQ: - return false; - case EXTENSIONS: - return []; - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case VERSION: - case REQ_POLICY: - case CERT_REQ: - return (memberValue === TimeStampReq.defaultValues(memberName)); - case MESSAGE_IMPRINT: - return ((MessageImprint.compareWithDefault("hashAlgorithm", memberValue.hashAlgorithm)) && - (MessageImprint.compareWithDefault("hashedMessage", memberValue.hashedMessage))); - case NONCE: - return (memberValue.isEqual(TimeStampReq.defaultValues(memberName))); - case EXTENSIONS: - return (memberValue.length === 0); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || TIME_STAMP_REQ), - value: [ - new Integer({ name: (names.version || TIME_STAMP_REQ_VERSION) }), - MessageImprint.schema(names.messageImprint || { - names: { - blockName: TIME_STAMP_REQ_MESSAGE_IMPRINT - } - }), - new ObjectIdentifier({ - name: (names.reqPolicy || TIME_STAMP_REQ_POLICY), - optional: true - }), - new Integer({ - name: (names.nonce || TIME_STAMP_REQ_NONCE), - optional: true - }), - new Boolean({ - name: (names.certReq || TIME_STAMP_REQ_CERT_REQ), - optional: true - }), - new Constructed({ - optional: true, - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: [new Repeated({ - name: (names.extensions || TIME_STAMP_REQ_EXTENSIONS), - value: Extension.schema() - })] - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS$1); - const asn1 = compareSchema(schema, schema, TimeStampReq.schema()); - AsnError.assertSchema(asn1, this.className); - this.version = asn1.result[TIME_STAMP_REQ_VERSION].valueBlock.valueDec; - this.messageImprint = new MessageImprint({ schema: asn1.result[TIME_STAMP_REQ_MESSAGE_IMPRINT] }); - if (TIME_STAMP_REQ_POLICY in asn1.result) - this.reqPolicy = asn1.result[TIME_STAMP_REQ_POLICY].valueBlock.toString(); - if (TIME_STAMP_REQ_NONCE in asn1.result) - this.nonce = asn1.result[TIME_STAMP_REQ_NONCE]; - if (TIME_STAMP_REQ_CERT_REQ in asn1.result) - this.certReq = asn1.result[TIME_STAMP_REQ_CERT_REQ].valueBlock.value; - if (TIME_STAMP_REQ_EXTENSIONS in asn1.result) - this.extensions = Array.from(asn1.result[TIME_STAMP_REQ_EXTENSIONS], element => new Extension({ schema: element })); - } - toSchema() { - const outputArray = []; - outputArray.push(new Integer({ value: this.version })); - outputArray.push(this.messageImprint.toSchema()); - if (this.reqPolicy) - outputArray.push(new ObjectIdentifier({ value: this.reqPolicy })); - if (this.nonce) - outputArray.push(this.nonce); - if ((CERT_REQ in this) && (TimeStampReq.compareWithDefault(CERT_REQ, this.certReq) === false)) - outputArray.push(new Boolean({ value: this.certReq })); - if (this.extensions) { - outputArray.push(new Constructed({ - idBlock: { - tagClass: 3, - tagNumber: 0 - }, - value: Array.from(this.extensions, o => o.toSchema()) - })); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - version: this.version, - messageImprint: this.messageImprint.toJSON() - }; - if (this.reqPolicy !== undefined) - res.reqPolicy = this.reqPolicy; - if (this.nonce !== undefined) - res.nonce = this.nonce.toJSON(); - if ((this.certReq !== undefined) && (TimeStampReq.compareWithDefault(CERT_REQ, this.certReq) === false)) - res.certReq = this.certReq; - if (this.extensions) { - res.extensions = Array.from(this.extensions, o => o.toJSON()); - } - return res; - } -} +const VERSION = "version"; +const MESSAGE_IMPRINT = "messageImprint"; +const REQ_POLICY = "reqPolicy"; +const NONCE = "nonce"; +const CERT_REQ = "certReq"; +const EXTENSIONS = "extensions"; +const TIME_STAMP_REQ = "TimeStampReq"; +const TIME_STAMP_REQ_VERSION = `${TIME_STAMP_REQ}.${VERSION}`; +const TIME_STAMP_REQ_MESSAGE_IMPRINT = `${TIME_STAMP_REQ}.${MESSAGE_IMPRINT}`; +const TIME_STAMP_REQ_POLICY = `${TIME_STAMP_REQ}.${REQ_POLICY}`; +const TIME_STAMP_REQ_NONCE = `${TIME_STAMP_REQ}.${NONCE}`; +const TIME_STAMP_REQ_CERT_REQ = `${TIME_STAMP_REQ}.${CERT_REQ}`; +const TIME_STAMP_REQ_EXTENSIONS = `${TIME_STAMP_REQ}.${EXTENSIONS}`; +const CLEAR_PROPS$1 = [ + TIME_STAMP_REQ_VERSION, + TIME_STAMP_REQ_MESSAGE_IMPRINT, + TIME_STAMP_REQ_POLICY, + TIME_STAMP_REQ_NONCE, + TIME_STAMP_REQ_CERT_REQ, + TIME_STAMP_REQ_EXTENSIONS, +]; +class TimeStampReq extends PkiObject { + constructor(parameters = {}) { + super(); + this.version = getParametersValue(parameters, VERSION, TimeStampReq.defaultValues(VERSION)); + this.messageImprint = getParametersValue(parameters, MESSAGE_IMPRINT, TimeStampReq.defaultValues(MESSAGE_IMPRINT)); + if (REQ_POLICY in parameters) { + this.reqPolicy = getParametersValue(parameters, REQ_POLICY, TimeStampReq.defaultValues(REQ_POLICY)); + } + if (NONCE in parameters) { + this.nonce = getParametersValue(parameters, NONCE, TimeStampReq.defaultValues(NONCE)); + } + if (CERT_REQ in parameters) { + this.certReq = getParametersValue(parameters, CERT_REQ, TimeStampReq.defaultValues(CERT_REQ)); + } + if (EXTENSIONS in parameters) { + this.extensions = getParametersValue(parameters, EXTENSIONS, TimeStampReq.defaultValues(EXTENSIONS)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case VERSION: + return 0; + case MESSAGE_IMPRINT: + return new MessageImprint(); + case REQ_POLICY: + return EMPTY_STRING; + case NONCE: + return new Integer(); + case CERT_REQ: + return false; + case EXTENSIONS: + return []; + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case VERSION: + case REQ_POLICY: + case CERT_REQ: + return (memberValue === TimeStampReq.defaultValues(memberName)); + case MESSAGE_IMPRINT: + return ((MessageImprint.compareWithDefault("hashAlgorithm", memberValue.hashAlgorithm)) && + (MessageImprint.compareWithDefault("hashedMessage", memberValue.hashedMessage))); + case NONCE: + return (memberValue.isEqual(TimeStampReq.defaultValues(memberName))); + case EXTENSIONS: + return (memberValue.length === 0); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || TIME_STAMP_REQ), + value: [ + new Integer({ name: (names.version || TIME_STAMP_REQ_VERSION) }), + MessageImprint.schema(names.messageImprint || { + names: { + blockName: TIME_STAMP_REQ_MESSAGE_IMPRINT + } + }), + new ObjectIdentifier({ + name: (names.reqPolicy || TIME_STAMP_REQ_POLICY), + optional: true + }), + new Integer({ + name: (names.nonce || TIME_STAMP_REQ_NONCE), + optional: true + }), + new Boolean({ + name: (names.certReq || TIME_STAMP_REQ_CERT_REQ), + optional: true + }), + new Constructed({ + optional: true, + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: [new Repeated({ + name: (names.extensions || TIME_STAMP_REQ_EXTENSIONS), + value: Extension.schema() + })] + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS$1); + const asn1 = compareSchema(schema, schema, TimeStampReq.schema()); + AsnError.assertSchema(asn1, this.className); + this.version = asn1.result[TIME_STAMP_REQ_VERSION].valueBlock.valueDec; + this.messageImprint = new MessageImprint({ schema: asn1.result[TIME_STAMP_REQ_MESSAGE_IMPRINT] }); + if (TIME_STAMP_REQ_POLICY in asn1.result) + this.reqPolicy = asn1.result[TIME_STAMP_REQ_POLICY].valueBlock.toString(); + if (TIME_STAMP_REQ_NONCE in asn1.result) + this.nonce = asn1.result[TIME_STAMP_REQ_NONCE]; + if (TIME_STAMP_REQ_CERT_REQ in asn1.result) + this.certReq = asn1.result[TIME_STAMP_REQ_CERT_REQ].valueBlock.value; + if (TIME_STAMP_REQ_EXTENSIONS in asn1.result) + this.extensions = Array.from(asn1.result[TIME_STAMP_REQ_EXTENSIONS], element => new Extension({ schema: element })); + } + toSchema() { + const outputArray = []; + outputArray.push(new Integer({ value: this.version })); + outputArray.push(this.messageImprint.toSchema()); + if (this.reqPolicy) + outputArray.push(new ObjectIdentifier({ value: this.reqPolicy })); + if (this.nonce) + outputArray.push(this.nonce); + if ((CERT_REQ in this) && (TimeStampReq.compareWithDefault(CERT_REQ, this.certReq) === false)) + outputArray.push(new Boolean({ value: this.certReq })); + if (this.extensions) { + outputArray.push(new Constructed({ + idBlock: { + tagClass: 3, + tagNumber: 0 + }, + value: Array.from(this.extensions, o => o.toSchema()) + })); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + version: this.version, + messageImprint: this.messageImprint.toJSON() + }; + if (this.reqPolicy !== undefined) + res.reqPolicy = this.reqPolicy; + if (this.nonce !== undefined) + res.nonce = this.nonce.toJSON(); + if ((this.certReq !== undefined) && (TimeStampReq.compareWithDefault(CERT_REQ, this.certReq) === false)) + res.certReq = this.certReq; + if (this.extensions) { + res.extensions = Array.from(this.extensions, o => o.toJSON()); + } + return res; + } +} TimeStampReq.CLASS_NAME = "TimeStampReq"; -const STATUS = "status"; -const TIME_STAMP_TOKEN = "timeStampToken"; -const TIME_STAMP_RESP = "TimeStampResp"; -const TIME_STAMP_RESP_STATUS = `${TIME_STAMP_RESP}.${STATUS}`; -const TIME_STAMP_RESP_TOKEN = `${TIME_STAMP_RESP}.${TIME_STAMP_TOKEN}`; -const CLEAR_PROPS = [ - TIME_STAMP_RESP_STATUS, - TIME_STAMP_RESP_TOKEN -]; -class TimeStampResp extends PkiObject { - constructor(parameters = {}) { - super(); - this.status = getParametersValue(parameters, STATUS, TimeStampResp.defaultValues(STATUS)); - if (TIME_STAMP_TOKEN in parameters) { - this.timeStampToken = getParametersValue(parameters, TIME_STAMP_TOKEN, TimeStampResp.defaultValues(TIME_STAMP_TOKEN)); - } - if (parameters.schema) { - this.fromSchema(parameters.schema); - } - } - static defaultValues(memberName) { - switch (memberName) { - case STATUS: - return new PKIStatusInfo(); - case TIME_STAMP_TOKEN: - return new ContentInfo(); - default: - return super.defaultValues(memberName); - } - } - static compareWithDefault(memberName, memberValue) { - switch (memberName) { - case STATUS: - return ((PKIStatusInfo.compareWithDefault(STATUS, memberValue.status)) && - (("statusStrings" in memberValue) === false) && - (("failInfo" in memberValue) === false)); - case TIME_STAMP_TOKEN: - return ((memberValue.contentType === EMPTY_STRING) && - (memberValue.content instanceof Any)); - default: - return super.defaultValues(memberName); - } - } - static schema(parameters = {}) { - const names = getParametersValue(parameters, "names", {}); - return (new Sequence({ - name: (names.blockName || TIME_STAMP_RESP), - value: [ - PKIStatusInfo.schema(names.status || { - names: { - blockName: TIME_STAMP_RESP_STATUS - } - }), - ContentInfo.schema(names.timeStampToken || { - names: { - blockName: TIME_STAMP_RESP_TOKEN, - optional: true - } - }) - ] - })); - } - fromSchema(schema) { - clearProps(schema, CLEAR_PROPS); - const asn1 = compareSchema(schema, schema, TimeStampResp.schema()); - AsnError.assertSchema(asn1, this.className); - this.status = new PKIStatusInfo({ schema: asn1.result[TIME_STAMP_RESP_STATUS] }); - if (TIME_STAMP_RESP_TOKEN in asn1.result) - this.timeStampToken = new ContentInfo({ schema: asn1.result[TIME_STAMP_RESP_TOKEN] }); - } - toSchema() { - const outputArray = []; - outputArray.push(this.status.toSchema()); - if (this.timeStampToken) { - outputArray.push(this.timeStampToken.toSchema()); - } - return (new Sequence({ - value: outputArray - })); - } - toJSON() { - const res = { - status: this.status.toJSON() - }; - if (this.timeStampToken) { - res.timeStampToken = this.timeStampToken.toJSON(); - } - return res; - } - sign(privateKey, hashAlgorithm, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - this.assertContentType(); - const signed = new SignedData({ schema: this.timeStampToken.content }); - return signed.sign(privateKey, 0, hashAlgorithm, undefined, crypto); - }); - } - verify(verificationParameters = { signer: 0, trustedCerts: [], data: EMPTY_BUFFER }, crypto = getCrypto(true)) { - return __awaiter(this, void 0, void 0, function* () { - this.assertContentType(); - const signed = new SignedData({ schema: this.timeStampToken.content }); - return signed.verify(verificationParameters, crypto); - }); - } - assertContentType() { - if (!this.timeStampToken) { - throw new Error("timeStampToken is absent in TSP response"); - } - if (this.timeStampToken.contentType !== id_ContentType_SignedData) { - throw new Error(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`); - } - } -} +const STATUS = "status"; +const TIME_STAMP_TOKEN = "timeStampToken"; +const TIME_STAMP_RESP = "TimeStampResp"; +const TIME_STAMP_RESP_STATUS = `${TIME_STAMP_RESP}.${STATUS}`; +const TIME_STAMP_RESP_TOKEN = `${TIME_STAMP_RESP}.${TIME_STAMP_TOKEN}`; +const CLEAR_PROPS = [ + TIME_STAMP_RESP_STATUS, + TIME_STAMP_RESP_TOKEN +]; +class TimeStampResp extends PkiObject { + constructor(parameters = {}) { + super(); + this.status = getParametersValue(parameters, STATUS, TimeStampResp.defaultValues(STATUS)); + if (TIME_STAMP_TOKEN in parameters) { + this.timeStampToken = getParametersValue(parameters, TIME_STAMP_TOKEN, TimeStampResp.defaultValues(TIME_STAMP_TOKEN)); + } + if (parameters.schema) { + this.fromSchema(parameters.schema); + } + } + static defaultValues(memberName) { + switch (memberName) { + case STATUS: + return new PKIStatusInfo(); + case TIME_STAMP_TOKEN: + return new ContentInfo(); + default: + return super.defaultValues(memberName); + } + } + static compareWithDefault(memberName, memberValue) { + switch (memberName) { + case STATUS: + return ((PKIStatusInfo.compareWithDefault(STATUS, memberValue.status)) && + (("statusStrings" in memberValue) === false) && + (("failInfo" in memberValue) === false)); + case TIME_STAMP_TOKEN: + return ((memberValue.contentType === EMPTY_STRING) && + (memberValue.content instanceof Any)); + default: + return super.defaultValues(memberName); + } + } + static schema(parameters = {}) { + const names = getParametersValue(parameters, "names", {}); + return (new Sequence({ + name: (names.blockName || TIME_STAMP_RESP), + value: [ + PKIStatusInfo.schema(names.status || { + names: { + blockName: TIME_STAMP_RESP_STATUS + } + }), + ContentInfo.schema(names.timeStampToken || { + names: { + blockName: TIME_STAMP_RESP_TOKEN, + optional: true + } + }) + ] + })); + } + fromSchema(schema) { + clearProps(schema, CLEAR_PROPS); + const asn1 = compareSchema(schema, schema, TimeStampResp.schema()); + AsnError.assertSchema(asn1, this.className); + this.status = new PKIStatusInfo({ schema: asn1.result[TIME_STAMP_RESP_STATUS] }); + if (TIME_STAMP_RESP_TOKEN in asn1.result) + this.timeStampToken = new ContentInfo({ schema: asn1.result[TIME_STAMP_RESP_TOKEN] }); + } + toSchema() { + const outputArray = []; + outputArray.push(this.status.toSchema()); + if (this.timeStampToken) { + outputArray.push(this.timeStampToken.toSchema()); + } + return (new Sequence({ + value: outputArray + })); + } + toJSON() { + const res = { + status: this.status.toJSON() + }; + if (this.timeStampToken) { + res.timeStampToken = this.timeStampToken.toJSON(); + } + return res; + } + async sign(privateKey, hashAlgorithm, crypto = getCrypto(true)) { + this.assertContentType(); + const signed = new SignedData({ schema: this.timeStampToken.content }); + return signed.sign(privateKey, 0, hashAlgorithm, undefined, crypto); + } + async verify(verificationParameters = { signer: 0, trustedCerts: [], data: EMPTY_BUFFER }, crypto = getCrypto(true)) { + this.assertContentType(); + const signed = new SignedData({ schema: this.timeStampToken.content }); + return signed.verify(verificationParameters, crypto); + } + assertContentType() { + if (!this.timeStampToken) { + throw new Error("timeStampToken is absent in TSP response"); + } + if (this.timeStampToken.contentType !== id_ContentType_SignedData) { + throw new Error(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`); + } + } +} TimeStampResp.CLASS_NAME = "TimeStampResp"; -function initCryptoEngine() { - if (typeof self !== "undefined") { - if ("crypto" in self) { - let engineName = "webcrypto"; - if ("webkitSubtle" in self.crypto) { - engineName = "safari"; - } - setEngine(engineName, new CryptoEngine({ name: engineName, crypto: crypto })); - } - } - else if (typeof crypto !== "undefined" && "webcrypto" in crypto) { - const name = "NodeJS ^15"; - const nodeCrypto = crypto.webcrypto; - setEngine(name, new CryptoEngine({ name, crypto: nodeCrypto })); - } +function initCryptoEngine() { + if (typeof globalThis !== "undefined" && "crypto" in globalThis) { + let engineName = "webcrypto"; + if ("webkitSubtle" in globalThis.crypto) { + engineName = "safari"; + } + setEngine(engineName, new CryptoEngine({ name: engineName, crypto: globalThis.crypto })); + } + else if (typeof crypto !== "undefined" && "webcrypto" in crypto) { + const name = "NodeJS ^15"; + const nodeCrypto = crypto.webcrypto; + setEngine(name, new CryptoEngine({ name, crypto: nodeCrypto })); + } } initCryptoEngine();