Backed out 2 changesets (bug 1811633) for causing lint bustage CLOSED TREE

Backed out changeset 3ef0fe45b191 (bug 1811633)
Backed out changeset 92a7ec78a4ce (bug 1811633)
This commit is contained in:
Noemi Erli 2023-01-26 02:26:54 +02:00
Родитель 78cdb5eb07
Коммит e287ab9d9a
182 изменённых файлов: 1592 добавлений и 62946 удалений

Просмотреть файл

@ -1716,8 +1716,8 @@ module.exports = {
"toolkit/components/antitracking/test/browser/head.js",
"toolkit/components/antitracking/test/browser/storageAccessAPIHelpers.js",
"toolkit/components/certviewer/tests/browser/adjustedCerts.js",
"toolkit/components/certviewer/tests/chrome/CSoutput.mjs",
"toolkit/components/certviewer/tests/chrome/parseOutput.mjs",
"toolkit/components/certviewer/tests/chrome/CSoutput.js",
"toolkit/components/certviewer/tests/chrome/parseOutput.js",
"toolkit/components/cleardata/tests/browser/browser_css_cache.js",
"toolkit/components/cleardata/tests/browser/browser_image_cache.js",
"toolkit/components/cleardata/tests/browser/browser_preflight_cache.js",

Просмотреть файл

@ -131,9 +131,6 @@ _OPT\.OBJ/
^remote/test/puppeteer/utils/mochaRunner/lib/
^remote/test/puppeteer/website
^third_party/js/PKI.js/node_modules/
^third_party/js/PKI.js/package-lock.json
# git checkout of libstagefright
^media/libstagefright/android$
@ -246,6 +243,10 @@ gfx/wgpu/target
gfx/wgpu/.*/build
gfx/wr/target/
# Ignore this files in certviewer
toolkit/components/certviewer/content/node_modules/
toolkit/components/certviewer/content/package-lock.json
# Ignore Rust/Cargo output from running `cargo` directly for image_builder docker image
^taskcluster/docker/image_builder/build-image/target

Просмотреть файл

@ -73,11 +73,31 @@ XPCOMUtils.defineLazyModuleGetters(lazy, {
NetUtil: "resource://gre/modules/NetUtil.jsm",
});
// It would make sense to put this in the above
// ChromeUtils.defineESModuleGetters, but that doesn't seem to work.
XPCOMUtils.defineLazyGetter(lazy, "certDecoder", () => {
const { parse, pemToDER } = ChromeUtils.importESModule(
"chrome://global/content/certviewer/certDecoder.mjs"
const { asn1js } = ChromeUtils.import(
"chrome://global/content/certviewer/asn1js_bundle.jsm"
);
const { pkijs } = ChromeUtils.import(
"chrome://global/content/certviewer/pkijs_bundle.jsm"
);
const { pvutils } = ChromeUtils.import(
"chrome://global/content/certviewer/pvutils_bundle.jsm"
);
const { Integer, fromBER } = asn1js.asn1js;
const { Certificate } = pkijs.pkijs;
const { fromBase64, stringToArrayBuffer } = pvutils.pvutils;
const { certDecoderInitializer } = ChromeUtils.import(
"chrome://global/content/certviewer/certDecoder.jsm"
);
const { parse, pemToDER } = certDecoderInitializer(
Integer,
fromBER,
Certificate,
fromBase64,
stringToArrayBuffer,
crypto
);
return { parse, pemToDER };
});

Просмотреть файл

@ -6,8 +6,30 @@
/* import-globals-from pippki.js */
"use strict";
const { parse, pemToDER } = ChromeUtils.importESModule(
"chrome://global/content/certviewer/certDecoder.mjs"
const { asn1js } = ChromeUtils.import(
"chrome://global/content/certviewer/asn1js_bundle.jsm"
);
const { pkijs } = ChromeUtils.import(
"chrome://global/content/certviewer/pkijs_bundle.jsm"
);
const { pvutils } = ChromeUtils.import(
"chrome://global/content/certviewer/pvutils_bundle.jsm"
);
const { Integer, fromBER } = asn1js.asn1js;
const { Certificate } = pkijs.pkijs;
const { fromBase64, stringToArrayBuffer } = pvutils.pvutils;
const { certDecoderInitializer } = ChromeUtils.import(
"chrome://global/content/certviewer/certDecoder.jsm"
);
const { parse, pemToDER } = certDecoderInitializer(
Integer,
fromBER,
Certificate,
fromBase64,
stringToArrayBuffer,
crypto
);
/**

30
third_party/js/PKI.js/LICENSE поставляемый
Просмотреть файл

@ -1,30 +0,0 @@
Copyright (c) 2014, GlobalSign
Copyright (c) 2015-2019, Peculiar Ventures
All rights reserved.
Author 2014-2019, Yury Strozhevsky
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Просмотреть файл

@ -1,70 +0,0 @@
diff --git a/rollup.config.js b/rollup.config.js
index 8c8a7c2..b6e61c0 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -3,6 +3,7 @@ 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 = [
@@ -12,7 +13,6 @@ const banner = [
"",
].join("\n");
const input = "src/index.ts";
-const external = Object.keys(pkg.dependencies || {});
export default [
{
@@ -26,10 +26,10 @@ export default [
module: "ES2015",
removeComments: true,
}
- }
+ },
}),
+ nodeResolve(),
],
- external: [...external],
output: [
{
banner,
@@ -45,7 +45,6 @@ export default [
},
{
input,
- external: [...external],
plugins: [
dts({
tsconfig: path.resolve(__dirname, "./tsconfig.json")
@@ -58,4 +57,4 @@ export default [
}
]
},
-];
\ No newline at end of file
+];
diff --git a/tsconfig.json b/tsconfig.json
index ffd67ec..e72bdb6 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,7 +1,8 @@
{
"compilerOptions": {
- "target": "ES2019",
- "module": "CommonJS",
+ "target": "ES6",
+ "module": "ES6",
+ "moduleResolution": "node",
"strict": true,
"importHelpers": true,
"noImplicitOverride": true,
@@ -11,4 +12,4 @@
"exclude": [
"build/*.ts"
]
-}
\ No newline at end of file
+}

5
third_party/js/PKI.js/make_bundle.sh поставляемый
Просмотреть файл

@ -1,5 +0,0 @@
#!/bin/sh
patch -p1 < make-esmodule-bundle.patch
npm install
npm run build

85
third_party/js/PKI.js/moz.yaml поставляемый
Просмотреть файл

@ -1,85 +0,0 @@
# Version of this schema
schema: 1
bugzilla:
# Bugzilla product and component for this directory and subdirectories
product: Firefox
component: Security
# Document the source of externally hosted code
origin:
# Short name of the package/library
name: PKIjs
description: TypeScript library for interacting with public key infrastructure types.
# Full URL for the package's homepage/etc
# Usually different from repository url
url: https://pkijs.org/
# Human-readable identifier for this version/release
# Generally "version NNN", "tag SSS", "bookmark SSS"
release: 72d175c9edbc8e00c550dee610a8dac6204f4383 (2023-01-15T09:12:35Z).
# Revision to pull in
# Must be a long or short commit SHA (long preferred)
revision: 72d175c9edbc8e00c550dee610a8dac6204f4383
# The package's license, where possible using the mnemonic from
# https://spdx.org/licenses/
# Multiple licenses can be specified (as a YAML list)
# A "LICENSE" file must exist containing the full license text
license: BSD-3-Clause
# If the package's license is specified in a particular file,
# this is the name of the file.
# optional
license-file: LICENSE
# Configuration for the automated vendoring system.
# optional
vendoring:
# Repository URL to vendor from
# eg. https://github.com/kinetiknz/nestegg
# Any repository host can be specified here, however initially we'll only
# support automated vendoring from selected sources.
url: https://github.com/PeculiarVentures/PKI.js
# Type of hosting for the upstream repository
# Valid values are 'gitlab', 'github', googlesource
source-hosting: github
# Files/paths that will not be vendored from the upstream repository
# Implicitly contains ".git", and ".gitignore"
# optional
exclude:
- .eslintrc.json
- .github/
- .gitignore
- .mocharc.yaml
- .nycrc
- CNAME
- FEATURES.md
- MAPPING.md
- README.md
- examples/
- test/
- typedoc.json
keep:
- make_bundle.sh
- make-esmodule-bundle.patch
update-actions:
- action: run-script
script: 'make_bundle.sh'
cwd: '{yaml_dir}'
- action: move-file
from: 'build/index.es.js'
to: '../../../toolkit/components/certviewer/content/vendor/pkijs.js'
- action: delete-path
path: 'build'

86
third_party/js/PKI.js/package.json поставляемый
Просмотреть файл

@ -1,86 +0,0 @@
{
"author": {
"email": "yury@strozhevsky.com",
"name": "Yury Strozhevsky"
},
"description": "Public Key Infrastructure (PKI) is the basis of how identity and key management is performed on the web today. PKIjs is a pure JavaScript library implementing the formats that are used in PKI applications. It is built on WebCrypto and aspires to make it possible to build native web applications that utilize X.509 and the related formats on the web without plug-ins",
"contributors": [
{
"email": "rmh@unmitigatedrisk.com",
"name": "Ryan Hurst"
}
],
"repository": {
"type": "git",
"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",
"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"
},
"dependencies": {
"asn1js": "^3.0.5",
"bytestreamjs": "^2.0.0",
"pvtsutils": "^1.3.2",
"pvutils": "^1.1.3",
"tslib": "^2.4.0"
},
"engines": {
"node": ">=12.0.0"
},
"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",
"test": "mocha",
"prepublishOnly": "npm run build"
},
"keywords": [
"ES6",
"ES2015",
"WebCrypto",
"Web Cryptography API",
"X.509",
"certificate",
"crl",
"cms",
"encrypted",
"enveloped",
"OCSP",
"timestamp",
"PKCS"
],
"files": [
"build",
"README.md",
"LICENSE"
],
"module": "build/index.es.js",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"name": "pkijs",
"version": "3.0.11",
"license": "BSD-3-Clause"
}

60
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,
}
]
},
];

151
third_party/js/PKI.js/src/AccessDescription.ts поставляемый
Просмотреть файл

@ -1,151 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { GeneralName, GeneralNameJson, GeneralNameSchema } from "./GeneralName";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const ACCESS_METHOD = "accessMethod";
const ACCESS_LOCATION = "accessLocation";
const CLEAR_PROPS = [
ACCESS_METHOD,
ACCESS_LOCATION,
];
export interface IAccessDescription {
/**
* The type and format of the information are specified by the accessMethod field. This profile defines two accessMethod OIDs: id-ad-caIssuers and id-ad-ocsp
*/
accessMethod: string;
/**
* The accessLocation field specifies the location of the information
*/
accessLocation: GeneralName;
}
export type AccessDescriptionParameters = PkiObjectParameters & Partial<IAccessDescription>;
/**
* JSON representation of {@link AccessDescription}
*/
export interface AccessDescriptionJson {
accessMethod: string;
accessLocation: GeneralNameJson;
}
/**
* Represents the AccessDescription structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*
* The authority information access extension indicates how to access
* information and services for the issuer of the certificate in which
* the extension appears. Information and services may include on-line
* validation services and CA policy data. This extension may be included in
* end entity or CA certificates. Conforming CAs MUST mark this
* extension as non-critical.
*/
export class AccessDescription extends PkiObject implements IAccessDescription {
public static override CLASS_NAME = "AccessDescription";
public accessMethod!: string;
public accessLocation!: GeneralName;
/**
* Initializes a new instance of the {@link AccessDescription} class
* @param parameters Initialization parameters
*/
constructor(parameters: AccessDescriptionParameters = {}) {
super();
this.accessMethod = pvutils.getParametersValue(parameters, ACCESS_METHOD, AccessDescription.defaultValues(ACCESS_METHOD));
this.accessLocation = pvutils.getParametersValue(parameters, ACCESS_LOCATION, AccessDescription.defaultValues(ACCESS_LOCATION));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ACCESS_METHOD): string;
public static override defaultValues(memberName: typeof ACCESS_LOCATION): GeneralName;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ACCESS_METHOD:
return EMPTY_STRING;
case ACCESS_LOCATION:
return new GeneralName();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AccessDescription ::= SEQUENCE {
* accessMethod OBJECT IDENTIFIER,
* accessLocation GeneralName }
*```
*/
static override schema(parameters: Schema.SchemaParameters<{ accessMethod?: string; accessLocation?: GeneralNameSchema; }> = {}) {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.accessMethod || EMPTY_STRING) }),
GeneralName.schema(names.accessLocation || {})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AccessDescription.schema({
names: {
accessMethod: ACCESS_METHOD,
accessLocation: {
names: {
blockName: ACCESS_LOCATION
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.accessMethod = asn1.result.accessMethod.valueBlock.toString();
this.accessLocation = new GeneralName({ schema: asn1.result.accessLocation });
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.accessMethod }),
this.accessLocation.toSchema()
]
}));
//#endregion
}
public toJSON(): AccessDescriptionJson {
return {
accessMethod: this.accessMethod,
accessLocation: this.accessLocation.toJSON()
};
}
}

243
third_party/js/PKI.js/src/Accuracy.ts поставляемый
Просмотреть файл

@ -1,243 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
export const SECONDS = "seconds";
export const MILLIS = "millis";
export const MICROS = "micros";
export interface IAccuracy {
/**
* Seconds
*/
seconds?: number;
/**
* Milliseconds
*/
millis?: number;
/**
* Microseconds
*/
micros?: number;
}
export type AccuracyParameters = PkiObjectParameters & Partial<IAccuracy>;
export type AccuracySchema = Schema.SchemaParameters<{
seconds?: string;
millis?: string;
micros?: string;
}>;
/**
* JSON representation of {@link Accuracy}
*/
export interface AccuracyJson {
seconds?: number;
millis?: number;
micros?: number;
}
/**
* Represents the time deviation around the UTC time contained in GeneralizedTime. Described in [RFC3161](https://www.ietf.org/rfc/rfc3161.txt)
*/
export class Accuracy extends PkiObject implements IAccuracy {
public static override CLASS_NAME = "Accuracy";
public seconds?: number;
public millis?: number;
public micros?: number;
/**
* Initializes a new instance of the {@link Accuracy} class
* @param parameters Initialization parameters
*/
constructor(parameters: AccuracyParameters = {}) {
super();
if (SECONDS in parameters) {
this.seconds = pvutils.getParametersValue(parameters, SECONDS, Accuracy.defaultValues(SECONDS));
}
if (MILLIS in parameters) {
this.millis = pvutils.getParametersValue(parameters, MILLIS, Accuracy.defaultValues(MILLIS));
}
if (MICROS in parameters) {
this.micros = pvutils.getParametersValue(parameters, MICROS, Accuracy.defaultValues(MICROS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof SECONDS): number;
public static override defaultValues(memberName: typeof MILLIS): number;
public static override defaultValues(memberName: typeof MICROS): number;
public static override defaultValues(memberName: string): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case SECONDS:
case MILLIS:
case MICROS:
return 0;
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: typeof SECONDS | typeof MILLIS | typeof MICROS, memberValue: number): boolean;
public static compareWithDefault(memberName: string, memberValue: any): boolean;
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case SECONDS:
case MILLIS:
case MICROS:
return (memberValue === Accuracy.defaultValues(memberName));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* Accuracy ::= SEQUENCE {
* seconds INTEGER OPTIONAL,
* millis [0] INTEGER (1..999) OPTIONAL,
* micros [1] INTEGER (1..999) OPTIONAL }
*```
*/
public static override schema(parameters: AccuracySchema = {}): any {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
optional: true,
value: [
new asn1js.Integer({
optional: true,
name: (names.seconds || EMPTY_STRING)
}),
new asn1js.Primitive({
name: (names.millis || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
}
}),
new asn1js.Primitive({
name: (names.micros || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
}
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, [
SECONDS,
MILLIS,
MICROS,
]);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
Accuracy.schema({
names: {
seconds: SECONDS,
millis: MILLIS,
micros: MICROS,
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
if ("seconds" in asn1.result) {
this.seconds = asn1.result.seconds.valueBlock.valueDec;
}
if ("millis" in asn1.result) {
const intMillis = new asn1js.Integer({ valueHex: asn1.result.millis.valueBlock.valueHex });
this.millis = intMillis.valueBlock.valueDec;
}
if ("micros" in asn1.result) {
const intMicros = new asn1js.Integer({ valueHex: asn1.result.micros.valueBlock.valueHex });
this.micros = intMicros.valueBlock.valueDec;
}
}
public toSchema(): asn1js.Sequence {
//#region Create array of output sequence
const outputArray = [];
if (this.seconds !== undefined)
outputArray.push(new asn1js.Integer({ value: this.seconds }));
if (this.millis !== undefined) {
const intMillis = new asn1js.Integer({ value: this.millis });
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
valueHex: intMillis.valueBlock.valueHexView
}));
}
if (this.micros !== undefined) {
const intMicros = new asn1js.Integer({ value: this.micros });
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
valueHex: intMicros.valueBlock.valueHexView
}));
}
//#endregion
return (new asn1js.Sequence({
value: outputArray
}));
}
public toJSON(): AccuracyJson {
const _object: AccuracyJson = {};
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;
}
}

Просмотреть файл

@ -1,209 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const ALGORITHM_ID = "algorithmId";
const ALGORITHM_PARAMS = "algorithmParams";
const ALGORITHM = "algorithm";
const PARAMS = "params";
const CLEAR_PROPS = [
ALGORITHM,
PARAMS
];
export interface IAlgorithmIdentifier {
/**
* ObjectIdentifier for algorithm (string representation)
*/
algorithmId: string;
/**
* Any algorithm parameters
*/
algorithmParams?: any;
}
export type AlgorithmIdentifierParameters = PkiObjectParameters & Partial<IAlgorithmIdentifier>;
/**
* JSON representation of {@link AlgorithmIdentifier}
*/
export interface AlgorithmIdentifierJson {
algorithmId: string;
algorithmParams?: any;
}
export type AlgorithmIdentifierSchema = Schema.SchemaParameters<{
algorithmIdentifier?: string;
algorithmParams?: string;
}>;
/**
* Represents the AlgorithmIdentifier structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class AlgorithmIdentifier extends PkiObject implements IAlgorithmIdentifier {
public static override CLASS_NAME = "AlgorithmIdentifier";
public algorithmId!: string;
public algorithmParams?: any;
/**
* Initializes a new instance of the {@link AlgorithmIdentifier} class
* @param parameters Initialization parameters
*/
constructor(parameters: AlgorithmIdentifierParameters = {}) {
super();
this.algorithmId = pvutils.getParametersValue(parameters, ALGORITHM_ID, AlgorithmIdentifier.defaultValues(ALGORITHM_ID));
if (ALGORITHM_PARAMS in parameters) {
this.algorithmParams = pvutils.getParametersValue(parameters, ALGORITHM_PARAMS, AlgorithmIdentifier.defaultValues(ALGORITHM_PARAMS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ALGORITHM_ID): string;
public static override defaultValues(memberName: typeof ALGORITHM_PARAMS): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ALGORITHM_ID:
return EMPTY_STRING;
case ALGORITHM_PARAMS:
return new asn1js.Any();
default:
return super.defaultValues(memberName);
}
}
/**
* Compares values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case ALGORITHM_ID:
return (memberValue === EMPTY_STRING);
case ALGORITHM_PARAMS:
return (memberValue instanceof asn1js.Any);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AlgorithmIdentifier ::= Sequence {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
*```
*/
public static override schema(parameters: AlgorithmIdentifierSchema = {}): any {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
optional: (names.optional || false),
value: [
new asn1js.ObjectIdentifier({ name: (names.algorithmIdentifier || EMPTY_STRING) }),
new asn1js.Any({ name: (names.algorithmParams || EMPTY_STRING), optional: true })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AlgorithmIdentifier.schema({
names: {
algorithmIdentifier: ALGORITHM,
algorithmParams: PARAMS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.algorithmId = asn1.result.algorithm.valueBlock.toString();
if (PARAMS in asn1.result) {
this.algorithmParams = asn1.result.params;
}
}
public toSchema(): asn1js.Sequence {
// Create array for output sequence
const outputArray = [];
outputArray.push(new asn1js.ObjectIdentifier({ value: this.algorithmId }));
if (this.algorithmParams && !(this.algorithmParams instanceof asn1js.Any)) {
outputArray.push(this.algorithmParams);
}
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
}
public toJSON(): AlgorithmIdentifierJson {
const object: AlgorithmIdentifierJson = {
algorithmId: this.algorithmId
};
if (this.algorithmParams && !(this.algorithmParams instanceof asn1js.Any)) {
object.algorithmParams = this.algorithmParams.toJSON();
}
return object;
}
/**
* Checks that two "AlgorithmIdentifiers" are equal
* @param algorithmIdentifier
*/
public isEqual(algorithmIdentifier: unknown): boolean {
//#region Check input type
if (!(algorithmIdentifier instanceof AlgorithmIdentifier)) {
return false;
}
//#endregion
//#region Check "algorithm_id"
if (this.algorithmId !== algorithmIdentifier.algorithmId) {
return false;
}
//#endregion
//#region Check "algorithm_params"
if (this.algorithmParams) {
if (algorithmIdentifier.algorithmParams) {
return JSON.stringify(this.algorithmParams) === JSON.stringify(algorithmIdentifier.algorithmParams);
}
return false;
}
if (algorithmIdentifier.algorithmParams) {
return false;
}
//#endregion
return true;
}
}

121
third_party/js/PKI.js/src/AltName.ts поставляемый
Просмотреть файл

@ -1,121 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { GeneralName, GeneralNameJson } from "./GeneralName";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const ALT_NAMES = "altNames";
const CLEAR_PROPS = [
ALT_NAMES
];
export interface IAltName {
/**
* Array of alternative names in GeneralName type
*/
altNames: GeneralName[];
}
export type AltNameParameters = PkiObjectParameters & Partial<IAltName>;
export interface AltNameJson {
altNames: GeneralNameJson[];
}
/**
* Represents the AltName structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class AltName extends PkiObject implements IAltName {
public static override CLASS_NAME = "AltName";
public altNames!: GeneralName[];
/**
* Initializes a new instance of the {@link AltName} class
* @param parameters Initialization parameters
*/
constructor(parameters: AltNameParameters = {}) {
super();
this.altNames = pvutils.getParametersValue(parameters, ALT_NAMES, AltName.defaultValues(ALT_NAMES));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ALT_NAMES): GeneralName[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ALT_NAMES:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AltName ::= GeneralNames
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{ altNames?: string; }> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.altNames || EMPTY_STRING),
value: GeneralName.schema()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AltName.schema({
names: {
altNames: ALT_NAMES
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
if (ALT_NAMES in asn1.result) {
this.altNames = Array.from(asn1.result.altNames, element => new GeneralName({ schema: element }));
}
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: Array.from(this.altNames, o => o.toSchema())
}));
//#endregion
}
public toJSON(): AltNameJson {
return {
altNames: Array.from(this.altNames, o => o.toJSON())
};
}
}

170
third_party/js/PKI.js/src/Attribute.ts поставляемый
Просмотреть файл

@ -1,170 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const TYPE = "type";
const VALUES = "values";
const CLEAR_PROPS = [
TYPE,
VALUES
];
export interface IAttribute {
/**
* Specifies type of attribute value
*/
type: string;
/**
* List of attribute values
*/
values: any[];
}
export type AttributeParameters = PkiObjectParameters & Partial<IAttribute>;
export type AttributeSchema = Schema.SchemaParameters<{
setName?: string;
type?: string;
values?: string;
}>;
export interface AttributeJson {
type: string;
values: any[];
}
/**
* Represents the Attribute structure described in [RFC2986](https://datatracker.ietf.org/doc/html/rfc2986)
*/
export class Attribute extends PkiObject implements IAttribute {
public static override CLASS_NAME = "Attribute";
public type!: string;
public values!: any[];
/**
* Initializes a new instance of the {@link Attribute} class
* @param parameters Initialization parameters
*/
constructor(parameters: AttributeParameters = {}) {
super();
this.type = pvutils.getParametersValue(parameters, TYPE, Attribute.defaultValues(TYPE));
this.values = pvutils.getParametersValue(parameters, VALUES, Attribute.defaultValues(VALUES));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TYPE): string;
public static override defaultValues(memberName: typeof VALUES): any[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TYPE:
return EMPTY_STRING;
case VALUES:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* Compares values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case TYPE:
return (memberValue === EMPTY_STRING);
case VALUES:
return (memberValue.length === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
* type ATTRIBUTE.&id({IOSet}),
* values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
* }
*```
*/
public static override schema(parameters: AttributeSchema = {}) {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.type || EMPTY_STRING) }),
new asn1js.Set({
name: (names.setName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.values || EMPTY_STRING),
value: new asn1js.Any()
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
Attribute.schema({
names: {
type: TYPE,
values: VALUES
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.type = asn1.result.type.valueBlock.toString();
this.values = asn1.result.values;
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.type }),
new asn1js.Set({
value: this.values
})
]
}));
//#endregion
}
public toJSON(): AttributeJson {
return {
type: this.type,
values: Array.from(this.values, o => o.toJSON())
};
}
}

Просмотреть файл

@ -1,134 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "../constants";
import { AsnError } from "../errors";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import * as Schema from "../Schema";
const NOT_BEFORE_TIME = "notBeforeTime";
const NOT_AFTER_TIME = "notAfterTime";
const CLEAR_PROPS = [
NOT_BEFORE_TIME,
NOT_AFTER_TIME,
];
export interface IAttCertValidityPeriod {
notBeforeTime: Date;
notAfterTime: Date;
}
export type AttCertValidityPeriodParameters = PkiObjectParameters & Partial<IAttCertValidityPeriod>;
export type AttCertValidityPeriodSchema = Schema.SchemaParameters<{
notBeforeTime?: string;
notAfterTime?: string;
}>;
export interface AttCertValidityPeriodJson {
notBeforeTime: Date;
notAfterTime: Date;
}
/**
* Represents the AttCertValidityPeriod structure described in [RFC5755 Section 4.1](https://datatracker.ietf.org/doc/html/rfc5755#section-4.1)
*/
export class AttCertValidityPeriod extends PkiObject implements IAttCertValidityPeriod {
public static override CLASS_NAME = "AttCertValidityPeriod";
public notBeforeTime!: Date;
public notAfterTime!: Date;
/**
* Initializes a new instance of the {@link AttCertValidityPeriod} class
* @param parameters Initialization parameters
*/
constructor(parameters: AttCertValidityPeriodParameters = {}) {
super();
this.notBeforeTime = pvutils.getParametersValue(parameters, NOT_BEFORE_TIME, AttCertValidityPeriod.defaultValues(NOT_BEFORE_TIME));
this.notAfterTime = pvutils.getParametersValue(parameters, NOT_AFTER_TIME, AttCertValidityPeriod.defaultValues(NOT_AFTER_TIME));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof NOT_BEFORE_TIME): Date;
public static override defaultValues(memberName: typeof NOT_AFTER_TIME): Date;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case NOT_BEFORE_TIME:
case NOT_AFTER_TIME:
return new Date(0, 0, 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AttCertValidityPeriod ::= SEQUENCE {
* notBeforeTime GeneralizedTime,
* notAfterTime GeneralizedTime
* }
*```
*/
public static override schema(parameters: AttCertValidityPeriodSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.GeneralizedTime({ name: (names.notBeforeTime || EMPTY_STRING) }),
new asn1js.GeneralizedTime({ name: (names.notAfterTime || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AttCertValidityPeriod.schema({
names: {
notBeforeTime: NOT_BEFORE_TIME,
notAfterTime: NOT_AFTER_TIME
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.notBeforeTime = asn1.result.notBeforeTime.toDate();
this.notAfterTime = asn1.result.notAfterTime.toDate();
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.GeneralizedTime({ valueDate: this.notBeforeTime }),
new asn1js.GeneralizedTime({ valueDate: this.notAfterTime }),
]
}));
}
public toJSON(): AttCertValidityPeriodJson {
return {
notBeforeTime: this.notBeforeTime,
notAfterTime: this.notAfterTime
};
}
}

Просмотреть файл

@ -1,407 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { GeneralNames, GeneralNamesJson } from "../GeneralNames";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "../AlgorithmIdentifier";
import { Attribute, AttributeJson } from "../Attribute";
import { Extensions, ExtensionsJson, ExtensionsSchema } from "../Extensions";
import { AttCertValidityPeriod, AttCertValidityPeriodJson, AttCertValidityPeriodSchema } from "./AttCertValidityPeriod";
import { IssuerSerial, IssuerSerialJson } from "./IssuerSerial";
import * as Schema from "../Schema";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import { AsnError } from "../errors";
import { EMPTY_STRING } from "../constants";
const VERSION = "version";
const BASE_CERTIFICATE_ID = "baseCertificateID";
const SUBJECT_NAME = "subjectName";
const ISSUER = "issuer";
const SIGNATURE = "signature";
const SERIAL_NUMBER = "serialNumber";
const ATTR_CERT_VALIDITY_PERIOD = "attrCertValidityPeriod";
const ATTRIBUTES = "attributes";
const ISSUER_UNIQUE_ID = "issuerUniqueID";
const EXTENSIONS = "extensions";
const CLEAR_PROPS = [
VERSION,
BASE_CERTIFICATE_ID,
SUBJECT_NAME,
ISSUER,
SIGNATURE,
SERIAL_NUMBER,
ATTR_CERT_VALIDITY_PERIOD,
ATTRIBUTES,
ISSUER_UNIQUE_ID,
EXTENSIONS,
];
export interface IAttributeCertificateInfoV1 {
/**
* The version field MUST have the value of v2
*/
version: number;
baseCertificateID?: IssuerSerial;
subjectName?: GeneralNames;
issuer: GeneralNames;
/**
* Contains the algorithm identifier used to validate the AC signature
*/
signature: AlgorithmIdentifier;
serialNumber: asn1js.Integer;
/**
* Specifies the period for which the AC issuer certifies that the binding between
* the holder and the attributes fields will be valid
*/
attrCertValidityPeriod: AttCertValidityPeriod;
/**
* The attributes field gives information about the AC holder
*/
attributes: Attribute[];
/**
* Issuer unique identifier
*/
issuerUniqueID?: asn1js.BitString;
/**
* The extensions field generally gives information about the AC as opposed
* to information about the AC holder
*/
extensions?: Extensions;
}
export interface AttributeCertificateInfoV1Json {
version: number;
baseCertificateID?: IssuerSerialJson;
subjectName?: GeneralNamesJson;
issuer: GeneralNamesJson;
signature: AlgorithmIdentifierJson;
serialNumber: asn1js.IntegerJson;
attrCertValidityPeriod: AttCertValidityPeriodJson;
attributes: AttributeJson[];
issuerUniqueID: asn1js.BitStringJson;
extensions: ExtensionsJson;
}
export type AttributeCertificateInfoV1Parameters = PkiObjectParameters & Partial<IAttributeCertificateInfoV1>;
export type AttributeCertificateInfoV1Schema = Schema.SchemaParameters<{
version?: string;
baseCertificateID?: string;
subjectName?: string;
signature?: AlgorithmIdentifierSchema;
issuer?: string;
attrCertValidityPeriod?: AttCertValidityPeriodSchema;
serialNumber?: string;
attributes?: string;
issuerUniqueID?: string;
extensions?: ExtensionsSchema;
}>;
/**
* Represents the AttributeCertificateInfoV1 structure described in [RFC5755](https://datatracker.ietf.org/doc/html/rfc5755)
*/
export class AttributeCertificateInfoV1 extends PkiObject implements IAttributeCertificateInfoV1 {
public static override CLASS_NAME = "AttributeCertificateInfoV1";
version!: number;
baseCertificateID?: IssuerSerial;
subjectName?: GeneralNames;
issuer!: GeneralNames;
signature!: AlgorithmIdentifier;
serialNumber!: asn1js.Integer;
attrCertValidityPeriod!: AttCertValidityPeriod;
attributes!: Attribute[];
issuerUniqueID?: asn1js.BitString;
extensions?: Extensions;
/**
* Initializes a new instance of the {@link AttributeCertificateInfoV1} class
* @param parameters Initialization parameters
*/
constructor(parameters: AttributeCertificateInfoV1Parameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, AttributeCertificateInfoV1.defaultValues(VERSION));
if (BASE_CERTIFICATE_ID in parameters) {
this.baseCertificateID = pvutils.getParametersValue(parameters, BASE_CERTIFICATE_ID, AttributeCertificateInfoV1.defaultValues(BASE_CERTIFICATE_ID));
}
if (SUBJECT_NAME in parameters) {
this.subjectName = pvutils.getParametersValue(parameters, SUBJECT_NAME, AttributeCertificateInfoV1.defaultValues(SUBJECT_NAME));
}
this.issuer = pvutils.getParametersValue(parameters, ISSUER, AttributeCertificateInfoV1.defaultValues(ISSUER));
this.signature = pvutils.getParametersValue(parameters, SIGNATURE, AttributeCertificateInfoV1.defaultValues(SIGNATURE));
this.serialNumber = pvutils.getParametersValue(parameters, SERIAL_NUMBER, AttributeCertificateInfoV1.defaultValues(SERIAL_NUMBER));
this.attrCertValidityPeriod = pvutils.getParametersValue(parameters, ATTR_CERT_VALIDITY_PERIOD, AttributeCertificateInfoV1.defaultValues(ATTR_CERT_VALIDITY_PERIOD));
this.attributes = pvutils.getParametersValue(parameters, ATTRIBUTES, AttributeCertificateInfoV1.defaultValues(ATTRIBUTES));
if (ISSUER_UNIQUE_ID in parameters)
this.issuerUniqueID = pvutils.getParametersValue(parameters, ISSUER_UNIQUE_ID, AttributeCertificateInfoV1.defaultValues(ISSUER_UNIQUE_ID));
if (EXTENSIONS in parameters) {
this.extensions = pvutils.getParametersValue(parameters, EXTENSIONS, AttributeCertificateInfoV1.defaultValues(EXTENSIONS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof BASE_CERTIFICATE_ID): IssuerSerial;
public static override defaultValues(memberName: typeof SUBJECT_NAME): GeneralNames;
public static override defaultValues(memberName: typeof ISSUER): GeneralNames;
public static override defaultValues(memberName: typeof SIGNATURE): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SERIAL_NUMBER): asn1js.Integer;
public static override defaultValues(memberName: typeof ATTR_CERT_VALIDITY_PERIOD): AttCertValidityPeriod;
public static override defaultValues(memberName: typeof ATTRIBUTES): Attribute[];
public static override defaultValues(memberName: typeof ISSUER_UNIQUE_ID): asn1js.BitString;
public static override defaultValues(memberName: typeof EXTENSIONS): Extensions;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return 0;
case BASE_CERTIFICATE_ID:
return new IssuerSerial();
case SUBJECT_NAME:
return new GeneralNames();
case ISSUER:
return new GeneralNames();
case SIGNATURE:
return new AlgorithmIdentifier();
case SERIAL_NUMBER:
return new asn1js.Integer();
case ATTR_CERT_VALIDITY_PERIOD:
return new AttCertValidityPeriod();
case ATTRIBUTES:
return [];
case ISSUER_UNIQUE_ID:
return new asn1js.BitString();
case EXTENSIONS:
return new Extensions();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AttributeCertificateInfo ::= SEQUENCE {
* version Version DEFAULT v1,
* subject CHOICE {
* baseCertificateID [0] IssuerSerial, -- associated with a Public Key Certificate
* subjectName [1] GeneralNames }, -- associated with a name
* issuer GeneralNames, -- CA issuing the attribute certificate
* signature AlgorithmIdentifier,
* serialNumber CertificateSerialNumber,
* attrCertValidityPeriod AttCertValidityPeriod,
* attributes SEQUENCE OF Attribute,
* issuerUniqueID UniqueIdentifier OPTIONAL,
* extensions Extensions OPTIONAL
* }
*```
*/
public static override schema(parameters: AttributeCertificateInfoV1Schema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || EMPTY_STRING) }),
new asn1js.Choice({
value: [
new asn1js.Constructed({
name: (names.baseCertificateID || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: IssuerSerial.schema().valueBlock.value
}),
new asn1js.Constructed({
name: (names.subjectName || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 1 // [2]
},
value: GeneralNames.schema().valueBlock.value
}),
]
}),
GeneralNames.schema({
names: {
blockName: (names.issuer || EMPTY_STRING)
}
}),
AlgorithmIdentifier.schema(names.signature || {}),
new asn1js.Integer({ name: (names.serialNumber || EMPTY_STRING) }),
AttCertValidityPeriod.schema(names.attrCertValidityPeriod || {}),
new asn1js.Sequence({
name: (names.attributes || EMPTY_STRING),
value: [
new asn1js.Repeated({
value: Attribute.schema()
})
]
}),
new asn1js.BitString({
optional: true,
name: (names.issuerUniqueID || EMPTY_STRING)
}),
Extensions.schema(names.extensions || {}, true)
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
//#region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AttributeCertificateInfoV1.schema({
names: {
version: VERSION,
baseCertificateID: BASE_CERTIFICATE_ID,
subjectName: SUBJECT_NAME,
issuer: ISSUER,
signature: {
names: {
blockName: SIGNATURE
}
},
serialNumber: SERIAL_NUMBER,
attrCertValidityPeriod: {
names: {
blockName: ATTR_CERT_VALIDITY_PERIOD
}
},
attributes: ATTRIBUTES,
issuerUniqueID: ISSUER_UNIQUE_ID,
extensions: {
names: {
blockName: EXTENSIONS
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
//#endregion
//#region Get internal properties from parsed schema
this.version = asn1.result.version.valueBlock.valueDec;
if (BASE_CERTIFICATE_ID in asn1.result) {
this.baseCertificateID = new IssuerSerial({
schema: new asn1js.Sequence({
value: asn1.result.baseCertificateID.valueBlock.value
})
});
}
if (SUBJECT_NAME in asn1.result) {
this.subjectName = new GeneralNames({
schema: new asn1js.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 in asn1.result) {
this.issuerUniqueID = asn1.result.issuerUniqueID;
}
if (EXTENSIONS in asn1.result) {
this.extensions = new Extensions({ schema: asn1.result.extensions });
}
//#endregion
}
public toSchema(): asn1js.Sequence {
const result = new asn1js.Sequence({
value: [new asn1js.Integer({ value: this.version })]
});
if (this.baseCertificateID) {
result.valueBlock.value.push(new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: this.baseCertificateID.toSchema().valueBlock.value
}));
}
if (this.subjectName) {
result.valueBlock.value.push(new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 1 // [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 asn1js.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;
}
public toJSON(): AttributeCertificateInfoV1Json {
const result = {
version: this.version
} as AttributeCertificateInfoV1Json;
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;
}
}

Просмотреть файл

@ -1,169 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "../AlgorithmIdentifier";
import { AttributeCertificateInfoV1, AttributeCertificateInfoV1Json, AttributeCertificateInfoV1Schema } from "./AttributeCertificateInfoV1";
import * as Schema from "../Schema";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import { AsnError } from "../errors";
import { EMPTY_STRING } from "../constants";
const ACINFO = "acinfo";
const SIGNATURE_ALGORITHM = "signatureAlgorithm";
const SIGNATURE_VALUE = "signatureValue";
const CLEAR_PROPS = [
ACINFO,
SIGNATURE_VALUE,
SIGNATURE_ALGORITHM
];
export interface IAttributeCertificateV1 {
/**
* Attribute certificate information
*/
acinfo: AttributeCertificateInfoV1;
/**
* Signature algorithm
*/
signatureAlgorithm: AlgorithmIdentifier;
/**
* Signature value
*/
signatureValue: asn1js.BitString;
}
export interface AttributeCertificateV1Json {
acinfo: AttributeCertificateInfoV1Json;
signatureAlgorithm: AlgorithmIdentifierJson;
signatureValue: asn1js.BitStringJson;
}
export type AttributeCertificateV1Parameters = PkiObjectParameters & Partial<IAttributeCertificateV1>;
/**
* Class from X.509:1997
*/
export class AttributeCertificateV1 extends PkiObject implements IAttributeCertificateV1 {
public static override CLASS_NAME = "AttributeCertificateV1";
public acinfo!: AttributeCertificateInfoV1;
public signatureAlgorithm!: AlgorithmIdentifier;
public signatureValue!: asn1js.BitString;
/**
* Initializes a new instance of the {@link AttributeCertificateV1} class
* @param parameters Initialization parameters
*/
constructor(parameters: AttributeCertificateV1Parameters = {}) {
super();
this.acinfo = pvutils.getParametersValue(parameters, ACINFO, AttributeCertificateV1.defaultValues(ACINFO));
this.signatureAlgorithm = pvutils.getParametersValue(parameters, SIGNATURE_ALGORITHM, AttributeCertificateV1.defaultValues(SIGNATURE_ALGORITHM));
this.signatureValue = pvutils.getParametersValue(parameters, SIGNATURE_VALUE, AttributeCertificateV1.defaultValues(SIGNATURE_VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ACINFO): AttributeCertificateInfoV1;
public static override defaultValues(memberName: typeof SIGNATURE_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SIGNATURE_VALUE): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ACINFO:
return new AttributeCertificateInfoV1();
case SIGNATURE_ALGORITHM:
return new AlgorithmIdentifier();
case SIGNATURE_VALUE:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AttributeCertificate ::= SEQUENCE {
* acinfo AttributeCertificateInfoV1,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
acinfo?: AttributeCertificateInfoV1Schema;
signatureAlgorithm?: AlgorithmIdentifierSchema;
signatureValue?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AttributeCertificateInfoV1.schema(names.acinfo || {}),
AlgorithmIdentifier.schema(names.signatureAlgorithm || {}),
new asn1js.BitString({ name: (names.signatureValue || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
//#region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AttributeCertificateV1.schema({
names: {
acinfo: {
names: {
blockName: ACINFO
}
},
signatureAlgorithm: {
names: {
blockName: SIGNATURE_ALGORITHM
}
},
signatureValue: SIGNATURE_VALUE
}
})
);
AsnError.assertSchema(asn1, this.className);
//#endregion
//#region Get internal properties from parsed schema
this.acinfo = new AttributeCertificateInfoV1({ schema: asn1.result.acinfo });
this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm });
this.signatureValue = asn1.result.signatureValue;
//#endregion
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: [
this.acinfo.toSchema(),
this.signatureAlgorithm.toSchema(),
this.signatureValue
]
}));
}
public toJSON(): AttributeCertificateV1Json {
return {
acinfo: this.acinfo.toJSON(),
signatureAlgorithm: this.signatureAlgorithm.toJSON(),
signatureValue: this.signatureValue.toJSON(),
};
}
}

Просмотреть файл

@ -1,183 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "../constants";
import { AsnError } from "../errors";
import { GeneralNames, GeneralNamesJson, GeneralNamesSchema } from "../GeneralNames";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import * as Schema from "../Schema";
const ISSUER = "issuer";
const SERIAL_NUMBER = "serialNumber";
const ISSUER_UID = "issuerUID";
const CLEAR_PROPS = [
ISSUER,
SERIAL_NUMBER,
ISSUER_UID,
];
export interface IIssuerSerial {
/**
* Issuer name
*/
issuer: GeneralNames;
/**
* Serial number
*/
serialNumber: asn1js.Integer;
/**
* Issuer unique identifier
*/
issuerUID?: asn1js.BitString;
}
export type IssuerSerialParameters = PkiObjectParameters & Partial<IIssuerSerial>;
export interface IssuerSerialJson {
issuer: GeneralNamesJson;
serialNumber: asn1js.IntegerJson;
issuerUID?: asn1js.BitStringJson;
}
/**
* Represents the IssuerSerial structure described in [RFC5755](https://datatracker.ietf.org/doc/html/rfc5755)
*/
export class IssuerSerial extends PkiObject implements IIssuerSerial {
public static override CLASS_NAME = "IssuerSerial";
public issuer!: GeneralNames;
public serialNumber!: asn1js.Integer;
public issuerUID?: asn1js.BitString;
/**
* Initializes a new instance of the {@link IssuerSerial} class
* @param parameters Initialization parameters
*/
constructor(parameters: IssuerSerialParameters = {}) {
super();
this.issuer = pvutils.getParametersValue(parameters, ISSUER, IssuerSerial.defaultValues(ISSUER));
this.serialNumber = pvutils.getParametersValue(parameters, SERIAL_NUMBER, IssuerSerial.defaultValues(SERIAL_NUMBER));
if (ISSUER_UID in parameters) {
this.issuerUID = pvutils.getParametersValue(parameters, ISSUER_UID, IssuerSerial.defaultValues(ISSUER_UID));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ISSUER): GeneralNames;
public static override defaultValues(memberName: typeof SERIAL_NUMBER): asn1js.Integer;
public static override defaultValues(memberName: typeof ISSUER_UID): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ISSUER:
return new GeneralNames();
case SERIAL_NUMBER:
return new asn1js.Integer();
case ISSUER_UID:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* IssuerSerial ::= SEQUENCE {
* issuer GeneralNames,
* serial CertificateSerialNumber,
* issuerUID UniqueIdentifier OPTIONAL
* }
*
* CertificateSerialNumber ::= INTEGER
* UniqueIdentifier ::= BIT STRING
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
issuer?: GeneralNamesSchema;
serialNumber?: string;
issuerUID?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
GeneralNames.schema(names.issuer || {}),
new asn1js.Integer({ name: (names.serialNumber || EMPTY_STRING) }),
new asn1js.BitString({
optional: true,
name: (names.issuerUID || EMPTY_STRING)
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
//#region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
IssuerSerial.schema({
names: {
issuer: {
names: {
blockName: ISSUER
}
},
serialNumber: SERIAL_NUMBER,
issuerUID: ISSUER_UID
}
})
);
AsnError.assertSchema(asn1, this.className);
//#endregion
//#region Get internal properties from parsed schema
this.issuer = new GeneralNames({ schema: asn1.result.issuer });
this.serialNumber = asn1.result.serialNumber;
if (ISSUER_UID in asn1.result)
this.issuerUID = asn1.result.issuerUID;
//#endregion
}
public toSchema(): asn1js.Sequence {
const result = new asn1js.Sequence({
value: [
this.issuer.toSchema(),
this.serialNumber
]
});
if (this.issuerUID) {
result.valueBlock.value.push(this.issuerUID);
}
return result;
}
public toJSON(): IssuerSerialJson {
const result = {
issuer: this.issuer.toJSON(),
serialNumber: this.serialNumber.toJSON()
} as IssuerSerialJson;
if (this.issuerUID) {
result.issuerUID = this.issuerUID.toJSON();
}
return result;
}
}

Просмотреть файл

@ -1,4 +0,0 @@
export * from "./AttCertValidityPeriod";
export * from "./AttributeCertificateInfoV1";
export * from "./AttributeCertificateV1";
export * from "./IssuerSerial";

Просмотреть файл

@ -1,341 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { GeneralNames, GeneralNamesJson } from "../GeneralNames";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "../AlgorithmIdentifier";
import { Attribute, AttributeJson } from "../Attribute";
import { Extensions, ExtensionsJson, ExtensionsSchema } from "../Extensions";
import { AttCertValidityPeriod, AttCertValidityPeriodJson, AttCertValidityPeriodSchema } from "../AttributeCertificateV1";
import { V2Form, V2FormJson } from "./V2Form";
import { Holder, HolderJson, HolderSchema } from "./Holder";
import * as Schema from "../Schema";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import { AsnError } from "../errors";
import { EMPTY_STRING } from "../constants";
const VERSION = "version";
const HOLDER = "holder";
const ISSUER = "issuer";
const SIGNATURE = "signature";
const SERIAL_NUMBER = "serialNumber";
const ATTR_CERT_VALIDITY_PERIOD = "attrCertValidityPeriod";
const ATTRIBUTES = "attributes";
const ISSUER_UNIQUE_ID = "issuerUniqueID";
const EXTENSIONS = "extensions";
const CLEAR_PROPS = [
VERSION,
HOLDER,
ISSUER,
SIGNATURE,
SERIAL_NUMBER,
ATTR_CERT_VALIDITY_PERIOD,
ATTRIBUTES,
ISSUER_UNIQUE_ID,
EXTENSIONS
];
export interface IAttributeCertificateInfoV2 {
version: number;
holder: Holder;
issuer: GeneralNames | V2Form;
signature: AlgorithmIdentifier;
serialNumber: asn1js.Integer;
attrCertValidityPeriod: AttCertValidityPeriod;
attributes: Attribute[];
issuerUniqueID?: asn1js.BitString;
extensions?: Extensions;
}
export type AttributeCertificateInfoV2Parameters = PkiObjectParameters & Partial<AttributeCertificateInfoV2>;
export type AttributeCertificateInfoV2Schema = Schema.SchemaParameters<{
version?: string;
holder?: HolderSchema;
issuer?: string;
signature?: AlgorithmIdentifierSchema;
serialNumber?: string;
attrCertValidityPeriod?: AttCertValidityPeriodSchema;
attributes?: string;
issuerUniqueID?: string;
extensions?: ExtensionsSchema;
}>;
export interface AttributeCertificateInfoV2Json {
version: number;
holder: HolderJson;
issuer: GeneralNamesJson | V2FormJson;
signature: AlgorithmIdentifierJson;
serialNumber: asn1js.IntegerJson;
attrCertValidityPeriod: AttCertValidityPeriodJson;
attributes: AttributeJson[];
issuerUniqueID?: asn1js.BitStringJson;
extensions?: ExtensionsJson;
}
/**
* Represents the AttributeCertificateInfoV2 structure described in [RFC5755](https://datatracker.ietf.org/doc/html/rfc5755)
*/
export class AttributeCertificateInfoV2 extends PkiObject implements IAttributeCertificateInfoV2 {
public static override CLASS_NAME = "AttributeCertificateInfoV2";
public version!: number;
public holder!: Holder;
public issuer!: GeneralNames | V2Form;
public signature!: AlgorithmIdentifier;
public serialNumber!: asn1js.Integer;
public attrCertValidityPeriod!: AttCertValidityPeriod;
public attributes!: Attribute[];
public issuerUniqueID?: asn1js.BitString;
public extensions?: Extensions;
/**
* Initializes a new instance of the {@link AttributeCertificateInfoV2} class
* @param parameters Initialization parameters
*/
constructor(parameters: AttributeCertificateInfoV2Parameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, AttributeCertificateInfoV2.defaultValues(VERSION));
this.holder = pvutils.getParametersValue(parameters, HOLDER, AttributeCertificateInfoV2.defaultValues(HOLDER));
this.issuer = pvutils.getParametersValue(parameters, ISSUER, AttributeCertificateInfoV2.defaultValues(ISSUER));
this.signature = pvutils.getParametersValue(parameters, SIGNATURE, AttributeCertificateInfoV2.defaultValues(SIGNATURE));
this.serialNumber = pvutils.getParametersValue(parameters, SERIAL_NUMBER, AttributeCertificateInfoV2.defaultValues(SERIAL_NUMBER));
this.attrCertValidityPeriod = pvutils.getParametersValue(parameters, ATTR_CERT_VALIDITY_PERIOD, AttributeCertificateInfoV2.defaultValues(ATTR_CERT_VALIDITY_PERIOD));
this.attributes = pvutils.getParametersValue(parameters, ATTRIBUTES, AttributeCertificateInfoV2.defaultValues(ATTRIBUTES));
if (ISSUER_UNIQUE_ID in parameters) {
this.issuerUniqueID = pvutils.getParametersValue(parameters, ISSUER_UNIQUE_ID, AttributeCertificateInfoV2.defaultValues(ISSUER_UNIQUE_ID));
}
if (EXTENSIONS in parameters) {
this.extensions = pvutils.getParametersValue(parameters, EXTENSIONS, AttributeCertificateInfoV2.defaultValues(EXTENSIONS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof HOLDER): Holder;
public static override defaultValues(memberName: typeof ISSUER): GeneralNames | V2Form;
public static override defaultValues(memberName: typeof SIGNATURE): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SERIAL_NUMBER): asn1js.Integer;
public static override defaultValues(memberName: typeof ATTR_CERT_VALIDITY_PERIOD): AttCertValidityPeriod;
public static override defaultValues(memberName: typeof ATTRIBUTES): Attribute[];
public static override defaultValues(memberName: typeof ISSUER_UNIQUE_ID): asn1js.BitString;
public static override defaultValues(memberName: typeof EXTENSIONS): Extensions;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return 1;
case HOLDER:
return new Holder();
case ISSUER:
return {};
case SIGNATURE:
return new AlgorithmIdentifier();
case SERIAL_NUMBER:
return new asn1js.Integer();
case ATTR_CERT_VALIDITY_PERIOD:
return new AttCertValidityPeriod();
case ATTRIBUTES:
return [];
case ISSUER_UNIQUE_ID:
return new asn1js.BitString();
case EXTENSIONS:
return new Extensions();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AttributeCertificateInfoV2 ::= SEQUENCE {
* version AttCertVersion, -- version is v2
* holder Holder,
* issuer AttCertIssuer,
* signature AlgorithmIdentifier,
* serialNumber CertificateSerialNumber,
* attrCertValidityPeriod AttCertValidityPeriod,
* attributes SEQUENCE OF Attribute,
* issuerUniqueID UniqueIdentifier OPTIONAL,
* extensions Extensions OPTIONAL
* }
*```
*/
public static override schema(parameters: AttributeCertificateInfoV2Schema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || EMPTY_STRING) }),
Holder.schema(names.holder || {}),
new asn1js.Choice({
value: [
GeneralNames.schema({
names: {
blockName: (names.issuer || EMPTY_STRING)
}
}),
new asn1js.Constructed({
name: (names.issuer || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: V2Form.schema().valueBlock.value
})
]
}),
AlgorithmIdentifier.schema(names.signature || {}),
new asn1js.Integer({ name: (names.serialNumber || EMPTY_STRING) }),
AttCertValidityPeriod.schema(names.attrCertValidityPeriod || {}),
new asn1js.Sequence({
name: (names.attributes || EMPTY_STRING),
value: [
new asn1js.Repeated({
value: Attribute.schema()
})
]
}),
new asn1js.BitString({
optional: true,
name: (names.issuerUniqueID || EMPTY_STRING)
}),
Extensions.schema(names.extensions || {}, true)
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AttributeCertificateInfoV2.schema({
names: {
version: VERSION,
holder: {
names: {
blockName: HOLDER
}
},
issuer: ISSUER,
signature: {
names: {
blockName: SIGNATURE
}
},
serialNumber: SERIAL_NUMBER,
attrCertValidityPeriod: {
names: {
blockName: ATTR_CERT_VALIDITY_PERIOD
}
},
attributes: ATTRIBUTES,
issuerUniqueID: ISSUER_UNIQUE_ID,
extensions: {
names: {
blockName: EXTENSIONS
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
this.version = asn1.result.version.valueBlock.valueDec;
this.holder = new Holder({ schema: asn1.result.holder });
switch (asn1.result.issuer.idBlock.tagClass) {
case 3: // V2Form
this.issuer = new V2Form({
schema: new asn1js.Sequence({
value: asn1.result.issuer.valueBlock.value
})
});
break;
case 1: // GeneralNames (should not be used)
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 in asn1.result) {
this.issuerUniqueID = asn1.result.issuerUniqueID;
}
if (EXTENSIONS in asn1.result) {
this.extensions = new Extensions({ schema: asn1.result.extensions });
}
//#endregion
}
public toSchema(): asn1js.Sequence {
const result = new asn1js.Sequence({
value: [
new asn1js.Integer({ value: this.version }),
this.holder.toSchema(),
new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: this.issuer.toSchema().valueBlock.value
}),
this.signature.toSchema(),
this.serialNumber,
this.attrCertValidityPeriod.toSchema(),
new asn1js.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;
}
public toJSON(): AttributeCertificateInfoV2Json {
const result: AttributeCertificateInfoV2Json = {
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;
}
}

Просмотреть файл

@ -1,169 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "../AlgorithmIdentifier";
import { AttributeCertificateInfoV2, AttributeCertificateInfoV2Json, AttributeCertificateInfoV2Schema } from "./AttributeCertificateInfoV2";
import * as Schema from "../Schema";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import { AsnError } from "../errors";
import { EMPTY_STRING } from "../constants";
const ACINFO = "acinfo";
const SIGNATURE_ALGORITHM = "signatureAlgorithm";
const SIGNATURE_VALUE = "signatureValue";
const CLEAR_PROPS = [
ACINFO,
SIGNATURE_ALGORITHM,
SIGNATURE_VALUE,
];
export interface IAttributeCertificateV2 {
/**
* Attribute certificate information
*/
acinfo: AttributeCertificateInfoV2;
/**
* Signature algorithm
*/
signatureAlgorithm: AlgorithmIdentifier;
/**
* Signature value
*/
signatureValue: asn1js.BitString;
}
export type AttributeCertificateV2Parameters = PkiObjectParameters & Partial<IAttributeCertificateV2>;
export interface AttributeCertificateV2Json {
acinfo: AttributeCertificateInfoV2Json;
signatureAlgorithm: AlgorithmIdentifierJson;
signatureValue: asn1js.BitStringJson;
}
/**
* Represents the AttributeCertificateV2 structure described in [RFC5755](https://datatracker.ietf.org/doc/html/rfc5755)
*/
export class AttributeCertificateV2 extends PkiObject implements IAttributeCertificateV2 {
public static override CLASS_NAME = "AttributeCertificateV2";
public acinfo!: AttributeCertificateInfoV2;
public signatureAlgorithm!: AlgorithmIdentifier;
public signatureValue!: asn1js.BitString;
/**
* Initializes a new instance of the {@link AttributeCertificateV2} class
* @param parameters Initialization parameters
*/
constructor(parameters: AttributeCertificateV2Parameters = {}) {
super();
this.acinfo = pvutils.getParametersValue(parameters, ACINFO, AttributeCertificateV2.defaultValues(ACINFO));
this.signatureAlgorithm = pvutils.getParametersValue(parameters, SIGNATURE_ALGORITHM, AttributeCertificateV2.defaultValues(SIGNATURE_ALGORITHM));
this.signatureValue = pvutils.getParametersValue(parameters, SIGNATURE_VALUE, AttributeCertificateV2.defaultValues(SIGNATURE_VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ACINFO): AttributeCertificateInfoV2;
public static override defaultValues(memberName: typeof SIGNATURE_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SIGNATURE_VALUE): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ACINFO:
return new AttributeCertificateInfoV2();
case SIGNATURE_ALGORITHM:
return new AlgorithmIdentifier();
case SIGNATURE_VALUE:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AttributeCertificate ::= SEQUENCE {
* acinfo AttributeCertificateInfoV2,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
acinfo?: AttributeCertificateInfoV2Schema;
signatureAlgorithm?: AlgorithmIdentifierSchema;
signatureValue?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AttributeCertificateInfoV2.schema(names.acinfo || {}),
AlgorithmIdentifier.schema(names.signatureAlgorithm || {}),
new asn1js.BitString({ name: (names.signatureValue || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
//#region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AttributeCertificateV2.schema({
names: {
acinfo: {
names: {
blockName: ACINFO
}
},
signatureAlgorithm: {
names: {
blockName: SIGNATURE_ALGORITHM
}
},
signatureValue: SIGNATURE_VALUE
}
})
);
AsnError.assertSchema(asn1, this.className);
//#endregion
// Get internal properties from parsed schema
this.acinfo = new AttributeCertificateInfoV2({ schema: asn1.result.acinfo });
this.signatureAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.signatureAlgorithm });
this.signatureValue = asn1.result.signatureValue;
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: [
this.acinfo.toSchema(),
this.signatureAlgorithm.toSchema(),
this.signatureValue
]
}));
}
public toJSON(): AttributeCertificateV2Json {
return {
acinfo: this.acinfo.toJSON(),
signatureAlgorithm: this.signatureAlgorithm.toJSON(),
signatureValue: this.signatureValue.toJSON(),
};
}
}

Просмотреть файл

@ -1,242 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { GeneralNames, GeneralNamesJson } from "../GeneralNames";
import { IssuerSerial, IssuerSerialJson } from "../AttributeCertificateV1";
import { ObjectDigestInfo, ObjectDigestInfoJson } from "./ObjectDigestInfo";
import * as Schema from "../Schema";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import { AsnError } from "../errors";
import { EMPTY_STRING } from "../constants";
const BASE_CERTIFICATE_ID = "baseCertificateID";
const ENTITY_NAME = "entityName";
const OBJECT_DIGEST_INFO = "objectDigestInfo";
const CLEAR_PROPS = [
BASE_CERTIFICATE_ID,
ENTITY_NAME,
OBJECT_DIGEST_INFO
];
export interface IHolder {
baseCertificateID?: IssuerSerial;
entityName?: GeneralNames;
objectDigestInfo?: ObjectDigestInfo;
}
export type HolderParameters = PkiObjectParameters & Partial<IHolder>;
export type HolderSchema = Schema.SchemaParameters<{
baseCertificateID?: string;
entityName?: string;
objectDigestInfo?: string;
}>;
export interface HolderJson {
baseCertificateID?: IssuerSerialJson;
entityName?: GeneralNamesJson;
objectDigestInfo?: ObjectDigestInfoJson;
}
/**
* Represents the Holder structure described in [RFC5755](https://datatracker.ietf.org/doc/html/rfc5755)
*/
export class Holder extends PkiObject implements IHolder {
public static override CLASS_NAME = "Holder";
public baseCertificateID?: IssuerSerial;
public entityName?: GeneralNames;
public objectDigestInfo?: ObjectDigestInfo;
/**
* Initializes a new instance of the {@link AttributeCertificateInfoV1} class
* @param parameters Initialization parameters
*/
constructor(parameters: HolderParameters = {}) {
super();
if (BASE_CERTIFICATE_ID in parameters) {
this.baseCertificateID = pvutils.getParametersValue(parameters, BASE_CERTIFICATE_ID, Holder.defaultValues(BASE_CERTIFICATE_ID));
}
if (ENTITY_NAME in parameters) {
this.entityName = pvutils.getParametersValue(parameters, ENTITY_NAME, Holder.defaultValues(ENTITY_NAME));
}
if (OBJECT_DIGEST_INFO in parameters) {
this.objectDigestInfo = pvutils.getParametersValue(parameters, OBJECT_DIGEST_INFO, Holder.defaultValues(OBJECT_DIGEST_INFO));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof BASE_CERTIFICATE_ID): IssuerSerial;
public static override defaultValues(memberName: typeof ENTITY_NAME): GeneralNames;
public static override defaultValues(memberName: typeof OBJECT_DIGEST_INFO): ObjectDigestInfo;
public static override defaultValues(memberName: string): any {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* Holder ::= SEQUENCE {
* baseCertificateID [0] IssuerSerial OPTIONAL,
* -- the issuer and serial number of
* -- the holder's Public Key Certificate
* entityName [1] GeneralNames OPTIONAL,
* -- the name of the claimant or role
* objectDigestInfo [2] ObjectDigestInfo OPTIONAL
* -- used to directly authenticate the holder,
* -- for example, an executable
* }
*```
*/
public static override schema(parameters: HolderSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Constructed({
optional: true,
name: (names.baseCertificateID || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: IssuerSerial.schema().valueBlock.value
}),
new asn1js.Constructed({
optional: true,
name: (names.entityName || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 1 // [2]
},
value: GeneralNames.schema().valueBlock.value
}),
new asn1js.Constructed({
optional: true,
name: (names.objectDigestInfo || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 2 // [2]
},
value: ObjectDigestInfo.schema().valueBlock.value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
Holder.schema({
names: {
baseCertificateID: BASE_CERTIFICATE_ID,
entityName: ENTITY_NAME,
objectDigestInfo: OBJECT_DIGEST_INFO
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
if (BASE_CERTIFICATE_ID in asn1.result) {
this.baseCertificateID = new IssuerSerial({
schema: new asn1js.Sequence({
value: asn1.result.baseCertificateID.valueBlock.value
})
});
}
if (ENTITY_NAME in asn1.result) {
this.entityName = new GeneralNames({
schema: new asn1js.Sequence({
value: asn1.result.entityName.valueBlock.value
})
});
}
if (OBJECT_DIGEST_INFO in asn1.result) {
this.objectDigestInfo = new ObjectDigestInfo({
schema: new asn1js.Sequence({
value: asn1.result.objectDigestInfo.valueBlock.value
})
});
}
}
public toSchema(): asn1js.Sequence {
const result = new asn1js.Sequence();
if (this.baseCertificateID) {
result.valueBlock.value.push(new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: this.baseCertificateID.toSchema().valueBlock.value
}));
}
if (this.entityName) {
result.valueBlock.value.push(new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 1 // [1]
},
value: this.entityName.toSchema().valueBlock.value
}));
}
if (this.objectDigestInfo) {
result.valueBlock.value.push(new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 2 // [2]
},
value: this.objectDigestInfo.toSchema().valueBlock.value
}));
}
return result;
}
public toJSON(): HolderJson {
const result: HolderJson = {};
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;
}
}

Просмотреть файл

@ -1,193 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "../AlgorithmIdentifier";
import { EMPTY_STRING } from "../constants";
import { AsnError } from "../errors";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import * as Schema from "../Schema";
const DIGESTED_OBJECT_TYPE = "digestedObjectType";
const OTHER_OBJECT_TYPE_ID = "otherObjectTypeID";
const DIGEST_ALGORITHM = "digestAlgorithm";
const OBJECT_DIGEST = "objectDigest";
const CLEAR_PROPS = [
DIGESTED_OBJECT_TYPE,
OTHER_OBJECT_TYPE_ID,
DIGEST_ALGORITHM,
OBJECT_DIGEST,
];
export interface IObjectDigestInfo {
digestedObjectType: asn1js.Enumerated;
otherObjectTypeID?: asn1js.ObjectIdentifier;
digestAlgorithm: AlgorithmIdentifier;
objectDigest: asn1js.BitString;
}
export type ObjectDigestInfoParameters = PkiObjectParameters & Partial<IObjectDigestInfo>;
export interface ObjectDigestInfoJson {
digestedObjectType: asn1js.EnumeratedJson;
otherObjectTypeID?: asn1js.ObjectIdentifierJson;
digestAlgorithm: AlgorithmIdentifierJson;
objectDigest: asn1js.BitStringJson;
}
/**
* Represents the ObjectDigestInfo structure described in [RFC5755](https://datatracker.ietf.org/doc/html/rfc5755)
*/
export class ObjectDigestInfo extends PkiObject implements IObjectDigestInfo {
public static override CLASS_NAME = "ObjectDigestInfo";
public digestedObjectType!: asn1js.Enumerated;
public otherObjectTypeID?: asn1js.ObjectIdentifier;
public digestAlgorithm!: AlgorithmIdentifier;
public objectDigest!: asn1js.BitString;
/**
* Initializes a new instance of the {@link ObjectDigestInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: ObjectDigestInfoParameters = {}) {
super();
this.digestedObjectType = pvutils.getParametersValue(parameters, DIGESTED_OBJECT_TYPE, ObjectDigestInfo.defaultValues(DIGESTED_OBJECT_TYPE));
if (OTHER_OBJECT_TYPE_ID in parameters) {
this.otherObjectTypeID = pvutils.getParametersValue(parameters, OTHER_OBJECT_TYPE_ID, ObjectDigestInfo.defaultValues(OTHER_OBJECT_TYPE_ID));
}
this.digestAlgorithm = pvutils.getParametersValue(parameters, DIGEST_ALGORITHM, ObjectDigestInfo.defaultValues(DIGEST_ALGORITHM));
this.objectDigest = pvutils.getParametersValue(parameters, OBJECT_DIGEST, ObjectDigestInfo.defaultValues(OBJECT_DIGEST));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof DIGESTED_OBJECT_TYPE): asn1js.Enumerated;
public static override defaultValues(memberName: typeof OTHER_OBJECT_TYPE_ID): asn1js.ObjectIdentifier;
public static override defaultValues(memberName: typeof DIGEST_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof OBJECT_DIGEST): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case DIGESTED_OBJECT_TYPE:
return new asn1js.Enumerated();
case OTHER_OBJECT_TYPE_ID:
return new asn1js.ObjectIdentifier();
case DIGEST_ALGORITHM:
return new AlgorithmIdentifier();
case OBJECT_DIGEST:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* ObjectDigestInfo ::= SEQUENCE {
* digestedObjectType ENUMERATED {
* publicKey (0),
* publicKeyCert (1),
* otherObjectTypes (2) },
* -- otherObjectTypes MUST NOT
* -- be used in this profile
* otherObjectTypeID OBJECT IDENTIFIER OPTIONAL,
* digestAlgorithm AlgorithmIdentifier,
* objectDigest BIT STRING
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
digestedObjectType?: string;
otherObjectTypeID?: string;
digestAlgorithm?: AlgorithmIdentifierSchema;
objectDigest?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Enumerated({ name: (names.digestedObjectType || EMPTY_STRING) }),
new asn1js.ObjectIdentifier({
optional: true,
name: (names.otherObjectTypeID || EMPTY_STRING)
}),
AlgorithmIdentifier.schema(names.digestAlgorithm || {}),
new asn1js.BitString({ name: (names.objectDigest || EMPTY_STRING) }),
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
ObjectDigestInfo.schema({
names: {
digestedObjectType: DIGESTED_OBJECT_TYPE,
otherObjectTypeID: OTHER_OBJECT_TYPE_ID,
digestAlgorithm: {
names: {
blockName: DIGEST_ALGORITHM
}
},
objectDigest: OBJECT_DIGEST
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
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;
//#endregion
}
public toSchema(): asn1js.Sequence {
const result = new asn1js.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;
}
public toJSON(): ObjectDigestInfoJson {
const result: ObjectDigestInfoJson = {
digestedObjectType: this.digestedObjectType.toJSON(),
digestAlgorithm: this.digestAlgorithm.toJSON(),
objectDigest: this.objectDigest.toJSON(),
};
if (this.otherObjectTypeID) {
result.otherObjectTypeID = this.otherObjectTypeID.toJSON();
}
return result;
}
}

Просмотреть файл

@ -1,223 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { GeneralNames, GeneralNamesJson } from "../GeneralNames";
import { IssuerSerial, IssuerSerialJson } from "../AttributeCertificateV1";
import { ObjectDigestInfo, ObjectDigestInfoJson } from "./ObjectDigestInfo";
import * as Schema from "../Schema";
import { PkiObject, PkiObjectParameters } from "../PkiObject";
import { AsnError } from "../errors";
import { EMPTY_STRING } from "../constants";
const ISSUER_NAME = "issuerName";
const BASE_CERTIFICATE_ID = "baseCertificateID";
const OBJECT_DIGEST_INFO = "objectDigestInfo";
const CLEAR_PROPS = [
ISSUER_NAME,
BASE_CERTIFICATE_ID,
OBJECT_DIGEST_INFO
];
export interface IV2Form {
issuerName?: GeneralNames;
baseCertificateID?: IssuerSerial;
objectDigestInfo?: ObjectDigestInfo;
}
export type V2FormParameters = PkiObjectParameters & Partial<IV2Form>;
export interface V2FormJson {
issuerName?: GeneralNamesJson;
baseCertificateID?: IssuerSerialJson;
objectDigestInfo?: ObjectDigestInfoJson;
}
/**
* Represents the V2Form structure described in [RFC5755](https://datatracker.ietf.org/doc/html/rfc5755)
*/
export class V2Form extends PkiObject implements IV2Form {
public static override CLASS_NAME = "V2Form";
public issuerName?: GeneralNames;
public baseCertificateID?: IssuerSerial;
public objectDigestInfo?: ObjectDigestInfo;
/**
* Initializes a new instance of the {@link V2Form} class
* @param parameters Initialization parameters
*/
constructor(parameters: V2FormParameters = {}) {
super();
if (ISSUER_NAME in parameters) {
this.issuerName = pvutils.getParametersValue(parameters, ISSUER_NAME, V2Form.defaultValues(ISSUER_NAME));
}
if (BASE_CERTIFICATE_ID in parameters) {
this.baseCertificateID = pvutils.getParametersValue(parameters, BASE_CERTIFICATE_ID, V2Form.defaultValues(BASE_CERTIFICATE_ID));
}
if (OBJECT_DIGEST_INFO in parameters) {
this.objectDigestInfo = pvutils.getParametersValue(parameters, OBJECT_DIGEST_INFO, V2Form.defaultValues(OBJECT_DIGEST_INFO));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ISSUER_NAME): GeneralNames;
public static override defaultValues(memberName: typeof BASE_CERTIFICATE_ID): IssuerSerial;
public static override defaultValues(memberName: typeof OBJECT_DIGEST_INFO): ObjectDigestInfo;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ISSUER_NAME:
return new GeneralNames();
case BASE_CERTIFICATE_ID:
return new IssuerSerial();
case OBJECT_DIGEST_INFO:
return new ObjectDigestInfo();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* V2Form ::= SEQUENCE {
* issuerName GeneralNames OPTIONAL,
* baseCertificateID [0] IssuerSerial OPTIONAL,
* objectDigestInfo [1] ObjectDigestInfo OPTIONAL
* -- issuerName MUST be present in this profile
* -- baseCertificateID and objectDigestInfo MUST NOT
* -- be present in this profile
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
issuerName?: string;
baseCertificateID?: string;
objectDigestInfo?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
GeneralNames.schema({
names: {
blockName: names.issuerName
}
}, true),
new asn1js.Constructed({
optional: true,
name: (names.baseCertificateID || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: IssuerSerial.schema().valueBlock.value
}),
new asn1js.Constructed({
optional: true,
name: (names.objectDigestInfo || EMPTY_STRING),
idBlock: {
tagClass: 3,
tagNumber: 1 // [1]
},
value: ObjectDigestInfo.schema().valueBlock.value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
V2Form.schema({
names: {
issuerName: ISSUER_NAME,
baseCertificateID: BASE_CERTIFICATE_ID,
objectDigestInfo: OBJECT_DIGEST_INFO
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
if (ISSUER_NAME in asn1.result)
this.issuerName = new GeneralNames({ schema: asn1.result.issuerName });
if (BASE_CERTIFICATE_ID in asn1.result) {
this.baseCertificateID = new IssuerSerial({
schema: new asn1js.Sequence({
value: asn1.result.baseCertificateID.valueBlock.value
})
});
}
if (OBJECT_DIGEST_INFO in asn1.result) {
this.objectDigestInfo = new ObjectDigestInfo({
schema: new asn1js.Sequence({
value: asn1.result.objectDigestInfo.valueBlock.value
})
});
}
//#endregion
}
public toSchema(): asn1js.Sequence {
const result = new asn1js.Sequence();
if (this.issuerName)
result.valueBlock.value.push(this.issuerName.toSchema());
if (this.baseCertificateID) {
result.valueBlock.value.push(new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 0 // [0]
},
value: this.baseCertificateID.toSchema().valueBlock.value
}));
}
if (this.objectDigestInfo) {
result.valueBlock.value.push(new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 1 // [1]
},
value: this.objectDigestInfo.toSchema().valueBlock.value
}));
}
return result;
}
public toJSON(): V2FormJson {
const result: V2FormJson = {};
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;
}
}

Просмотреть файл

@ -1,5 +0,0 @@
export * from "./AttributeCertificateInfoV2";
export * from "./Holder";
export * from "./ObjectDigestInfo";
export * from "./V2Form";
export * from "./AttributeCertificateV2";

Просмотреть файл

@ -1,225 +0,0 @@
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { stringPrep } from "./Helpers";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const TYPE = "type";
const VALUE = "value";
export interface IAttributeTypeAndValue {
type: string;
value: AttributeValueType;
}
export type AttributeTypeAndValueParameters = PkiObjectParameters & Partial<IAttributeTypeAndValue>;
export type AttributeValueType = asn1js.Utf8String
| asn1js.BmpString
| asn1js.UniversalString
| asn1js.NumericString
| asn1js.PrintableString
| asn1js.TeletexString
| asn1js.VideotexString
| asn1js.IA5String
| asn1js.GraphicString
| asn1js.VisibleString
| asn1js.GeneralString
| asn1js.CharacterString;
export interface AttributeTypeAndValueJson {
type: string;
value: any;
}
/**
* Represents the AttributeTypeAndValue structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class AttributeTypeAndValue extends PkiObject implements IAttributeTypeAndValue {
public static override CLASS_NAME = "AttributeTypeAndValue";
public type!: string;
public value!: AttributeValueType;
/**
* Initializes a new instance of the {@link AttributeTypeAndValue} class
* @param parameters Initialization parameters
*/
constructor(parameters: AttributeTypeAndValueParameters = {}) {
super();
this.type = pvutils.getParametersValue(parameters, TYPE, AttributeTypeAndValue.defaultValues(TYPE));
this.value = pvutils.getParametersValue(parameters, VALUE, AttributeTypeAndValue.defaultValues(VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TYPE): string;
public static override defaultValues(memberName: typeof VALUE): AttributeValueType;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TYPE:
return EMPTY_STRING;
case VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AttributeTypeAndValue ::= Sequence {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY -- DEFINED BY AttributeType
*```
*/
static override schema(parameters: Schema.SchemaParameters<{ type?: string, value?: string; }> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.type || EMPTY_STRING) }),
new asn1js.Any({ name: (names.value || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType) {
//#region Clear input data first
pvutils.clearProps(schema, [
TYPE,
"typeValue"
]);
//#endregion
//#region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AttributeTypeAndValue.schema({
names: {
type: TYPE,
value: "typeValue"
}
})
);
AsnError.assertSchema(asn1, this.className);
//#endregion
//#region Get internal properties from parsed schema
this.type = asn1.result.type.valueBlock.toString();
this.value = asn1.result.typeValue;
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.type }),
this.value
]
}));
//#endregion
}
public toJSON(): AttributeTypeAndValueJson {
const _object = {
type: this.type
} as AttributeTypeAndValueJson;
if (Object.keys(this.value).length !== 0) {
_object.value = (this.value).toJSON();
} else {
_object.value = this.value;
}
return _object;
}
/**
* Compares two AttributeTypeAndValue values, or AttributeTypeAndValue with ArrayBuffer value
* @param compareTo The value compare to current
*/
public isEqual(compareTo: AttributeTypeAndValue | ArrayBuffer): boolean {
const stringBlockNames = [
asn1js.Utf8String.blockName(),
asn1js.BmpString.blockName(),
asn1js.UniversalString.blockName(),
asn1js.NumericString.blockName(),
asn1js.PrintableString.blockName(),
asn1js.TeletexString.blockName(),
asn1js.VideotexString.blockName(),
asn1js.IA5String.blockName(),
asn1js.GraphicString.blockName(),
asn1js.VisibleString.blockName(),
asn1js.GeneralString.blockName(),
asn1js.CharacterString.blockName()
];
if (compareTo instanceof ArrayBuffer) {
return pvtsutils.BufferSourceConverter.isEqual(this.value.valueBeforeDecodeView, compareTo);
}
if ((compareTo.constructor as typeof AttributeTypeAndValue).blockName() === AttributeTypeAndValue.blockName()) {
if (this.type !== compareTo.type)
return false;
//#region Check we do have both strings
const isStringPair = [false, false];
const thisName = (this.value.constructor as typeof asn1js.BaseBlock).blockName();
for (const name of stringBlockNames) {
if (thisName === name) {
isStringPair[0] = true;
}
if ((compareTo.value.constructor as typeof asn1js.BaseBlock).blockName() === name) {
isStringPair[1] = true;
}
}
if (isStringPair[0] !== isStringPair[1]) {
return false;
}
const isString = (isStringPair[0] && isStringPair[1]);
//#endregion
if (isString) {
const value1 = stringPrep(this.value.valueBlock.value);
const value2 = stringPrep(compareTo.value.valueBlock.value);
if (value1.localeCompare(value2) !== 0)
return false;
}
else // Comparing as two ArrayBuffers
{
if (!pvtsutils.BufferSourceConverter.isEqual(this.value.valueBeforeDecodeView, compareTo.value.valueBeforeDecodeView))
return false;
}
return true;
}
return false;
}
}

379
third_party/js/PKI.js/src/AuthenticatedSafe.ts поставляемый
Просмотреть файл

@ -1,379 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { ContentInfo, ContentInfoJson } from "./ContentInfo";
import { SafeContents } from "./SafeContents";
import { EnvelopedData } from "./EnvelopedData";
import { EncryptedData } from "./EncryptedData";
import * as Schema from "./Schema";
import { id_ContentType_Data, id_ContentType_EncryptedData, id_ContentType_EnvelopedData } from "./ObjectIdentifiers";
import { ArgumentError, AsnError, ParameterError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_STRING } from "./constants";
import * as common from "./common";
const SAFE_CONTENTS = "safeContents";
const PARSED_VALUE = "parsedValue";
const CONTENT_INFOS = "contentInfos";
export interface IAuthenticatedSafe {
safeContents: ContentInfo[];
parsedValue: any;
}
export type AuthenticatedSafeParameters = PkiObjectParameters & Partial<IAuthenticatedSafe>;
export interface AuthenticatedSafeJson {
safeContents: ContentInfoJson[];
}
export type SafeContent = ContentInfo | EncryptedData | EnvelopedData | object;
/**
* Represents the AuthenticatedSafe structure described in [RFC7292](https://datatracker.ietf.org/doc/html/rfc7292)
*/
export class AuthenticatedSafe extends PkiObject implements IAuthenticatedSafe {
public static override CLASS_NAME = "AuthenticatedSafe";
public safeContents!: ContentInfo[];
public parsedValue: any;
/**
* Initializes a new instance of the {@link AuthenticatedSafe} class
* @param parameters Initialization parameters
*/
constructor(parameters: AuthenticatedSafeParameters = {}) {
super();
this.safeContents = pvutils.getParametersValue(parameters, SAFE_CONTENTS, AuthenticatedSafe.defaultValues(SAFE_CONTENTS));
if (PARSED_VALUE in parameters) {
this.parsedValue = pvutils.getParametersValue(parameters, PARSED_VALUE, AuthenticatedSafe.defaultValues(PARSED_VALUE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof SAFE_CONTENTS): ContentInfo[];
public static override defaultValues(memberName: typeof PARSED_VALUE): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case SAFE_CONTENTS:
return [];
case PARSED_VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case SAFE_CONTENTS:
return (memberValue.length === 0);
case PARSED_VALUE:
return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AuthenticatedSafe ::= SEQUENCE OF ContentInfo
* -- Data if unencrypted
* -- EncryptedData if password-encrypted
* -- EnvelopedData if public key-encrypted
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
contentInfos?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.contentInfos || EMPTY_STRING),
value: ContentInfo.schema()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, [
CONTENT_INFOS
]);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AuthenticatedSafe.schema({
names: {
contentInfos: CONTENT_INFOS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.safeContents = Array.from(asn1.result.contentInfos, element => new ContentInfo({ schema: element }));
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: Array.from(this.safeContents, o => o.toSchema())
}));
}
public toJSON(): AuthenticatedSafeJson {
return {
safeContents: Array.from(this.safeContents, o => o.toJSON())
};
}
public async parseInternalValues(parameters: { safeContents: SafeContent[]; }, crypto = common.getCrypto(true)): Promise<void> {
//#region Check input data from "parameters"
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\"");
}
//#endregion
//#region Create value for "this.parsedValue.authenticatedSafe"
this.parsedValue = {
safeContents: [] as any[],
};
for (const [index, content] of this.safeContents.entries()) {
const safeContent = parameters.safeContents[index];
const errorTarget = `parameters.safeContents[${index}]`;
switch (content.contentType) {
//#region data
case id_ContentType_Data:
{
// Check that we do have OCTET STRING as "content"
ArgumentError.assert(content.content, "this.safeContents[j].content", asn1js.OctetString);
//#region Check we have "constructive encoding" for AuthSafe content
const authSafeContent = content.content.getValue();
//#endregion
//#region Finally initialize initial values of SAFE_CONTENTS type
this.parsedValue.safeContents.push({
privacyMode: 0, // No privacy, clear data
value: SafeContents.fromBER(authSafeContent)
});
//#endregion
}
break;
//#endregion
//#region envelopedData
case id_ContentType_EnvelopedData:
{
//#region Initial variables
const cmsEnveloped = new EnvelopedData({ schema: content.content });
//#endregion
//#region Check mandatory parameters
ParameterError.assert(errorTarget, safeContent, "recipientCertificate", "recipientKey");
const envelopedData = safeContent as any;
const recipientCertificate = envelopedData.recipientCertificate;
const recipientKey = envelopedData.recipientKey;
//#endregion
//#region Decrypt CMS EnvelopedData using first recipient information
const decrypted = await cmsEnveloped.decrypt(0, {
recipientCertificate,
recipientPrivateKey: recipientKey
}, crypto);
this.parsedValue.safeContents.push({
privacyMode: 2, // Public-key privacy mode
value: SafeContents.fromBER(decrypted),
});
//#endregion
}
break;
//#endregion
//#region encryptedData
case id_ContentType_EncryptedData:
{
//#region Initial variables
const cmsEncrypted = new EncryptedData({ schema: content.content });
//#endregion
//#region Check mandatory parameters
ParameterError.assert(errorTarget, safeContent, "password");
const password = (safeContent as any).password;
//#endregion
//#region Decrypt CMS EncryptedData using password
const decrypted = await cmsEncrypted.decrypt({
password
}, crypto);
//#endregion
//#region Initialize internal data
this.parsedValue.safeContents.push({
privacyMode: 1, // Password-based privacy mode
value: SafeContents.fromBER(decrypted),
});
//#endregion
}
break;
//#endregion
//#region default
default:
throw new Error(`Unknown "contentType" for AuthenticatedSafe: " ${content.contentType}`);
//#endregion
}
}
//#endregion
}
public async makeInternalValues(parameters: {
safeContents: any[];
}, crypto = common.getCrypto(true)): Promise<this> {
//#region Check data in PARSED_VALUE
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");
//#region Check input data from "parameters"
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\"");
}
//#endregion
//#region Create internal values from already parsed values
this.safeContents = [];
for (const [index, content] of this.parsedValue.safeContents.entries()) {
//#region Check current "content" value
ParameterError.assert("content", content, "privacyMode", "value");
ArgumentError.assert(content.value, "content.value", SafeContents);
//#endregion
switch (content.privacyMode) {
//#region No privacy
case 0:
{
const contentBuffer = content.value.toSchema().toBER(false);
this.safeContents.push(new ContentInfo({
contentType: "1.2.840.113549.1.7.1",
content: new asn1js.OctetString({ valueHex: contentBuffer })
}));
}
break;
//#endregion
//#region Privacy with password
case 1:
{
//#region Initial variables
const cmsEncrypted = new EncryptedData();
const currentParameters = parameters.safeContents[index];
currentParameters.contentToEncrypt = content.value.toSchema().toBER(false);
//#endregion
//#region Encrypt CMS EncryptedData using password
await cmsEncrypted.encrypt(currentParameters);
//#endregion
//#region Store result content in CMS_CONTENT_INFO type
this.safeContents.push(new ContentInfo({
contentType: "1.2.840.113549.1.7.6",
content: cmsEncrypted.toSchema()
}));
//#endregion
}
break;
//#endregion
//#region Privacy with public key
case 2:
{
//#region Initial variables
const cmsEnveloped = new EnvelopedData();
const contentToEncrypt = content.value.toSchema().toBER(false);
const safeContent = parameters.safeContents[index];
//#endregion
//#region Check mandatory parameters
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}`);
}
//#endregion
//#region Making correct "encryptionAlgorithm" variable
const encryptionAlgorithm = safeContent.encryptionAlgorithm;
//#endregion
//#region Append recipient for enveloped data
cmsEnveloped.addRecipientByCertificate(safeContent.encryptingCertificate, {}, undefined, crypto);
//#endregion
//#region Making encryption
await cmsEnveloped.encrypt(encryptionAlgorithm, contentToEncrypt, crypto);
this.safeContents.push(new ContentInfo({
contentType: "1.2.840.113549.1.7.3",
content: cmsEnveloped.toSchema()
}));
//#endregion
}
break;
//#endregion
//#region default
default:
throw new Error(`Incorrect value for "content.privacyMode": ${content.privacyMode}`);
//#endregion
}
}
//#endregion
//#region Return result of the function
return this;
//#endregion
}
}

Просмотреть файл

@ -1,231 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { GeneralName, GeneralNameJson } from "./GeneralName";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const KEY_IDENTIFIER = "keyIdentifier";
const AUTHORITY_CERT_ISSUER = "authorityCertIssuer";
const AUTHORITY_CERT_SERIAL_NUMBER = "authorityCertSerialNumber";
const CLEAR_PROPS = [
KEY_IDENTIFIER,
AUTHORITY_CERT_ISSUER,
AUTHORITY_CERT_SERIAL_NUMBER,
];
export interface IAuthorityKeyIdentifier {
keyIdentifier?: asn1js.OctetString;
authorityCertIssuer?: GeneralName[];
authorityCertSerialNumber?: asn1js.Integer;
}
export type AuthorityKeyIdentifierParameters = PkiObjectParameters & Partial<IAuthorityKeyIdentifier>;
export interface AuthorityKeyIdentifierJson {
keyIdentifier?: asn1js.OctetStringJson;
authorityCertIssuer?: GeneralNameJson[];
authorityCertSerialNumber?: asn1js.IntegerJson;
}
/**
* Represents the AuthorityKeyIdentifier structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class AuthorityKeyIdentifier extends PkiObject implements IAuthorityKeyIdentifier {
public static override CLASS_NAME = "AuthorityKeyIdentifier";
public keyIdentifier?: asn1js.OctetString;
public authorityCertIssuer?: GeneralName[];
public authorityCertSerialNumber?: asn1js.Integer;
/**
* Initializes a new instance of the {@link AuthorityKeyIdentifier} class
* @param parameters Initialization parameters
*/
constructor(parameters: AuthorityKeyIdentifierParameters = {}) {
super();
if (KEY_IDENTIFIER in parameters) {
this.keyIdentifier = pvutils.getParametersValue(parameters, KEY_IDENTIFIER, AuthorityKeyIdentifier.defaultValues(KEY_IDENTIFIER));
}
if (AUTHORITY_CERT_ISSUER in parameters) {
this.authorityCertIssuer = pvutils.getParametersValue(parameters, AUTHORITY_CERT_ISSUER, AuthorityKeyIdentifier.defaultValues(AUTHORITY_CERT_ISSUER));
}
if (AUTHORITY_CERT_SERIAL_NUMBER in parameters) {
this.authorityCertSerialNumber = pvutils.getParametersValue(parameters, AUTHORITY_CERT_SERIAL_NUMBER, AuthorityKeyIdentifier.defaultValues(AUTHORITY_CERT_SERIAL_NUMBER));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof KEY_IDENTIFIER): asn1js.OctetString;
public static override defaultValues(memberName: typeof AUTHORITY_CERT_ISSUER): GeneralName[];
public static override defaultValues(memberName: typeof AUTHORITY_CERT_SERIAL_NUMBER): asn1js.Integer;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case KEY_IDENTIFIER:
return new asn1js.OctetString();
case AUTHORITY_CERT_ISSUER:
return [];
case AUTHORITY_CERT_SERIAL_NUMBER:
return new asn1js.Integer();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AuthorityKeyIdentifier OID ::= 2.5.29.35
*
* AuthorityKeyIdentifier ::= SEQUENCE {
* keyIdentifier [0] KeyIdentifier OPTIONAL,
* authorityCertIssuer [1] GeneralNames OPTIONAL,
* authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
*
* KeyIdentifier ::= OCTET STRING
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
keyIdentifier?: string;
authorityCertIssuer?: string;
authorityCertSerialNumber?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Primitive({
name: (names.keyIdentifier || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
}
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [
new asn1js.Repeated({
name: (names.authorityCertIssuer || EMPTY_STRING),
value: GeneralName.schema()
})
]
}),
new asn1js.Primitive({
name: (names.authorityCertSerialNumber || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
}
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
AuthorityKeyIdentifier.schema({
names: {
keyIdentifier: KEY_IDENTIFIER,
authorityCertIssuer: AUTHORITY_CERT_ISSUER,
authorityCertSerialNumber: AUTHORITY_CERT_SERIAL_NUMBER
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
if (KEY_IDENTIFIER in asn1.result)
this.keyIdentifier = new asn1js.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 asn1js.Integer({ valueHex: asn1.result.authorityCertSerialNumber.valueBlock.valueHex });
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
if (this.keyIdentifier) {
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
valueHex: this.keyIdentifier.valueBlock.valueHexView
}));
}
if (this.authorityCertIssuer) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: Array.from(this.authorityCertIssuer, o => o.toSchema())
}));
}
if (this.authorityCertSerialNumber) {
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
valueHex: this.authorityCertSerialNumber.valueBlock.valueHexView
}));
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): AuthorityKeyIdentifierJson {
const object: AuthorityKeyIdentifierJson = {};
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;
}
}

172
third_party/js/PKI.js/src/BasicConstraints.ts поставляемый
Просмотреть файл

@ -1,172 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const PATH_LENGTH_CONSTRAINT = "pathLenConstraint";
const CA = "cA";
export interface IBasicConstraints {
cA: boolean;
pathLenConstraint?: number | asn1js.Integer;
}
export type BasicConstraintsParameters = PkiObjectParameters & Partial<IBasicConstraints>;
export interface BasicConstraintsJson {
cA?: boolean;
pathLenConstraint?: asn1js.IntegerJson | number;
}
/**
* Represents the BasicConstraints structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class BasicConstraints extends PkiObject implements IBasicConstraints {
public static override CLASS_NAME = "BasicConstraints";
public cA!: boolean;
public pathLenConstraint?: number | asn1js.Integer;
/**
* Initializes a new instance of the {@link AuthorityKeyIdentifier} class
* @param parameters Initialization parameters
*/
constructor(parameters: BasicConstraintsParameters = {}) {
super();
this.cA = pvutils.getParametersValue(parameters, CA, false);
if (PATH_LENGTH_CONSTRAINT in parameters) {
this.pathLenConstraint = pvutils.getParametersValue(parameters, PATH_LENGTH_CONSTRAINT, 0);
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CA): boolean;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CA:
return false;
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL }
*```
*/
static override schema(parameters: Schema.SchemaParameters<{ cA?: string; pathLenConstraint?: string; }> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Boolean({
optional: true,
name: (names.cA || EMPTY_STRING)
}),
new asn1js.Integer({
optional: true,
name: (names.pathLenConstraint || EMPTY_STRING)
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, [
CA,
PATH_LENGTH_CONSTRAINT
]);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
BasicConstraints.schema({
names: {
cA: CA,
pathLenConstraint: PATH_LENGTH_CONSTRAINT
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
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;
}
}
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
if (this.cA !== BasicConstraints.defaultValues(CA))
outputArray.push(new asn1js.Boolean({ value: this.cA }));
if (PATH_LENGTH_CONSTRAINT in this) {
if (this.pathLenConstraint instanceof asn1js.Integer) {
outputArray.push(this.pathLenConstraint);
} else {
outputArray.push(new asn1js.Integer({ value: this.pathLenConstraint }));
}
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
/**
* Conversion for the class to JSON object
* @returns
*/
public toJSON(): BasicConstraintsJson {
const object: BasicConstraintsJson = {};
if (this.cA !== BasicConstraints.defaultValues(CA)) {
object.cA = this.cA;
}
if (PATH_LENGTH_CONSTRAINT in this) {
if (this.pathLenConstraint instanceof asn1js.Integer) {
object.pathLenConstraint = this.pathLenConstraint.toJSON();
} else {
object.pathLenConstraint = this.pathLenConstraint;
}
}
return object;
}
}

442
third_party/js/PKI.js/src/BasicOCSPResponse.ts поставляемый
Просмотреть файл

@ -1,442 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import * as common from "./common";
import { ResponseData, ResponseDataJson, ResponseDataSchema } from "./ResponseData";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { Certificate, CertificateJson, CertificateSchema, checkCA } from "./Certificate";
import { CertID } from "./CertID";
import { RelativeDistinguishedNames } from "./RelativeDistinguishedNames";
import { CertificateChainValidationEngine } from "./CertificateChainValidationEngine";
import * as Schema from "./Schema";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_STRING } from "./constants";
const TBS_RESPONSE_DATA = "tbsResponseData";
const SIGNATURE_ALGORITHM = "signatureAlgorithm";
const SIGNATURE = "signature";
const CERTS = "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}`;
const BASIC_OCSP_RESPONSE_SIGNATURE = `${BASIC_OCSP_RESPONSE}.${SIGNATURE}`;
const BASIC_OCSP_RESPONSE_CERTS = `${BASIC_OCSP_RESPONSE}.${CERTS}`;
const CLEAR_PROPS = [
BASIC_OCSP_RESPONSE_TBS_RESPONSE_DATA,
BASIC_OCSP_RESPONSE_SIGNATURE_ALGORITHM,
BASIC_OCSP_RESPONSE_SIGNATURE,
BASIC_OCSP_RESPONSE_CERTS
];
export interface IBasicOCSPResponse {
tbsResponseData: ResponseData;
signatureAlgorithm: AlgorithmIdentifier;
signature: asn1js.BitString;
certs?: Certificate[];
}
export interface CertificateStatus {
isForCertificate: boolean;
/**
* 0 = good, 1 = revoked, 2 = unknown
*/
status: number;
}
export type BasicOCSPResponseParameters = PkiObjectParameters & Partial<IBasicOCSPResponse>;
export interface BasicOCSPResponseVerifyParams {
trustedCerts?: Certificate[];
}
export interface BasicOCSPResponseJson {
tbsResponseData: ResponseDataJson;
signatureAlgorithm: AlgorithmIdentifierJson;
signature: asn1js.BitStringJson;
certs?: CertificateJson[];
}
/**
* Represents the BasicOCSPResponse structure described in [RFC6960](https://datatracker.ietf.org/doc/html/rfc6960)
*/
export class BasicOCSPResponse extends PkiObject implements IBasicOCSPResponse {
public static override CLASS_NAME = "BasicOCSPResponse";
public tbsResponseData!: ResponseData;
public signatureAlgorithm!: AlgorithmIdentifier;
public signature!: asn1js.BitString;
public certs?: Certificate[];
/**
* Initializes a new instance of the {@link BasicOCSPResponse} class
* @param parameters Initialization parameters
*/
constructor(parameters: BasicOCSPResponseParameters = {}) {
super();
this.tbsResponseData = pvutils.getParametersValue(parameters, TBS_RESPONSE_DATA, BasicOCSPResponse.defaultValues(TBS_RESPONSE_DATA));
this.signatureAlgorithm = pvutils.getParametersValue(parameters, SIGNATURE_ALGORITHM, BasicOCSPResponse.defaultValues(SIGNATURE_ALGORITHM));
this.signature = pvutils.getParametersValue(parameters, SIGNATURE, BasicOCSPResponse.defaultValues(SIGNATURE));
if (CERTS in parameters) {
this.certs = pvutils.getParametersValue(parameters, CERTS, BasicOCSPResponse.defaultValues(CERTS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TBS_RESPONSE_DATA): ResponseData;
public static override defaultValues(memberName: typeof SIGNATURE_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SIGNATURE): asn1js.BitString;
public static override defaultValues(memberName: typeof CERTS): Certificate[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TBS_RESPONSE_DATA:
return new ResponseData();
case SIGNATURE_ALGORITHM:
return new AlgorithmIdentifier();
case SIGNATURE:
return new asn1js.BitString();
case CERTS:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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:
return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false));
case SIGNATURE:
return (memberValue.isEqual(BasicOCSPResponse.defaultValues(memberName)));
case CERTS:
return (memberValue.length === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* BasicOCSPResponse ::= SEQUENCE {
* tbsResponseData ResponseData,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING,
* certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
tbsResponseData?: ResponseDataSchema;
signatureAlgorithm?: AlgorithmIdentifierSchema;
signature?: string;
certs?: CertificateSchema;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.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 asn1js.BitString({ name: (names.signature || BASIC_OCSP_RESPONSE_SIGNATURE) }),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Sequence({
value: [new asn1js.Repeated({
name: BASIC_OCSP_RESPONSE_CERTS,
value: Certificate.schema(names.certs || {})
})]
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
//#endregion
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
BasicOCSPResponse.schema()
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
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 }));
}
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(this.tbsResponseData.toSchema());
outputArray.push(this.signatureAlgorithm.toSchema());
outputArray.push(this.signature);
//#region Create array of certificates
if (this.certs) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Sequence({
value: Array.from(this.certs, o => o.toSchema())
})
]
}));
}
//#endregion
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): BasicOCSPResponseJson {
const res: BasicOCSPResponseJson = {
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;
}
/**
* Get OCSP response status for specific certificate
* @param certificate Certificate to be checked
* @param issuerCertificate Certificate of issuer for certificate to be checked
* @param crypto Crypto engine
*/
public async getCertificateStatus(certificate: Certificate, issuerCertificate: Certificate, crypto = common.getCrypto(true)): Promise<CertificateStatus> {
//#region Initial variables
const result = {
isForCertificate: false,
status: 2 // 0 = good, 1 = revoked, 2 = unknown
};
const hashesObject: Record<string, number> = {};
const certIDs: CertID[] = [];
//#endregion
//#region Create all "certIDs" for input certificates
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);
}
}
//#endregion
//#region Compare all response's "certIDs" with identifiers for input certificate
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; // revoked
break;
case false:
switch (response.certStatus.idBlock.tagNumber) {
case 0: // good
result.status = 0;
break;
case 2: // unknown
result.status = 2;
break;
default:
}
break;
default:
}
}
catch (ex) {
// nothing
}
return result;
}
}
}
return result;
//#endregion
}
/**
* Make signature for current OCSP Basic Response
* @param privateKey Private key for "subjectPublicKeyInfo" structure
* @param hashAlgorithm Hashing algorithm. Default SHA-1
* @param crypto Crypto engine
*/
async sign(privateKey: CryptoKey, hashAlgorithm = "SHA-1", crypto = common.getCrypto(true)): Promise<void> {
// Get a private key from function parameter
if (!privateKey) {
throw new Error("Need to provide a private key for signing");
}
//#region Get a "default parameters" for current algorithm and set correct signature algorithm
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;
//#endregion
//#region Create TBS data for signing
this.tbsResponseData.tbsView = new Uint8Array(this.tbsResponseData.toSchema(true).toBER());
//#endregion
//#region Signing TBS data on provided private key
const signature = await crypto.signWithPrivateKey(this.tbsResponseData.tbsView, privateKey, { algorithm });
this.signature = new asn1js.BitString({ valueHex: signature });
//#endregion
}
/**
* Verify existing OCSP Basic Response
* @param params Additional parameters
* @param crypto Crypto engine
*/
public async verify(params: BasicOCSPResponseVerifyParams = {}, crypto = common.getCrypto(true)): Promise<boolean> {
//#region Initial variables
let signerCert: Certificate | null = null;
let certIndex = -1;
const trustedCerts: Certificate[] = params.trustedCerts || [];
//#endregion
//#region Check amount of certificates
if (!this.certs) {
throw new Error("No certificates attached to the BasicOCSPResponse");
}
//#endregion
//#region Find correct value for "responderID"
switch (true) {
case (this.tbsResponseData.responderID instanceof RelativeDistinguishedNames): // [1] Name
for (const [index, certificate] of this.certs.entries()) {
if (certificate.subject.isEqual(this.tbsResponseData.responderID)) {
certIndex = index;
break;
}
}
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);
if (pvutils.isEqualBuffer(hash, this.tbsResponseData.responderID.valueBlock.valueHex)) {
certIndex = index;
break;
}
}
break;
default:
throw new Error("Wrong value for responderID");
}
//#endregion
//#region Make additional verification for signer's certificate
if (certIndex === (-1))
throw new Error("Correct certificate was not found in OCSP response");
signerCert = this.certs[certIndex];
const additionalCerts: Certificate[] = [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);
}
}

170
third_party/js/PKI.js/src/CAVersion.ts поставляемый
Просмотреть файл

@ -1,170 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const CERTIFICATE_INDEX = "certificateIndex";
const KEY_INDEX = "keyIndex";
export interface ICAVersion {
certificateIndex: number;
keyIndex: number;
}
export type CAVersionParameters = PkiObjectParameters & Partial<ICAVersion>;
export interface CAVersionJson {
certificateIndex: number;
keyIndex: number;
}
/**
* Represents an CAVersion described in [Certification Authority Renewal](https://docs.microsoft.com/en-us/windows/desktop/seccrypto/certification-authority-renewal)
*/
export class CAVersion extends PkiObject implements ICAVersion {
public static override CLASS_NAME = "CAVersion";
public certificateIndex!: number;
public keyIndex!: number;
/**
* Initializes a new instance of the {@link CAVersion} class
* @param parameters Initialization parameters
*/
constructor(parameters: CAVersionParameters = {}) {
super();
this.certificateIndex = pvutils.getParametersValue(parameters, CERTIFICATE_INDEX, CAVersion.defaultValues(CERTIFICATE_INDEX));
this.keyIndex = pvutils.getParametersValue(parameters, KEY_INDEX, CAVersion.defaultValues(KEY_INDEX));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CERTIFICATE_INDEX): number;
public static override defaultValues(memberName: typeof KEY_INDEX): number;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CERTIFICATE_INDEX:
case KEY_INDEX:
return 0;
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CAVersion ::= INTEGER
*```
*/
public static override schema(): Schema.SchemaType {
return (new asn1js.Integer());
}
public fromSchema(schema: Schema.SchemaType) {
//#region Check the schema is valid
if (schema.constructor.blockName() !== asn1js.Integer.blockName()) {
throw new Error("Object's schema was not verified against input data for CAVersion");
}
//#endregion
//#region Check length of the input value and correct it if needed
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;
default:
}
//#endregion
//#region Get internal properties from parsed schema
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];
//#endregion
}
public toSchema(): asn1js.Integer {
//#region Create raw values
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;
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Integer({
valueHex: pvutils.utilConcatBuf(keyIndexBuffer, certificateIndexBuffer)
}));
//#endregion
}
public toJSON(): CAVersionJson {
return {
certificateIndex: this.certificateIndex,
keyIndex: this.keyIndex
};
}
}

190
third_party/js/PKI.js/src/CRLBag.ts поставляемый
Просмотреть файл

@ -1,190 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { CertificateRevocationList } from "./CertificateRevocationList";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { id_CRLBag_X509CRL } from "./ObjectIdentifiers";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const CRL_ID = "crlId";
const CRL_VALUE = "crlValue";
const PARSED_VALUE = "parsedValue";
const CLEAR_PROPS = [
CRL_ID,
CRL_VALUE,
];
export interface ICRLBag {
crlId: string;
crlValue: any;
parsedValue?: any;
certValue?: any;
}
export interface CRLBagJson {
crlId: string;
crlValue: any;
}
export type CRLBagParameters = PkiObjectParameters & Partial<ICRLBag>;
/**
* Represents the CRLBag structure described in [RFC7292](https://datatracker.ietf.org/doc/html/rfc7292)
*/
export class CRLBag extends PkiObject implements ICRLBag {
public static override CLASS_NAME = "CRLBag";
public crlId!: string;
public crlValue: any;
public parsedValue?: any;
public certValue?: any;
/**
* Initializes a new instance of the {@link CRLBag} class
* @param parameters Initialization parameters
*/
constructor(parameters: CRLBagParameters = {}) {
super();
this.crlId = pvutils.getParametersValue(parameters, CRL_ID, CRLBag.defaultValues(CRL_ID));
this.crlValue = pvutils.getParametersValue(parameters, CRL_VALUE, CRLBag.defaultValues(CRL_VALUE));
if (PARSED_VALUE in parameters) {
this.parsedValue = pvutils.getParametersValue(parameters, PARSED_VALUE, CRLBag.defaultValues(PARSED_VALUE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CRL_ID): string;
public static override defaultValues(memberName: typeof CRL_VALUE): any;
public static override defaultValues(memberName: typeof PARSED_VALUE): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CRL_ID:
return EMPTY_STRING;
case CRL_VALUE:
return (new asn1js.Any());
case PARSED_VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case CRL_ID:
return (memberValue === EMPTY_STRING);
case CRL_VALUE:
return (memberValue instanceof asn1js.Any);
case PARSED_VALUE:
return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CRLBag ::= SEQUENCE {
* crlId BAG-TYPE.&id ({CRLTypes}),
* crlValue [0] EXPLICIT BAG-TYPE.&Type ({CRLTypes}{@crlId})
*}
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
id?: string;
value?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.id || "id") }),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [new asn1js.Any({ name: (names.value || "value") })] // EXPLICIT ANY value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CRLBag.schema({
names: {
id: CRL_ID,
value: CRL_VALUE
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.crlId = asn1.result.crlId.valueBlock.toString();
this.crlValue = asn1.result.crlValue;
switch (this.crlId) {
case id_CRLBag_X509CRL: // x509CRL
{
this.parsedValue = CertificateRevocationList.fromBER(this.certValue.valueBlock.valueHex);
}
break;
default:
throw new Error(`Incorrect CRL_ID value in CRLBag: ${this.crlId}`);
}
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
if (this.parsedValue) {
this.crlId = id_CRLBag_X509CRL;
this.crlValue = new asn1js.OctetString({ valueHex: this.parsedValue.toSchema().toBER(false) });
}
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.crlId }),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [this.crlValue.toSchema()]
})
]
}));
}
public toJSON(): CRLBagJson {
return {
crlId: this.crlId,
crlValue: this.crlValue.toJSON()
};
}
}

Просмотреть файл

@ -1,122 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { DistributionPoint, DistributionPointJson } from "./DistributionPoint";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const DISTRIBUTION_POINTS = "distributionPoints";
const CLEAR_PROPS = [
DISTRIBUTION_POINTS
];
export interface ICRLDistributionPoints {
distributionPoints: DistributionPoint[];
}
export interface CRLDistributionPointsJson {
distributionPoints: DistributionPointJson[];
}
export type CRLDistributionPointsParameters = PkiObjectParameters & Partial<ICRLDistributionPoints>;
/**
* Represents the CRLDistributionPoints structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class CRLDistributionPoints extends PkiObject implements ICRLDistributionPoints {
public static override CLASS_NAME = "CRLDistributionPoints";
public distributionPoints!: DistributionPoint[];
/**
* Initializes a new instance of the {@link CRLDistributionPoints} class
* @param parameters Initialization parameters
*/
constructor(parameters: CRLDistributionPointsParameters = {}) {
super();
this.distributionPoints = pvutils.getParametersValue(parameters, DISTRIBUTION_POINTS, CRLDistributionPoints.defaultValues(DISTRIBUTION_POINTS));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: string): DistributionPoint[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case DISTRIBUTION_POINTS:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
distributionPoints?: string;
}> = {}): Schema.SchemaType {
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [distributionPoints]
*/
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.distributionPoints || EMPTY_STRING),
value: DistributionPoint.schema()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CRLDistributionPoints.schema({
names: {
distributionPoints: DISTRIBUTION_POINTS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.distributionPoints = Array.from(asn1.result.distributionPoints, element => new DistributionPoint({ schema: element }));
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: Array.from(this.distributionPoints, o => o.toSchema())
}));
}
public toJSON(): CRLDistributionPointsJson {
return {
distributionPoints: Array.from(this.distributionPoints, o => o.toJSON())
};
}
}

210
third_party/js/PKI.js/src/CertBag.ts поставляемый
Просмотреть файл

@ -1,210 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { Certificate } from "./Certificate";
import { AttributeCertificateV2 } from "./AttributeCertificateV2";
import * as Schema from "./Schema";
import { id_CertBag_AttributeCertificate, id_CertBag_SDSICertificate, id_CertBag_X509Certificate } from "./ObjectIdentifiers";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_STRING } from "./constants";
const CERT_ID = "certId";
const CERT_VALUE = "certValue";
const PARSED_VALUE = "parsedValue";
const CLEAR_PROPS = [
CERT_ID,
CERT_VALUE
];
export interface ICertBag {
certId: string;
certValue: asn1js.OctetString | PkiObject;
parsedValue: any;
}
export type CertBagParameters = PkiObjectParameters & Partial<ICertBag>;
export interface CertBagJson {
certId: string;
certValue: any;
}
/**
* Represents the CertBag structure described in [RFC7292](https://datatracker.ietf.org/doc/html/rfc7292)
*/
export class CertBag extends PkiObject implements ICertBag {
public static override CLASS_NAME = "CertBag";
public certId!: string;
public certValue: PkiObject | asn1js.OctetString;
public parsedValue: any;
/**
* Initializes a new instance of the {@link CertBag} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertBagParameters = {}) {
super();
this.certId = pvutils.getParametersValue(parameters, CERT_ID, CertBag.defaultValues(CERT_ID));
this.certValue = pvutils.getParametersValue(parameters, CERT_VALUE, CertBag.defaultValues(CERT_VALUE));
if (PARSED_VALUE in parameters) {
this.parsedValue = pvutils.getParametersValue(parameters, PARSED_VALUE, CertBag.defaultValues(PARSED_VALUE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CERT_ID): string;
public static override defaultValues(memberName: typeof CERT_VALUE): any;
public static override defaultValues(memberName: typeof PARSED_VALUE): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CERT_ID:
return EMPTY_STRING;
case CERT_VALUE:
return (new asn1js.Any());
case PARSED_VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case CERT_ID:
return (memberValue === EMPTY_STRING);
case CERT_VALUE:
return (memberValue instanceof asn1js.Any);
case PARSED_VALUE:
return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CertBag ::= SEQUENCE {
* certId BAG-TYPE.&id ({CertTypes}),
* certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
id?: string;
value?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.id || "id") }),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [new asn1js.Any({ name: (names.value || "value") })] // EXPLICIT ANY value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CertBag.schema({
names: {
id: CERT_ID,
value: CERT_VALUE
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
this.certId = asn1.result.certId.valueBlock.toString();
this.certValue = asn1.result.certValue as asn1js.OctetString;
const certValueHex = this.certValue.valueBlock.valueHexView;
switch (this.certId) {
case id_CertBag_X509Certificate: // x509Certificate
{
try {
this.parsedValue = Certificate.fromBER(certValueHex);
}
catch (ex) // In some realizations the same OID used for attribute certificates
{
AttributeCertificateV2.fromBER(certValueHex);
}
}
break;
case id_CertBag_AttributeCertificate: // attributeCertificate - (!!!) THIS OID IS SUBJECT FOR CHANGE IN FUTURE (!!!)
{
this.parsedValue = AttributeCertificateV2.fromBER(certValueHex);
}
break;
case id_CertBag_SDSICertificate: // sdsiCertificate
default:
throw new Error(`Incorrect CERT_ID value in CertBag: ${this.certId}`);
}
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
if (PARSED_VALUE in this) {
if ("acinfo" in this.parsedValue) {// attributeCertificate
this.certId = id_CertBag_AttributeCertificate;
} else {// x509Certificate
this.certId = id_CertBag_X509Certificate;
}
this.certValue = new asn1js.OctetString({ valueHex: this.parsedValue.toSchema().toBER(false) });
}
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.certId }),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [(("toSchema" in this.certValue) ? this.certValue.toSchema() : this.certValue)]
})
]
}));
//#endregion
}
public toJSON(): CertBagJson {
return {
certId: this.certId,
certValue: this.certValue.toJSON()
};
}
}

284
third_party/js/PKI.js/src/CertID.ts поставляемый
Просмотреть файл

@ -1,284 +0,0 @@
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import * as common from "./common";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { Certificate } from "./Certificate";
import * as Schema from "./Schema";
import { AsnError, ParameterError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_STRING } from "./constants";
const HASH_ALGORITHM = "hashAlgorithm";
const ISSUER_NAME_HASH = "issuerNameHash";
const ISSUER_KEY_HASH = "issuerKeyHash";
const SERIAL_NUMBER = "serialNumber";
const CLEAR_PROPS = [
HASH_ALGORITHM,
ISSUER_NAME_HASH,
ISSUER_KEY_HASH,
SERIAL_NUMBER,
];
export interface ICertID {
/**
* Hash algorithm used to generate the `issuerNameHash` and `issuerKeyHash` values
*/
hashAlgorithm: AlgorithmIdentifier;
/**
* Hash of the issuer's distinguished name (DN). The hash shall be calculated over the DER encoding
* of the issuer's name field in the certificate being checked.
*/
issuerNameHash: asn1js.OctetString;
/**
* Hash of the issuer's public key. The hash shall be calculated over the value (excluding tag and length)
* of the subject public key field in the issuer's certificate.
*/
issuerKeyHash: asn1js.OctetString;
/**
* Serial number of the certificate for which status is being requested
*/
serialNumber: asn1js.Integer;
}
export type CertIDParameters = PkiObjectParameters & Partial<ICertID>;
export type CertIDSchema = Schema.SchemaParameters<{
hashAlgorithm?: string;
hashAlgorithmObject?: AlgorithmIdentifierSchema;
issuerNameHash?: string;
issuerKeyHash?: string;
serialNumber?: string;
}>;
export interface CertIDJson {
hashAlgorithm: AlgorithmIdentifierJson;
issuerNameHash: asn1js.OctetStringJson;
issuerKeyHash: asn1js.OctetStringJson;
serialNumber: asn1js.IntegerJson;
}
export interface CertIDCreateParams {
issuerCertificate: Certificate;
hashAlgorithm: string;
}
/**
* Represents an CertID described in [RFC6960](https://datatracker.ietf.org/doc/html/rfc6960)
*/
export class CertID extends PkiObject implements ICertID {
public static override CLASS_NAME = "CertID";
/**
* Making OCSP certificate identifier for specific certificate
* @param certificate Certificate making OCSP Request for
* @param parameters Additional parameters
* @param crypto Crypto engine
* @returns Returns created CertID object
*/
public static async create(certificate: Certificate, parameters: CertIDCreateParams, crypto = common.getCrypto(true)): Promise<CertID> {
const certID = new CertID();
await certID.createForCertificate(certificate, parameters, crypto);
return certID;
}
public hashAlgorithm!: AlgorithmIdentifier;
public issuerNameHash!: asn1js.OctetString;
public issuerKeyHash!: asn1js.OctetString;
public serialNumber!: asn1js.Integer;
/**
* Initializes a new instance of the {@link CertID} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertIDParameters = {}) {
super();
this.hashAlgorithm = pvutils.getParametersValue(parameters, HASH_ALGORITHM, CertID.defaultValues(HASH_ALGORITHM));
this.issuerNameHash = pvutils.getParametersValue(parameters, ISSUER_NAME_HASH, CertID.defaultValues(ISSUER_NAME_HASH));
this.issuerKeyHash = pvutils.getParametersValue(parameters, ISSUER_KEY_HASH, CertID.defaultValues(ISSUER_KEY_HASH));
this.serialNumber = pvutils.getParametersValue(parameters, SERIAL_NUMBER, CertID.defaultValues(SERIAL_NUMBER));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof HASH_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ISSUER_NAME_HASH): asn1js.OctetString;
public static override defaultValues(memberName: typeof ISSUER_KEY_HASH): asn1js.OctetString;
public static override defaultValues(memberName: typeof SERIAL_NUMBER): asn1js.Integer;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case HASH_ALGORITHM:
return new AlgorithmIdentifier();
case ISSUER_NAME_HASH:
case ISSUER_KEY_HASH:
return new asn1js.OctetString();
case SERIAL_NUMBER:
return new asn1js.Integer();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case HASH_ALGORITHM:
return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false));
case ISSUER_NAME_HASH:
case ISSUER_KEY_HASH:
case SERIAL_NUMBER:
return (memberValue.isEqual(CertID.defaultValues(SERIAL_NUMBER)));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CertID ::= SEQUENCE {
* hashAlgorithm AlgorithmIdentifier,
* issuerNameHash OCTET STRING, -- Hash of issuer's DN
* issuerKeyHash OCTET STRING, -- Hash of issuer's public key
* serialNumber CertificateSerialNumber }
*```
*/
public static override schema(parameters: CertIDSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AlgorithmIdentifier.schema(names.hashAlgorithmObject || {
names: {
blockName: (names.hashAlgorithm || EMPTY_STRING)
}
}),
new asn1js.OctetString({ name: (names.issuerNameHash || EMPTY_STRING) }),
new asn1js.OctetString({ name: (names.issuerKeyHash || EMPTY_STRING) }),
new asn1js.Integer({ name: (names.serialNumber || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CertID.schema({
names: {
hashAlgorithm: HASH_ALGORITHM,
issuerNameHash: ISSUER_NAME_HASH,
issuerKeyHash: ISSUER_KEY_HASH,
serialNumber: SERIAL_NUMBER
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm });
this.issuerNameHash = asn1.result.issuerNameHash;
this.issuerKeyHash = asn1.result.issuerKeyHash;
this.serialNumber = asn1.result.serialNumber;
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: [
this.hashAlgorithm.toSchema(),
this.issuerNameHash,
this.issuerKeyHash,
this.serialNumber
]
}));
}
public toJSON(): CertIDJson {
return {
hashAlgorithm: this.hashAlgorithm.toJSON(),
issuerNameHash: this.issuerNameHash.toJSON(),
issuerKeyHash: this.issuerKeyHash.toJSON(),
serialNumber: this.serialNumber.toJSON(),
};
}
/**
* Checks that two "CertIDs" are equal
* @param certificateID Identifier of the certificate to be checked
*/
public isEqual(certificateID: CertID): boolean {
// Check HASH_ALGORITHM
if (this.hashAlgorithm.algorithmId !== certificateID.hashAlgorithm.algorithmId) {
return false;
}
// Check ISSUER_NAME_HASH
if (!pvtsutils.BufferSourceConverter.isEqual(this.issuerNameHash.valueBlock.valueHexView, certificateID.issuerNameHash.valueBlock.valueHexView)) {
return false;
}
// Check ISSUER_KEY_HASH
if (!pvtsutils.BufferSourceConverter.isEqual(this.issuerKeyHash.valueBlock.valueHexView, certificateID.issuerKeyHash.valueBlock.valueHexView)) {
return false;
}
// Check SERIAL_NUMBER
if (!this.serialNumber.isEqual(certificateID.serialNumber)) {
return false;
}
return true;
}
/**
* Making OCSP certificate identifier for specific certificate
* @param certificate Certificate making OCSP Request for
* @param parameters Additional parameters
* @param crypto Crypto engine
*/
public async createForCertificate(certificate: Certificate, parameters: CertIDCreateParams, crypto = common.getCrypto(true)): Promise<void> {
//#region Check input parameters
ParameterError.assert(parameters, HASH_ALGORITHM, "issuerCertificate");
const hashOID = crypto.getOIDByAlgorithm({ name: parameters.hashAlgorithm }, true, "hashAlgorithm");
this.hashAlgorithm = new AlgorithmIdentifier({
algorithmId: hashOID,
algorithmParams: new asn1js.Null()
});
const issuerCertificate = parameters.issuerCertificate;
//#endregion
// Initialize SERIAL_NUMBER field
this.serialNumber = certificate.serialNumber;
// Create ISSUER_NAME_HASH
const hashIssuerName = await crypto.digest({ name: parameters.hashAlgorithm }, issuerCertificate.subject.toSchema().toBER(false));
this.issuerNameHash = new asn1js.OctetString({ valueHex: hashIssuerName });
// Create ISSUER_KEY_HASH
const issuerKeyBuffer = issuerCertificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView;
const hashIssuerKey = await crypto.digest({ name: parameters.hashAlgorithm }, issuerKeyBuffer);
this.issuerKeyHash = new asn1js.OctetString({ valueHex: hashIssuerKey });
}
}

828
third_party/js/PKI.js/src/Certificate.ts поставляемый
Просмотреть файл

@ -1,828 +0,0 @@
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import * as common from "./common";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { RelativeDistinguishedNames, RelativeDistinguishedNamesJson, RelativeDistinguishedNamesSchema } from "./RelativeDistinguishedNames";
import { Time, TimeJson, TimeSchema } from "./Time";
import { PublicKeyInfo, PublicKeyInfoJson, PublicKeyInfoSchema } from "./PublicKeyInfo";
import { Extension, ExtensionJson } from "./Extension";
import { Extensions, ExtensionsSchema } from "./Extensions";
import * as Schema from "./Schema";
import { id_BasicConstraints } from "./ObjectIdentifiers";
import { BasicConstraints } from "./BasicConstraints";
import { CryptoEnginePublicKeyParams } from "./CryptoEngine/CryptoEngineInterface";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_BUFFER, EMPTY_STRING } from "./constants";
const TBS = "tbs";
const VERSION = "version";
const SERIAL_NUMBER = "serialNumber";
const SIGNATURE = "signature";
const ISSUER = "issuer";
const NOT_BEFORE = "notBefore";
const NOT_AFTER = "notAfter";
const SUBJECT = "subject";
const SUBJECT_PUBLIC_KEY_INFO = "subjectPublicKeyInfo";
const ISSUER_UNIQUE_ID = "issuerUniqueID";
const SUBJECT_UNIQUE_ID = "subjectUniqueID";
const EXTENSIONS = "extensions";
const SIGNATURE_ALGORITHM = "signatureAlgorithm";
const SIGNATURE_VALUE = "signatureValue";
const TBS_CERTIFICATE = "tbsCertificate";
const TBS_CERTIFICATE_VERSION = `${TBS_CERTIFICATE}.${VERSION}`;
const TBS_CERTIFICATE_SERIAL_NUMBER = `${TBS_CERTIFICATE}.${SERIAL_NUMBER}`;
const TBS_CERTIFICATE_SIGNATURE = `${TBS_CERTIFICATE}.${SIGNATURE}`;
const TBS_CERTIFICATE_ISSUER = `${TBS_CERTIFICATE}.${ISSUER}`;
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}`;
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}`;
const CLEAR_PROPS = [
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,
SIGNATURE_VALUE
];
export type TBSCertificateSchema = Schema.SchemaParameters<{
tbsCertificateVersion?: string;
tbsCertificateSerialNumber?: string;
signature?: AlgorithmIdentifierSchema;
issuer?: RelativeDistinguishedNamesSchema;
tbsCertificateValidity?: string;
notBefore?: TimeSchema;
notAfter?: TimeSchema;
subject?: RelativeDistinguishedNamesSchema;
subjectPublicKeyInfo?: PublicKeyInfoSchema;
tbsCertificateIssuerUniqueID?: string;
tbsCertificateSubjectUniqueID?: string;
extensions?: ExtensionsSchema;
}>;
function tbsCertificate(parameters: TBSCertificateSchema = {}): Schema.SchemaType {
//TBSCertificate ::= SEQUENCE {
// version [0] EXPLICIT Version DEFAULT v1,
// serialNumber CertificateSerialNumber,
// signature AlgorithmIdentifier,
// issuer Name,
// validity Validity,
// subject Name,
// subjectPublicKeyInfo SubjectPublicKeyInfo,
// issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
// -- If present, version MUST be v2 or v3
// subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
// -- If present, version MUST be v2 or v3
// extensions [3] EXPLICIT Extensions OPTIONAL
// -- If present, version MUST be v3
//}
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || TBS_CERTIFICATE),
value: [
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Integer({ name: (names.tbsCertificateVersion || TBS_CERTIFICATE_VERSION) }) // EXPLICIT integer value
]
}),
new asn1js.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 asn1js.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 asn1js.Primitive({
name: (names.tbsCertificateIssuerUniqueID || TBS_CERTIFICATE_ISSUER_UNIQUE_ID),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
}
}), // IMPLICIT BIT_STRING value
new asn1js.Primitive({
name: (names.tbsCertificateSubjectUniqueID || TBS_CERTIFICATE_SUBJECT_UNIQUE_ID),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
}
}), // IMPLICIT BIT_STRING value
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
},
value: [Extensions.schema(names.extensions || {
names: {
blockName: TBS_CERTIFICATE_EXTENSIONS
}
})]
}) // EXPLICIT SEQUENCE value
]
}));
}
export interface ICertificate {
/**
* ToBeSigned (TBS) part of the certificate
*/
tbs: ArrayBuffer;
/**
* Version number
*/
version: number;
/**
* Serial number of the certificate
*/
serialNumber: asn1js.Integer;
/**
* This field contains the algorithm identifier for the algorithm used by the CA to sign the certificate
*/
signature: AlgorithmIdentifier;
/**
* The issuer field identifies the entity that has signed and issued the certificate
*/
issuer: RelativeDistinguishedNames;
/**
* The date on which the certificate validity period begins
*/
notBefore: Time;
/**
* The date on which the certificate validity period ends
*/
notAfter: Time;
/**
* The subject field identifies the entity associated with the public key stored in the subject public key field
*/
subject: RelativeDistinguishedNames;
/**
* This field is used to carry the public key and identify the algorithm with which the key is used
*/
subjectPublicKeyInfo: PublicKeyInfo;
/**
* The subject and issuer unique identifiers are present in the certificate to handle the possibility of reuse of subject and/or issuer names over time
*/
issuerUniqueID?: ArrayBuffer;
/**
* The subject and issuer unique identifiers are present in the certificate to handle the possibility of reuse of subject and/or issuer names over time
*/
subjectUniqueID?: ArrayBuffer;
/**
* If present, this field is a SEQUENCE of one or more certificate extensions
*/
extensions?: Extension[];
/**
* The signatureAlgorithm field contains the identifier for the cryptographic algorithm used by the CA to sign this certificate
*/
signatureAlgorithm: AlgorithmIdentifier;
/**
* The signatureValue field contains a digital signature computed upon the ASN.1 DER encoded tbsCertificate
*/
signatureValue: asn1js.BitString;
}
/**
* Constructor parameters for the {@link Certificate} class
*/
export type CertificateParameters = PkiObjectParameters & Partial<ICertificate>;
/**
* Parameters for {@link Certificate} schema generation
*/
export type CertificateSchema = Schema.SchemaParameters<{
tbsCertificate?: TBSCertificateSchema;
signatureAlgorithm?: AlgorithmIdentifierSchema;
signatureValue?: string;
}>;
export interface CertificateJson {
tbs: string;
version: number;
serialNumber: asn1js.IntegerJson;
signature: AlgorithmIdentifierJson;
issuer: RelativeDistinguishedNamesJson;
notBefore: TimeJson;
notAfter: TimeJson;
subject: RelativeDistinguishedNamesJson;
subjectPublicKeyInfo: PublicKeyInfoJson | JsonWebKey;
issuerUniqueID?: string;
subjectUniqueID?: string;
extensions?: ExtensionJson[];
signatureAlgorithm: AlgorithmIdentifierJson;
signatureValue: asn1js.BitStringJson;
}
/**
* Represents an X.509 certificate described in [RFC5280 Section 4](https://datatracker.ietf.org/doc/html/rfc5280#section-4).
*
* @example The following example demonstrates how to parse X.509 Certificate
* ```js
* const asn1 = asn1js.fromBER(raw);
* if (asn1.offset === -1) {
* throw new Error("Incorrect encoded ASN.1 data");
* }
*
* const cert = new pkijs.Certificate({ schema: asn1.result });
* ```
*
* @example The following example demonstrates how to create self-signed certificate
* ```js
* const crypto = pkijs.getCrypto(true);
*
* // Create certificate
* const certificate = new pkijs.Certificate();
* certificate.version = 2;
* certificate.serialNumber = new asn1js.Integer({ value: 1 });
* certificate.issuer.typesAndValues.push(new pkijs.AttributeTypeAndValue({
* type: "2.5.4.3", // Common name
* value: new asn1js.BmpString({ value: "Test" })
* }));
* certificate.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
* type: "2.5.4.3", // Common name
* value: new asn1js.BmpString({ value: "Test" })
* }));
*
* certificate.notBefore.value = new Date();
* const notAfter = new Date();
* notAfter.setUTCFullYear(notAfter.getUTCFullYear() + 1);
* certificate.notAfter.value = notAfter;
*
* certificate.extensions = []; // Extensions are not a part of certificate by default, it's an optional array
*
* // "BasicConstraints" extension
* const basicConstr = new pkijs.BasicConstraints({
* cA: true,
* pathLenConstraint: 3
* });
* certificate.extensions.push(new pkijs.Extension({
* extnID: "2.5.29.19",
* critical: false,
* extnValue: basicConstr.toSchema().toBER(false),
* parsedValue: basicConstr // Parsed value for well-known extensions
* }));
*
* // "KeyUsage" extension
* const bitArray = new ArrayBuffer(1);
* const bitView = new Uint8Array(bitArray);
* bitView[0] |= 0x02; // Key usage "cRLSign" flag
* bitView[0] |= 0x04; // Key usage "keyCertSign" flag
* const keyUsage = new asn1js.BitString({ valueHex: bitArray });
* certificate.extensions.push(new pkijs.Extension({
* extnID: "2.5.29.15",
* critical: false,
* extnValue: keyUsage.toBER(false),
* parsedValue: keyUsage // Parsed value for well-known extensions
* }));
*
* const algorithm = pkijs.getAlgorithmParameters("RSASSA-PKCS1-v1_5", "generateKey");
* if ("hash" in algorithm.algorithm) {
* algorithm.algorithm.hash.name = "SHA-256";
* }
*
* const keys = await crypto.generateKey(algorithm.algorithm, true, algorithm.usages);
*
* // Exporting public key into "subjectPublicKeyInfo" value of certificate
* await certificate.subjectPublicKeyInfo.importKey(keys.publicKey);
*
* // Signing final certificate
* await certificate.sign(keys.privateKey, "SHA-256");
*
* const raw = certificate.toSchema().toBER();
* ```
*/
export class Certificate extends PkiObject implements ICertificate {
public static override CLASS_NAME = "Certificate";
public tbsView!: Uint8Array;
/**
* @deprecated Since version 3.0.0
*/
public get tbs(): ArrayBuffer {
return pvtsutils.BufferSourceConverter.toArrayBuffer(this.tbsView);
}
/**
* @deprecated Since version 3.0.0
*/
public set tbs(value: ArrayBuffer) {
this.tbsView = new Uint8Array(value);
}
public version!: number;
public serialNumber!: asn1js.Integer;
public signature!: AlgorithmIdentifier;
public issuer!: RelativeDistinguishedNames;
public notBefore!: Time;
public notAfter!: Time;
public subject!: RelativeDistinguishedNames;
public subjectPublicKeyInfo!: PublicKeyInfo;
public issuerUniqueID?: ArrayBuffer;
public subjectUniqueID?: ArrayBuffer;
public extensions?: Extension[];
public signatureAlgorithm!: AlgorithmIdentifier;
public signatureValue!: asn1js.BitString;
/**
* Initializes a new instance of the {@link Certificate} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertificateParameters = {}) {
super();
this.tbsView = new Uint8Array(pvutils.getParametersValue(parameters, TBS, Certificate.defaultValues(TBS)));
this.version = pvutils.getParametersValue(parameters, VERSION, Certificate.defaultValues(VERSION));
this.serialNumber = pvutils.getParametersValue(parameters, SERIAL_NUMBER, Certificate.defaultValues(SERIAL_NUMBER));
this.signature = pvutils.getParametersValue(parameters, SIGNATURE, Certificate.defaultValues(SIGNATURE));
this.issuer = pvutils.getParametersValue(parameters, ISSUER, Certificate.defaultValues(ISSUER));
this.notBefore = pvutils.getParametersValue(parameters, NOT_BEFORE, Certificate.defaultValues(NOT_BEFORE));
this.notAfter = pvutils.getParametersValue(parameters, NOT_AFTER, Certificate.defaultValues(NOT_AFTER));
this.subject = pvutils.getParametersValue(parameters, SUBJECT, Certificate.defaultValues(SUBJECT));
this.subjectPublicKeyInfo = pvutils.getParametersValue(parameters, SUBJECT_PUBLIC_KEY_INFO, Certificate.defaultValues(SUBJECT_PUBLIC_KEY_INFO));
if (ISSUER_UNIQUE_ID in parameters) {
this.issuerUniqueID = pvutils.getParametersValue(parameters, ISSUER_UNIQUE_ID, Certificate.defaultValues(ISSUER_UNIQUE_ID));
}
if (SUBJECT_UNIQUE_ID in parameters) {
this.subjectUniqueID = pvutils.getParametersValue(parameters, SUBJECT_UNIQUE_ID, Certificate.defaultValues(SUBJECT_UNIQUE_ID));
}
if (EXTENSIONS in parameters) {
this.extensions = pvutils.getParametersValue(parameters, EXTENSIONS, Certificate.defaultValues(EXTENSIONS));
}
this.signatureAlgorithm = pvutils.getParametersValue(parameters, SIGNATURE_ALGORITHM, Certificate.defaultValues(SIGNATURE_ALGORITHM));
this.signatureValue = pvutils.getParametersValue(parameters, SIGNATURE_VALUE, Certificate.defaultValues(SIGNATURE_VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Return default values for all class members
* @param memberName String name for a class member
* @returns Predefined default value
*/
public static override defaultValues(memberName: typeof TBS): ArrayBuffer;
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof SERIAL_NUMBER): asn1js.Integer;
public static override defaultValues(memberName: typeof SIGNATURE): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ISSUER): RelativeDistinguishedNames;
public static override defaultValues(memberName: typeof NOT_BEFORE): Time;
public static override defaultValues(memberName: typeof NOT_AFTER): Time;
public static override defaultValues(memberName: typeof SUBJECT): RelativeDistinguishedNames;
public static override defaultValues(memberName: typeof SUBJECT_PUBLIC_KEY_INFO): PublicKeyInfo;
public static override defaultValues(memberName: typeof ISSUER_UNIQUE_ID): ArrayBuffer;
public static override defaultValues(memberName: typeof SUBJECT_UNIQUE_ID): ArrayBuffer;
public static override defaultValues(memberName: typeof EXTENSIONS): Extension[];
public static override defaultValues(memberName: typeof SIGNATURE_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SIGNATURE_VALUE): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TBS:
return EMPTY_BUFFER;
case VERSION:
return 0;
case SERIAL_NUMBER:
return new asn1js.Integer();
case SIGNATURE:
return new AlgorithmIdentifier();
case ISSUER:
return new RelativeDistinguishedNames();
case NOT_BEFORE:
return new Time();
case NOT_AFTER:
return new Time();
case SUBJECT:
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:
return [];
case SIGNATURE_ALGORITHM:
return new AlgorithmIdentifier();
case SIGNATURE_VALUE:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
*
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
* serialNumber CertificateSerialNumber,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version MUST be v3
* }
*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*
* CertificateSerialNumber ::= INTEGER
*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
*
* UniqueIdentifier ::= BIT STRING
*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING
* -- contains the DER encoding of an ASN.1 value
* -- corresponding to the extension type identified
* -- by extnID
* }
*```
*/
public static override schema(parameters: CertificateSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
tbsCertificate(names.tbsCertificate),
AlgorithmIdentifier.schema(names.signatureAlgorithm || {
names: {
blockName: SIGNATURE_ALGORITHM
}
}),
new asn1js.BitString({ name: (names.signatureValue || SIGNATURE_VALUE) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
//#region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
Certificate.schema({
names: {
tbsCertificate: {
names: {
extensions: {
names: {
extensions: TBS_CERTIFICATE_EXTENSIONS
}
}
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
//#endregion
//#region Get internal properties from parsed schema
this.tbsView = (asn1.result.tbsCertificate as asn1js.Sequence).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;
//#endregion
}
/**
* Creates ASN.1 schema for existing values of TBS part for the certificate
* @returns ASN.1 SEQUENCE
*/
public encodeTBS(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
if ((VERSION in this) && (this.version !== Certificate.defaultValues(VERSION))) {
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Integer({ value: this.version }) // EXPLICIT integer value
]
}));
}
outputArray.push(this.serialNumber);
outputArray.push(this.signature.toSchema());
outputArray.push(this.issuer.toSchema());
outputArray.push(new asn1js.Sequence({
value: [
this.notBefore.toSchema(),
this.notAfter.toSchema()
]
}));
outputArray.push(this.subject.toSchema());
outputArray.push(this.subjectPublicKeyInfo.toSchema());
if (this.issuerUniqueID) {
outputArray.push(new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
valueHex: this.issuerUniqueID
}));
}
if (this.subjectUniqueID) {
outputArray.push(new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
valueHex: this.subjectUniqueID
}));
}
if (this.extensions) {
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
},
value: [new asn1js.Sequence({
value: Array.from(this.extensions, o => o.toSchema())
})]
}));
}
//#endregion
//#region Create and return output sequence
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toSchema(encodeFlag = false): asn1js.Sequence {
let tbsSchema: asn1js.AsnType;
// Decode stored TBS value
if (encodeFlag === false) {
if (!this.tbsView.byteLength) { // No stored certificate TBS part
return Certificate.schema().value[0];
}
const asn1 = asn1js.fromBER(this.tbsView);
AsnError.assert(asn1, "TBS Certificate");
tbsSchema = asn1.result;
} else {
// Create TBS schema via assembling from TBS parts
tbsSchema = this.encodeTBS();
}
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
tbsSchema,
this.signatureAlgorithm.toSchema(),
this.signatureValue
]
}));
}
public toJSON(): CertificateJson {
const res: CertificateJson = {
tbs: pvtsutils.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 in this) && (this.version !== Certificate.defaultValues(VERSION))) {
res.version = this.version;
}
if (this.issuerUniqueID) {
res.issuerUniqueID = pvtsutils.Convert.ToHex(this.issuerUniqueID);
}
if (this.subjectUniqueID) {
res.subjectUniqueID = pvtsutils.Convert.ToHex(this.subjectUniqueID);
}
if (this.extensions) {
res.extensions = Array.from(this.extensions, o => o.toJSON());
}
return res;
}
/**
* Importing public key for current certificate
* @param parameters Public key export parameters
* @param crypto Crypto engine
* @returns WebCrypto public key
*/
public async getPublicKey(parameters?: CryptoEnginePublicKeyParams, crypto = common.getCrypto(true)): Promise<CryptoKey> {
return crypto.getPublicKey(this.subjectPublicKeyInfo, this.signatureAlgorithm, parameters);
}
/**
* Get hash value for subject public key (default SHA-1)
* @param hashAlgorithm Hashing algorithm name
* @param crypto Crypto engine
* @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);
}
/**
* Make a signature for current value from TBS section
* @param privateKey Private key for SUBJECT_PUBLIC_KEY_INFO structure
* @param hashAlgorithm Hashing algorithm
* @param crypto Crypto engine
*/
public async sign(privateKey: CryptoKey, hashAlgorithm = "SHA-1", crypto = common.getCrypto(true)): Promise<void> {
// Initial checking
if (!privateKey) {
throw new Error("Need to provide a private key for signing");
}
// Get a "default parameters" for current algorithm and set correct signature algorithm
const signatureParameters = await crypto.getSignatureParameters(privateKey, hashAlgorithm);
const parameters = signatureParameters.parameters;
this.signature = signatureParameters.signatureAlgorithm;
this.signatureAlgorithm = signatureParameters.signatureAlgorithm;
// Create TBS data for signing
this.tbsView = new Uint8Array(this.encodeTBS().toBER());
// Signing TBS data on provided private key
// TODO remove any
const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters as any);
this.signatureValue = new asn1js.BitString({ valueHex: signature });
}
/**
* Verifies the certificate signature
* @param issuerCertificate
* @param crypto Crypto engine
*/
public async verify(issuerCertificate?: Certificate, crypto = common.getCrypto(true)): Promise<boolean> {
let subjectPublicKeyInfo: PublicKeyInfo | undefined;
// Set correct SUBJECT_PUBLIC_KEY_INFO value
if (issuerCertificate) {
subjectPublicKeyInfo = issuerCertificate.subjectPublicKeyInfo;
} else if (this.issuer.isEqual(this.subject)) {
// Self-signed certificate
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);
}
}
/**
* Check CA flag for the certificate
* @param cert Certificate to find CA flag for
* @returns Returns {@link Certificate} if `cert` is CA certificate otherwise return `null`
*/
export function checkCA(cert: Certificate, signerCert: Certificate | null = null): Certificate | null {
//#region Do not include signer's certificate
if (signerCert && cert.issuer.isEqual(signerCert.issuer) && cert.serialNumber.isEqual(signerCert.serialNumber)) {
return null;
}
//#endregion
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;
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,115 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { PolicyInformation, PolicyInformationJson } from "./PolicyInformation";
import * as Schema from "./Schema";
const CERTIFICATE_POLICIES = "certificatePolicies";
const CLEAR_PROPS = [
CERTIFICATE_POLICIES,
];
export interface ICertificatePolicies {
certificatePolicies: PolicyInformation[];
}
export type CertificatePoliciesParameters = PkiObjectParameters & Partial<ICertificatePolicies>;
export interface CertificatePoliciesJson {
certificatePolicies: PolicyInformationJson[];
}
/**
* Represents the CertificatePolicies structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class CertificatePolicies extends PkiObject implements ICertificatePolicies {
public static override CLASS_NAME = "CertificatePolicies";
public certificatePolicies!: PolicyInformation[];
/**
* Initializes a new instance of the {@link CertificatePolicies} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertificatePoliciesParameters = {}) {
super();
this.certificatePolicies = pvutils.getParametersValue(parameters, CERTIFICATE_POLICIES, CertificatePolicies.defaultValues(CERTIFICATE_POLICIES));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CERTIFICATE_POLICIES): PolicyInformation[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CERTIFICATE_POLICIES:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
*```
*/
static override schema(parameters: Schema.SchemaParameters<{ certificatePolicies?: string; }> = {}) {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.certificatePolicies || EMPTY_STRING),
value: PolicyInformation.schema()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CertificatePolicies.schema({
names: {
certificatePolicies: CERTIFICATE_POLICIES
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.certificatePolicies = Array.from(asn1.result.certificatePolicies, element => new PolicyInformation({ schema: element }));
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: Array.from(this.certificatePolicies, o => o.toSchema())
}));
}
public toJSON(): CertificatePoliciesJson {
return {
certificatePolicies: Array.from(this.certificatePolicies, o => o.toJSON())
};
}
}

Просмотреть файл

@ -1,561 +0,0 @@
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import * as common from "./common";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { RelativeDistinguishedNames, RelativeDistinguishedNamesJson, RelativeDistinguishedNamesSchema } from "./RelativeDistinguishedNames";
import { Time, TimeJson, TimeSchema } from "./Time";
import { RevokedCertificate, RevokedCertificateJson } from "./RevokedCertificate";
import { Extensions, ExtensionsJson, ExtensionsSchema } from "./Extensions";
import * as Schema from "./Schema";
import { Certificate } from "./Certificate";
import { PublicKeyInfo } from "./PublicKeyInfo";
import { id_AuthorityInfoAccess, id_AuthorityKeyIdentifier, id_BaseCRLNumber, id_CertificateIssuer, id_CRLNumber, id_CRLReason, id_FreshestCRL, id_InvalidityDate, id_IssuerAltName, id_IssuingDistributionPoint } from "./ObjectIdentifiers";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_BUFFER } from "./constants";
const TBS = "tbs";
const VERSION = "version";
const SIGNATURE = "signature";
const ISSUER = "issuer";
const THIS_UPDATE = "thisUpdate";
const NEXT_UPDATE = "nextUpdate";
const REVOKED_CERTIFICATES = "revokedCertificates";
const CRL_EXTENSIONS = "crlExtensions";
const SIGNATURE_ALGORITHM = "signatureAlgorithm";
const SIGNATURE_VALUE = "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 = [
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,
SIGNATURE_VALUE
];
export interface ICertificateRevocationList {
tbs: ArrayBuffer;
version: number;
signature: AlgorithmIdentifier;
issuer: RelativeDistinguishedNames;
thisUpdate: Time;
nextUpdate?: Time;
revokedCertificates?: RevokedCertificate[];
crlExtensions?: Extensions;
signatureAlgorithm: AlgorithmIdentifier;
signatureValue: asn1js.BitString;
}
export type TBSCertListSchema = Schema.SchemaParameters<{
tbsCertListVersion?: string;
signature?: AlgorithmIdentifierSchema;
issuer?: RelativeDistinguishedNamesSchema;
tbsCertListThisUpdate?: TimeSchema;
tbsCertListNextUpdate?: TimeSchema;
tbsCertListRevokedCertificates?: string;
crlExtensions?: ExtensionsSchema;
}>;
export interface CertificateRevocationListJson {
tbs: string;
version: number;
signature: AlgorithmIdentifierJson;
issuer: RelativeDistinguishedNamesJson;
thisUpdate: TimeJson;
nextUpdate?: TimeJson;
revokedCertificates?: RevokedCertificateJson[];
crlExtensions?: ExtensionsJson;
signatureAlgorithm: AlgorithmIdentifierJson;
signatureValue: asn1js.BitStringJson;
}
function tbsCertList(parameters: TBSCertListSchema = {}): Schema.SchemaType {
//TBSCertList ::= SEQUENCE {
// version Version OPTIONAL,
// -- if present, MUST be v2
// signature AlgorithmIdentifier,
// issuer Name,
// thisUpdate Time,
// nextUpdate Time OPTIONAL,
// revokedCertificates SEQUENCE OF SEQUENCE {
// userCertificate CertificateSerialNumber,
// revocationDate Time,
// crlEntryExtensions Extensions OPTIONAL
// -- if present, version MUST be v2
// } OPTIONAL,
// crlExtensions [0] EXPLICIT Extensions OPTIONAL
// -- if present, version MUST be v2
//}
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || TBS_CERT_LIST),
value: [
new asn1js.Integer({
optional: true,
name: (names.tbsCertListVersion || TBS_CERT_LIST_VERSION),
value: 2
}), // EXPLICIT integer value (v2)
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 asn1js.Sequence({
optional: true,
value: [
new asn1js.Repeated({
name: (names.tbsCertListRevokedCertificates || TBS_CERT_LIST_REVOKED_CERTIFICATES),
value: new asn1js.Sequence({
value: [
new asn1js.Integer(),
Time.schema(),
Extensions.schema({}, true)
]
})
})
]
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [Extensions.schema(names.crlExtensions || {
names: {
blockName: TBS_CERT_LIST_EXTENSIONS
}
})]
}) // EXPLICIT SEQUENCE value
]
}));
}
export type CertificateRevocationListParameters = PkiObjectParameters & Partial<ICertificateRevocationList>;
export interface CertificateRevocationListVerifyParams {
issuerCertificate?: Certificate;
publicKeyInfo?: PublicKeyInfo;
}
const WELL_KNOWN_EXTENSIONS = [
id_AuthorityKeyIdentifier,
id_IssuerAltName,
id_CRLNumber,
id_BaseCRLNumber,
id_IssuingDistributionPoint,
id_FreshestCRL,
id_AuthorityInfoAccess,
id_CRLReason,
id_InvalidityDate,
id_CertificateIssuer,
];
/**
* Represents the CertificateRevocationList structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class CertificateRevocationList extends PkiObject implements ICertificateRevocationList {
public static override CLASS_NAME = "CertificateRevocationList";
public tbsView!: Uint8Array;
/**
* @deprecated Since version 3.0.0
*/
public get tbs(): ArrayBuffer {
return pvtsutils.BufferSourceConverter.toArrayBuffer(this.tbsView);
}
/**
* @deprecated Since version 3.0.0
*/
public set tbs(value: ArrayBuffer) {
this.tbsView = new Uint8Array(value);
}
public version!: number;
public signature!: AlgorithmIdentifier;
public issuer!: RelativeDistinguishedNames;
public thisUpdate!: Time;
public nextUpdate?: Time;
public revokedCertificates?: RevokedCertificate[];
public crlExtensions?: Extensions;
public signatureAlgorithm!: AlgorithmIdentifier;
public signatureValue!: asn1js.BitString;
/**
* Initializes a new instance of the {@link CertificateRevocationList} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertificateRevocationListParameters = {}) {
super();
this.tbsView = new Uint8Array(pvutils.getParametersValue(parameters, TBS, CertificateRevocationList.defaultValues(TBS)));
this.version = pvutils.getParametersValue(parameters, VERSION, CertificateRevocationList.defaultValues(VERSION));
this.signature = pvutils.getParametersValue(parameters, SIGNATURE, CertificateRevocationList.defaultValues(SIGNATURE));
this.issuer = pvutils.getParametersValue(parameters, ISSUER, CertificateRevocationList.defaultValues(ISSUER));
this.thisUpdate = pvutils.getParametersValue(parameters, THIS_UPDATE, CertificateRevocationList.defaultValues(THIS_UPDATE));
if (NEXT_UPDATE in parameters) {
this.nextUpdate = pvutils.getParametersValue(parameters, NEXT_UPDATE, CertificateRevocationList.defaultValues(NEXT_UPDATE));
}
if (REVOKED_CERTIFICATES in parameters) {
this.revokedCertificates = pvutils.getParametersValue(parameters, REVOKED_CERTIFICATES, CertificateRevocationList.defaultValues(REVOKED_CERTIFICATES));
}
if (CRL_EXTENSIONS in parameters) {
this.crlExtensions = pvutils.getParametersValue(parameters, CRL_EXTENSIONS, CertificateRevocationList.defaultValues(CRL_EXTENSIONS));
}
this.signatureAlgorithm = pvutils.getParametersValue(parameters, SIGNATURE_ALGORITHM, CertificateRevocationList.defaultValues(SIGNATURE_ALGORITHM));
this.signatureValue = pvutils.getParametersValue(parameters, SIGNATURE_VALUE, CertificateRevocationList.defaultValues(SIGNATURE_VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TBS): ArrayBuffer;
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof SIGNATURE): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ISSUER): RelativeDistinguishedNames;
public static override defaultValues(memberName: typeof THIS_UPDATE): Time;
public static override defaultValues(memberName: typeof NEXT_UPDATE): Time;
public static override defaultValues(memberName: typeof REVOKED_CERTIFICATES): RevokedCertificate[];
public static override defaultValues(memberName: typeof CRL_EXTENSIONS): Extensions;
public static override defaultValues(memberName: typeof SIGNATURE_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SIGNATURE_VALUE): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TBS:
return EMPTY_BUFFER;
case VERSION:
return 0;
case SIGNATURE:
return new AlgorithmIdentifier();
case ISSUER:
return new RelativeDistinguishedNames();
case THIS_UPDATE:
return new Time();
case NEXT_UPDATE:
return new Time();
case REVOKED_CERTIFICATES:
return [];
case CRL_EXTENSIONS:
return new Extensions();
case SIGNATURE_ALGORITHM:
return new AlgorithmIdentifier();
case SIGNATURE_VALUE:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CertificateList ::= SEQUENCE {
* tbsCertList TBSCertList,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
tbsCertListVersion?: string;
signature?: AlgorithmIdentifierSchema;
issuer?: RelativeDistinguishedNamesSchema;
tbsCertListThisUpdate?: TimeSchema;
tbsCertListNextUpdate?: TimeSchema;
tbsCertListRevokedCertificates?: string;
crlExtensions?: ExtensionsSchema;
signatureAlgorithm?: AlgorithmIdentifierSchema;
signatureValue?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || "CertificateList"),
value: [
tbsCertList(parameters),
AlgorithmIdentifier.schema(names.signatureAlgorithm || {
names: {
blockName: SIGNATURE_ALGORITHM
}
}),
new asn1js.BitString({ name: (names.signatureValue || SIGNATURE_VALUE) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CertificateRevocationList.schema()
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
this.tbsView = (asn1.result.tbsCertList as asn1js.Sequence).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;
//#endregion
}
protected encodeTBS() {
//#region Create array for output sequence
const outputArray: any[] = [];
if (this.version !== CertificateRevocationList.defaultValues(VERSION)) {
outputArray.push(new asn1js.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 asn1js.Sequence({
value: Array.from(this.revokedCertificates, o => o.toSchema())
}));
}
if (this.crlExtensions) {
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
this.crlExtensions.toSchema()
]
}));
}
//#endregion
return (new asn1js.Sequence({
value: outputArray
}));
}
/**
* Convert current object to asn1js object and set correct values
* @returns asn1js object
*/
public toSchema(encodeFlag = false) {
//#region Decode stored TBS value
let tbsSchema;
if (!encodeFlag) {
if (!this.tbsView.byteLength) { // No stored TBS part
return CertificateRevocationList.schema();
}
const asn1 = asn1js.fromBER(this.tbsView);
AsnError.assert(asn1, "TBS Certificate Revocation List");
tbsSchema = asn1.result;
}
//#endregion
//#region Create TBS schema via assembling from TBS parts
else {
tbsSchema = this.encodeTBS();
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
tbsSchema,
this.signatureAlgorithm.toSchema(),
this.signatureValue
]
}));
//#endregion
}
public toJSON(): CertificateRevocationListJson {
const res: CertificateRevocationListJson = {
tbs: pvtsutils.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))
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;
}
/**
* Returns `true` if supplied certificate is revoked, otherwise `false`
* @param certificate
*/
public isCertificateRevoked(certificate: Certificate): boolean {
// Check that issuer of the input certificate is the same with issuer of this CRL
if (!this.issuer.isEqual(certificate.issuer)) {
return false;
}
// Check that there are revoked certificates in this CRL
if (!this.revokedCertificates) {
return false;
}
// Search for input certificate in revoked certificates array
for (const revokedCertificate of this.revokedCertificates) {
if (revokedCertificate.userCertificate.isEqual(certificate.serialNumber)) {
return true;
}
}
return false;
}
/**
* Make a signature for existing CRL data
* @param privateKey Private key for "subjectPublicKeyInfo" structure
* @param hashAlgorithm Hashing algorithm. Default SHA-1
* @param crypto Crypto engine
*/
public async sign(privateKey: CryptoKey, hashAlgorithm = "SHA-1", crypto = common.getCrypto(true)): Promise<void> {
// Get a private key from function parameter
if (!privateKey) {
throw new Error("Need to provide a private key for signing");
}
//#region Get a "default parameters" for current algorithm and set correct signature algorithm
const signatureParameters = await crypto.getSignatureParameters(privateKey, hashAlgorithm);
const { parameters } = signatureParameters;
this.signature = signatureParameters.signatureAlgorithm;
this.signatureAlgorithm = signatureParameters.signatureAlgorithm;
//#endregion
//#region Create TBS data for signing
this.tbsView = new Uint8Array(this.encodeTBS().toBER());
//#endregion
//#region Signing TBS data on provided private key
const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters as any);
this.signatureValue = new asn1js.BitString({ valueHex: signature });
//#endregion
}
/**
* Verify existing signature
* @param parameters
* @param crypto Crypto engine
*/
public async verify(parameters: CertificateRevocationListVerifyParams = {}, crypto = common.getCrypto(true)): Promise<boolean> {
let subjectPublicKeyInfo: PublicKeyInfo | undefined;
//#region Get information about CRL issuer certificate
if (parameters.issuerCertificate) { // "issuerCertificate" must be of type "Certificate"
subjectPublicKeyInfo = parameters.issuerCertificate.subjectPublicKeyInfo;
// The CRL issuer name and "issuerCertificate" subject name are not equal
if (!this.issuer.isEqual(parameters.issuerCertificate.subject)) {
return false;
}
}
//#region In case if there is only public key during verification
if (parameters.publicKeyInfo) {
subjectPublicKeyInfo = parameters.publicKeyInfo; // Must be of type "PublicKeyInfo"
}
//#endregion
if (!subjectPublicKeyInfo) {
throw new Error("Issuer's certificate must be provided as an input parameter");
}
//#endregion
//#region Check the CRL for unknown critical extensions
if (this.crlExtensions) {
for (const extension of this.crlExtensions.extensions) {
if (extension.critical) {
// We can not be sure that unknown extension has no value for CRL signature
if (!WELL_KNOWN_EXTENSIONS.includes(extension.extnID))
return false;
}
}
}
//#endregion
return crypto.verifyWithPublicKey(this.tbsView, this.signatureValue, subjectPublicKeyInfo, this.signatureAlgorithm);
}
}

228
third_party/js/PKI.js/src/CertificateSet.ts поставляемый
Просмотреть файл

@ -1,228 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { Certificate, CertificateJson } from "./Certificate";
import { AttributeCertificateV1, AttributeCertificateV1Json } from "./AttributeCertificateV1";
import { AttributeCertificateV2, AttributeCertificateV2Json } from "./AttributeCertificateV2";
import { OtherCertificateFormat, OtherCertificateFormatJson } from "./OtherCertificateFormat";
import * as Schema from "./Schema";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_STRING } from "./constants";
const CERTIFICATES = "certificates";
const CLEAR_PROPS = [
CERTIFICATES,
];
export interface ICertificateSet {
certificates: CertificateSetItem[];
}
export interface CertificateSetJson {
certificates: CertificateSetItemJson[];
}
export type CertificateSetItemJson = CertificateJson | AttributeCertificateV1Json | AttributeCertificateV2Json | OtherCertificateFormatJson;
export type CertificateSetItem = Certificate | AttributeCertificateV1 | AttributeCertificateV2 | OtherCertificateFormat;
export type CertificateSetParameters = PkiObjectParameters & Partial<ICertificateSet>;
/**
* Represents the CertificateSet structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class CertificateSet extends PkiObject implements ICertificateSet {
public static override CLASS_NAME = "CertificateSet";
public certificates!: CertificateSetItem[];
/**
* Initializes a new instance of the {@link CertificateSet} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertificateSetParameters = {}) {
super();
this.certificates = pvutils.getParametersValue(parameters, CERTIFICATES, CertificateSet.defaultValues(CERTIFICATES));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CERTIFICATES): CertificateSetItem[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CERTIFICATES:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CertificateSet ::= SET OF CertificateChoices
*
* CertificateChoices ::= CHOICE {
* certificate Certificate,
* extendedCertificate [0] IMPLICIT ExtendedCertificate, -- Obsolete
* v1AttrCert [1] IMPLICIT AttributeCertificateV1, -- Obsolete
* v2AttrCert [2] IMPLICIT AttributeCertificateV2,
* other [3] IMPLICIT OtherCertificateFormat }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
certificates?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (
new asn1js.Set({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.certificates || CERTIFICATES),
value: new asn1js.Choice({
value: [
Certificate.schema(),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Any()
]
}), // JUST A STUB
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [
new asn1js.Sequence
]
}),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
value: AttributeCertificateV2.schema().valueBlock.value
}),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
},
value: OtherCertificateFormat.schema().valueBlock.value
})
]
})
})
]
})
);
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CertificateSet.schema()
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
this.certificates = Array.from(asn1.result.certificates || [], (element: any) => {
const initialTagNumber = element.idBlock.tagNumber;
if (element.idBlock.tagClass === 1)
return new Certificate({ schema: element });
//#region Making "Sequence" from "Constructed" value
const elementSequence = new asn1js.Sequence({
value: element.valueBlock.value
});
//#endregion
switch (initialTagNumber) {
case 1:
// WARN: It's possible that CMS contains AttributeCertificateV2 instead of AttributeCertificateV1
// Check the certificate version
if ((elementSequence.valueBlock.value[0] as any).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 });
case 0:
default:
}
return element;
});
//#endregion
}
public toSchema(): asn1js.Set {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Set({
value: Array.from(this.certificates, element => {
switch (true) {
case (element instanceof Certificate):
return element.toSchema();
case (element instanceof AttributeCertificateV1):
return new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 1 // [1]
},
value: element.toSchema().valueBlock.value
});
case (element instanceof AttributeCertificateV2):
return new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 2 // [2]
},
value: element.toSchema().valueBlock.value
});
case (element instanceof OtherCertificateFormat):
return new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: 3 // [3]
},
value: element.toSchema().valueBlock.value
});
default:
}
return element.toSchema();
})
}));
}
public toJSON(): CertificateSetJson {
return {
certificates: Array.from(this.certificates, o => o.toJSON())
};
}
}

Просмотреть файл

@ -1,172 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const TEMPLATE_ID = "templateID";
const TEMPLATE_MAJOR_VERSION = "templateMajorVersion";
const TEMPLATE_MINOR_VERSION = "templateMinorVersion";
const CLEAR_PROPS = [
TEMPLATE_ID,
TEMPLATE_MAJOR_VERSION,
TEMPLATE_MINOR_VERSION
];
export interface ICertificateTemplate {
templateID: string;
templateMajorVersion?: number;
templateMinorVersion?: number;
}
export interface CertificateTemplateJson {
templateID: string;
templateMajorVersion?: number;
templateMinorVersion?: number;
}
export type CertificateTemplateParameters = PkiObjectParameters & Partial<ICertificateTemplate>;
/**
* Class from "[MS-WCCE]: Windows Client Certificate Enrollment Protocol"
*/
export class CertificateTemplate extends PkiObject implements ICertificateTemplate {
public templateID!: string;
public templateMajorVersion?: number;
public templateMinorVersion?: number;
/**
* Initializes a new instance of the {@link CertificateTemplate} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertificateTemplateParameters = {}) {
super();
this.templateID = pvutils.getParametersValue(parameters, TEMPLATE_ID, CertificateTemplate.defaultValues(TEMPLATE_ID));
if (TEMPLATE_MAJOR_VERSION in parameters) {
this.templateMajorVersion = pvutils.getParametersValue(parameters, TEMPLATE_MAJOR_VERSION, CertificateTemplate.defaultValues(TEMPLATE_MAJOR_VERSION));
}
if (TEMPLATE_MINOR_VERSION in parameters) {
this.templateMinorVersion = pvutils.getParametersValue(parameters, TEMPLATE_MINOR_VERSION, CertificateTemplate.defaultValues(TEMPLATE_MINOR_VERSION));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TEMPLATE_MINOR_VERSION): number;
public static override defaultValues(memberName: typeof TEMPLATE_MAJOR_VERSION): number;
public static override defaultValues(memberName: typeof TEMPLATE_ID): string;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TEMPLATE_ID:
return EMPTY_STRING;
case TEMPLATE_MAJOR_VERSION:
case TEMPLATE_MINOR_VERSION:
return 0;
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CertificateTemplateOID ::= SEQUENCE {
* templateID OBJECT IDENTIFIER,
* templateMajorVersion INTEGER (0..4294967295) OPTIONAL,
* templateMinorVersion INTEGER (0..4294967295) OPTIONAL
* }
*```
*/
static override schema(parameters: Schema.SchemaParameters<{
templateID?: string,
templateMajorVersion?: string,
templateMinorVersion?: string,
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.templateID || EMPTY_STRING) }),
new asn1js.Integer({
name: (names.templateMajorVersion || EMPTY_STRING),
optional: true
}),
new asn1js.Integer({
name: (names.templateMinorVersion || EMPTY_STRING),
optional: true
}),
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CertificateTemplate.schema({
names: {
templateID: TEMPLATE_ID,
templateMajorVersion: TEMPLATE_MAJOR_VERSION,
templateMinorVersion: TEMPLATE_MINOR_VERSION
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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;
}
}
public toSchema(): asn1js.Sequence {
// Create array for output sequence
const outputArray = [];
outputArray.push(new asn1js.ObjectIdentifier({ value: this.templateID }));
if (TEMPLATE_MAJOR_VERSION in this) {
outputArray.push(new asn1js.Integer({ value: this.templateMajorVersion }));
}
if (TEMPLATE_MINOR_VERSION in this) {
outputArray.push(new asn1js.Integer({ value: this.templateMinorVersion }));
}
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
}
public toJSON(): CertificateTemplateJson {
const res: CertificateTemplateJson = {
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;
}
}

Просмотреть файл

@ -1,487 +0,0 @@
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import * as common from "./common";
import { PublicKeyInfo, PublicKeyInfoJson } from "./PublicKeyInfo";
import { RelativeDistinguishedNames, RelativeDistinguishedNamesJson, RelativeDistinguishedNamesSchema } from "./RelativeDistinguishedNames";
import { AlgorithmIdentifier, AlgorithmIdentifierJson } from "./AlgorithmIdentifier";
import { Attribute, AttributeJson, AttributeSchema } from "./Attribute";
import * as Schema from "./Schema";
import { CryptoEnginePublicKeyParams } from "./CryptoEngine/CryptoEngineInterface";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_BUFFER } from "./constants";
const TBS = "tbs";
const VERSION = "version";
const SUBJECT = "subject";
const SPKI = "subjectPublicKeyInfo";
const ATTRIBUTES = "attributes";
const SIGNATURE_ALGORITHM = "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 = [
CSR_INFO,
CSR_INFO_VERSION,
CSR_INFO_SUBJECT,
CSR_INFO_SPKI,
CSR_INFO_ATTRS,
SIGNATURE_ALGORITHM,
SIGNATURE_VALUE
];
export interface ICertificationRequest {
/**
* Value being signed
*/
tbs: ArrayBuffer;
/**
* Version number. It should be 0
*/
version: number;
/**
* Distinguished name of the certificate subject
*/
subject: RelativeDistinguishedNames;
/**
* Information about the public key being certified
*/
subjectPublicKeyInfo: PublicKeyInfo;
/**
* Collection of attributes providing additional information about the subject of the certificate
*/
attributes?: Attribute[];
/**
* signature algorithm (and any associated parameters) under which the certification-request information is signed
*/
signatureAlgorithm: AlgorithmIdentifier;
/**
* result of signing the certification request information with the certification request subject's private key
*/
signatureValue: asn1js.BitString;
}
/**
* JSON representation of {@link CertificationRequest}
*/
export interface CertificationRequestJson {
tbs: string;
version: number;
subject: RelativeDistinguishedNamesJson;
subjectPublicKeyInfo: PublicKeyInfoJson | JsonWebKey;
attributes?: AttributeJson[];
signatureAlgorithm: AlgorithmIdentifierJson;
signatureValue: asn1js.BitStringJson;
}
export interface CertificationRequestInfoParameters {
names?: {
blockName?: string;
CertificationRequestInfo?: string;
CertificationRequestInfoVersion?: string;
subject?: RelativeDistinguishedNamesSchema;
CertificationRequestInfoAttributes?: string;
attributes?: AttributeSchema;
};
}
function CertificationRequestInfo(parameters: CertificationRequestInfoParameters = {}) {
//CertificationRequestInfo ::= SEQUENCE {
// version INTEGER { v1(0) } (v1,...),
// subject Name,
// subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
// attributes [0] Attributes{{ CRIAttributes }}
//}
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.CertificationRequestInfo || CSR_INFO),
value: [
new asn1js.Integer({ name: (names.CertificationRequestInfoVersion || CSR_INFO_VERSION) }),
RelativeDistinguishedNames.schema(names.subject || {
names: {
blockName: CSR_INFO_SUBJECT
}
}),
PublicKeyInfo.schema({
names: {
blockName: CSR_INFO_SPKI
}
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Repeated({
optional: true, // Because OpenSSL makes wrong ATTRIBUTES field
name: (names.CertificationRequestInfoAttributes || CSR_INFO_ATTRS),
value: Attribute.schema(names.attributes || {})
})
]
})
]
}));
}
export type CertificationRequestParameters = PkiObjectParameters & Partial<ICertificationRequest>;
/**
* Represents the CertificationRequest structure described in [RFC2986](https://datatracker.ietf.org/doc/html/rfc2986)
*
* @example The following example demonstrates how to parse PKCS#11 certification request
* and verify its challenge password extension and signature value
* ```js
* const pkcs10 = pkijs.CertificationRequest.fromBER(pkcs10Raw);
*
* // Get and validate challenge password extension
* if (pkcs10.attributes) {
* const attrExtensions = pkcs10.attributes.find(o => o.type === "1.2.840.113549.1.9.14"); // pkcs-9-at-extensionRequest
* if (attrExtensions) {
* const extensions = new pkijs.Extensions({ schema: attrExtensions.values[0] });
* for (const extension of extensions.extensions) {
* if (extension.extnID === "1.2.840.113549.1.9.7") { // pkcs-9-at-challengePassword
* const asn = asn1js.fromBER(extension.extnValue.valueBlock.valueHex);
* if (asn.result.valueBlock.value !== "passwordChallenge") {
* throw new Error("PKCS#11 certification request is invalid. Challenge password is incorrect");
* }
* }
* }
* }
* }
*
* // Verify signature value
* const ok = await pkcs10.verify();
* if (!ok) {
* throw Error("PKCS#11 certification request is invalid. Signature is wrong")
* }
* ```
*
* @example The following example demonstrates how to create PKCS#11 certification request
* ```js
* // Get a "crypto" extension
* const crypto = pkijs.getCrypto(true);
*
* const pkcs10 = new pkijs.CertificationRequest();
*
* pkcs10.subject.typesAndValues.push(new pkijs.AttributeTypeAndValue({
* type: "2.5.4.3",
* value: new asn1js.Utf8String({ value: "Test" })
* }));
*
*
* await pkcs10.subjectPublicKeyInfo.importKey(keys.publicKey);
*
* pkcs10.attributes = [];
*
* // Subject Alternative Name
* const altNames = new pkijs.GeneralNames({
* names: [
* new pkijs.GeneralName({ // email
* type: 1,
* value: "email@address.com"
* }),
* new pkijs.GeneralName({ // domain
* type: 2,
* value: "www.domain.com"
* }),
* ]
* });
*
* // SubjectKeyIdentifier
* const subjectKeyIdentifier = await crypto.digest({ name: "SHA-1" }, pkcs10.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHex);
*
* pkcs10.attributes.push(new pkijs.Attribute({
* type: "1.2.840.113549.1.9.14", // pkcs-9-at-extensionRequest
* values: [(new pkijs.Extensions({
* extensions: [
* new pkijs.Extension({
* extnID: "2.5.29.14", // id-ce-subjectKeyIdentifier
* critical: false,
* extnValue: (new asn1js.OctetString({ valueHex: subjectKeyIdentifier })).toBER(false)
* }),
* new pkijs.Extension({
* extnID: "2.5.29.17", // id-ce-subjectAltName
* critical: false,
* extnValue: altNames.toSchema().toBER(false)
* }),
* new pkijs.Extension({
* extnID: "1.2.840.113549.1.9.7", // pkcs-9-at-challengePassword
* critical: false,
* extnValue: (new asn1js.PrintableString({ value: "passwordChallenge" })).toBER(false)
* })
* ]
* })).toSchema()]
* }));
*
* // Signing final PKCS#10 request
* await pkcs10.sign(keys.privateKey, "SHA-256");
*
* const pkcs10Raw = pkcs10.toSchema(true).toBER();
* ```
*/
export class CertificationRequest extends PkiObject implements ICertificationRequest {
public static override CLASS_NAME = "CertificationRequest";
public tbsView!: Uint8Array;
/**
* @deprecated Since version 3.0.0
*/
public get tbs(): ArrayBuffer {
return pvtsutils.BufferSourceConverter.toArrayBuffer(this.tbsView);
}
/**
* @deprecated Since version 3.0.0
*/
public set tbs(value: ArrayBuffer) {
this.tbsView = new Uint8Array(value);
}
public version!: number;
public subject!: RelativeDistinguishedNames;
public subjectPublicKeyInfo!: PublicKeyInfo;
public attributes?: Attribute[];
public signatureAlgorithm!: AlgorithmIdentifier;
public signatureValue!: asn1js.BitString;
/**
* Initializes a new instance of the {@link CertificationRequest} class
* @param parameters Initialization parameters
*/
constructor(parameters: CertificationRequestParameters = {}) {
super();
this.tbsView = new Uint8Array(pvutils.getParametersValue(parameters, TBS, CertificationRequest.defaultValues(TBS)));
this.version = pvutils.getParametersValue(parameters, VERSION, CertificationRequest.defaultValues(VERSION));
this.subject = pvutils.getParametersValue(parameters, SUBJECT, CertificationRequest.defaultValues(SUBJECT));
this.subjectPublicKeyInfo = pvutils.getParametersValue(parameters, SPKI, CertificationRequest.defaultValues(SPKI));
if (ATTRIBUTES in parameters) {
this.attributes = pvutils.getParametersValue(parameters, ATTRIBUTES, CertificationRequest.defaultValues(ATTRIBUTES));
}
this.signatureAlgorithm = pvutils.getParametersValue(parameters, SIGNATURE_ALGORITHM, CertificationRequest.defaultValues(SIGNATURE_ALGORITHM));
this.signatureValue = pvutils.getParametersValue(parameters, SIGNATURE_VALUE, CertificationRequest.defaultValues(SIGNATURE_VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TBS): ArrayBuffer;
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof SUBJECT): RelativeDistinguishedNames;
public static override defaultValues(memberName: typeof SPKI): PublicKeyInfo;
public static override defaultValues(memberName: typeof ATTRIBUTES): Attribute[];
public static override defaultValues(memberName: typeof SIGNATURE_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof SIGNATURE_VALUE): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TBS:
return EMPTY_BUFFER;
case VERSION:
return 0;
case SUBJECT:
return new RelativeDistinguishedNames();
case SPKI:
return new PublicKeyInfo();
case ATTRIBUTES:
return [];
case SIGNATURE_ALGORITHM:
return new AlgorithmIdentifier();
case SIGNATURE_VALUE:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* CertificationRequest ::= SEQUENCE {
* certificationRequestInfo CertificationRequestInfo,
* signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
* signature BIT STRING
* }
*```
*/
static override schema(parameters: Schema.SchemaParameters<{
certificationRequestInfo?: CertificationRequestInfoParameters;
signatureAlgorithm?: string;
signatureValue?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
value: [
CertificationRequestInfo(names.certificationRequestInfo || {}),
new asn1js.Sequence({
name: (names.signatureAlgorithm || SIGNATURE_ALGORITHM),
value: [
new asn1js.ObjectIdentifier(),
new asn1js.Any({ optional: true })
]
}),
new asn1js.BitString({ name: (names.signatureValue || SIGNATURE_VALUE) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
CertificationRequest.schema()
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.tbsView = (asn1.result.CertificationRequestInfo as asn1js.Sequence).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;
}
/**
* Aux function making ASN1js Sequence from current TBS
* @returns
*/
protected encodeTBS(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [
new asn1js.Integer({ value: this.version }),
this.subject.toSchema(),
this.subjectPublicKeyInfo.toSchema()
];
if (ATTRIBUTES in this) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: Array.from(this.attributes || [], o => o.toSchema())
}));
}
//#endregion
return (new asn1js.Sequence({
value: outputArray
}));
}
public toSchema(encodeFlag = false): asn1js.Sequence {
let tbsSchema;
if (encodeFlag === false) {
if (this.tbsView.byteLength === 0) { // No stored TBS part
return CertificationRequest.schema();
}
const asn1 = asn1js.fromBER(this.tbsView);
AsnError.assert(asn1, "PKCS#10 Certificate Request");
tbsSchema = asn1.result;
} else {
tbsSchema = this.encodeTBS();
}
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
tbsSchema,
this.signatureAlgorithm.toSchema(),
this.signatureValue
]
}));
//#endregion
}
public toJSON(): CertificationRequestJson {
const object: CertificationRequestJson = {
tbs: pvtsutils.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 in this) {
object.attributes = Array.from(this.attributes || [], o => o.toJSON());
}
return object;
}
/**
* Makes signature for current certification request
* @param privateKey WebCrypto private key
* @param hashAlgorithm String representing current hashing algorithm
* @param crypto Crypto engine
*/
async sign(privateKey: CryptoKey, hashAlgorithm = "SHA-1", crypto = common.getCrypto(true)): Promise<void> {
// Initial checking
if (!privateKey) {
throw new Error("Need to provide a private key for signing");
}
//#region Get a "default parameters" for current algorithm and set correct signature algorithm
const signatureParams = await crypto.getSignatureParameters(privateKey, hashAlgorithm);
const parameters = signatureParams.parameters;
this.signatureAlgorithm = signatureParams.signatureAlgorithm;
//#endregion
//#region Create TBS data for signing
this.tbsView = new Uint8Array(this.encodeTBS().toBER());
//#endregion
//#region Signing TBS data on provided private key
const signature = await crypto.signWithPrivateKey(this.tbsView, privateKey, parameters as any);
this.signatureValue = new asn1js.BitString({ valueHex: signature });
//#endregion
}
/**
* Verify existing certification request signature
* @param crypto Crypto engine
* @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);
}
/**
* Importing public key for current certificate request
* @param parameters
* @param crypto Crypto engine
* @returns WebCrypt public key
*/
public async getPublicKey(parameters?: CryptoEnginePublicKeyParams, crypto = common.getCrypto(true)): Promise<CryptoKey> {
return crypto.getPublicKey(this.subjectPublicKeyInfo, this.signatureAlgorithm, parameters);
}
}

171
third_party/js/PKI.js/src/ContentInfo.ts поставляемый
Просмотреть файл

@ -1,171 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { id_ContentType_Data, id_ContentType_EncryptedData, id_ContentType_EnvelopedData, id_ContentType_SignedData } from "./ObjectIdentifiers";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const CONTENT_TYPE = "contentType";
const CONTENT = "content";
const CLEAR_PROPS = [CONTENT_TYPE, CONTENT];
export interface IContentInfo {
contentType: string;
content: any;
}
export type ContentInfoParameters = PkiObjectParameters & Partial<IContentInfo>;
export type ContentInfoSchema = Schema.SchemaParameters<{
contentType?: string;
content?: string;
}>;
export interface ContentInfoJson {
contentType: string;
content?: any;
}
/**
* Represents the ContentInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class ContentInfo extends PkiObject implements IContentInfo {
public static override CLASS_NAME = "ContentInfo";
public static readonly DATA = id_ContentType_Data;
public static readonly SIGNED_DATA = id_ContentType_SignedData;
public static readonly ENVELOPED_DATA = id_ContentType_EnvelopedData;
public static readonly ENCRYPTED_DATA = id_ContentType_EncryptedData;
public contentType!: string;
public content: any;
/**
* Initializes a new instance of the {@link ContentInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: ContentInfoParameters = {}) {
super();
this.contentType = pvutils.getParametersValue(parameters, CONTENT_TYPE, ContentInfo.defaultValues(CONTENT_TYPE));
this.content = pvutils.getParametersValue(parameters, CONTENT, ContentInfo.defaultValues(CONTENT));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CONTENT_TYPE): string;
public static override defaultValues(memberName: typeof CONTENT): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CONTENT_TYPE:
return EMPTY_STRING;
case CONTENT:
return new asn1js.Any();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
static compareWithDefault<T>(memberName: string, memberValue: T): memberValue is T {
switch (memberName) {
case CONTENT_TYPE:
return (typeof memberValue === "string" &&
memberValue === this.defaultValues(CONTENT_TYPE));
case CONTENT:
return (memberValue instanceof asn1js.Any);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* ContentInfo ::= SEQUENCE {
* contentType ContentType,
* content [0] EXPLICIT ANY DEFINED BY contentType }
*```
*/
public static override schema(parameters: ContentInfoSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
if (("optional" in names) === false) {
names.optional = false;
}
return (new asn1js.Sequence({
name: (names.blockName || "ContentInfo"),
optional: names.optional,
value: [
new asn1js.ObjectIdentifier({ name: (names.contentType || CONTENT_TYPE) }),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [new asn1js.Any({ name: (names.content || CONTENT) })] // EXPLICIT ANY value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
ContentInfo.schema()
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.contentType = asn1.result.contentType.valueBlock.toString();
this.content = asn1.result.content;
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.contentType }),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [this.content] // EXPLICIT ANY value
})
]
}));
//#endregion
}
public toJSON(): ContentInfoJson {
const object: ContentInfoJson = {
contentType: this.contentType
};
if (!(this.content instanceof asn1js.Any)) {
object.content = this.content.toJSON();
}
return object;
}
}

Просмотреть файл

@ -1,111 +0,0 @@
import { BitString, OctetString } from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier } from "../AlgorithmIdentifier";
import { EMPTY_STRING } from "../constants";
import { EncryptedContentInfo } from "../EncryptedContentInfo";
import { PublicKeyInfo } from "../PublicKeyInfo";
import * as type from "./CryptoEngineInterface";
export abstract class AbstractCryptoEngine implements type.ICryptoEngine {
public name: string;
public crypto: Crypto;
public subtle: SubtleCrypto;
/**
* Constructor for CryptoEngine class
* @param parameters
*/
constructor(parameters: type.CryptoEngineParameters) {
this.crypto = parameters.crypto;
this.subtle = "webkitSubtle" in parameters.crypto
? (parameters.crypto as any).webkitSubtle
: parameters.crypto.subtle;
this.name = pvutils.getParametersValue(parameters, "name", EMPTY_STRING);
}
public abstract getOIDByAlgorithm(algorithm: Algorithm, safety?: boolean, target?: string): string;
public abstract getAlgorithmParameters(algorithmName: string, operation: type.CryptoEngineAlgorithmOperation): type.CryptoEngineAlgorithmParams;
public abstract getAlgorithmByOID<T extends Algorithm = Algorithm>(oid: string, safety?: boolean, target?: string): object | T;
public abstract getAlgorithmByOID<T extends Algorithm = Algorithm>(oid: string, safety: true, target?: string): T;
public abstract getAlgorithmByOID(oid: any, safety?: any, target?: any): object;
public abstract getHashAlgorithm(signatureAlgorithm: AlgorithmIdentifier): string;
public abstract getSignatureParameters(privateKey: CryptoKey, hashAlgorithm?: string): Promise<type.CryptoEngineSignatureParams>;
public abstract signWithPrivateKey(data: BufferSource, privateKey: CryptoKey, parameters: type.CryptoEngineSignWithPrivateKeyParams): Promise<ArrayBuffer>;
public abstract verifyWithPublicKey(data: BufferSource, signature: BitString | OctetString, publicKeyInfo: PublicKeyInfo, signatureAlgorithm: AlgorithmIdentifier, shaAlgorithm?: string): Promise<boolean>;
public abstract getPublicKey(publicKeyInfo: PublicKeyInfo, signatureAlgorithm: AlgorithmIdentifier, parameters?: type.CryptoEnginePublicKeyParams): Promise<CryptoKey>;
public abstract encryptEncryptedContentInfo(parameters: type.CryptoEngineEncryptParams): Promise<EncryptedContentInfo>;
public abstract decryptEncryptedContentInfo(parameters: type.CryptoEngineDecryptParams): Promise<ArrayBuffer>;
public abstract stampDataWithPassword(parameters: type.CryptoEngineStampDataWithPasswordParams): Promise<ArrayBuffer>;
public abstract verifyDataStampedWithPassword(parameters: type.CryptoEngineVerifyDataStampedWithPasswordParams): Promise<boolean>;
public async encrypt(algorithm: globalThis.AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
public async encrypt(...args: any[]): Promise<ArrayBuffer> {
return (this.subtle.encrypt as any)(...args);
}
public decrypt(algorithm: globalThis.AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
public async decrypt(...args: any[]): Promise<ArrayBuffer> {
return (this.subtle.decrypt as any)(...args);
}
public sign(algorithm: globalThis.AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
public sign(...args: any[]): Promise<ArrayBuffer> {
return (this.subtle.sign as any)(...args);
}
public verify(algorithm: globalThis.AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>;
public async verify(...args: any[]): Promise<boolean> {
return (this.subtle.verify as any)(...args);
}
public digest(algorithm: globalThis.AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>;
public async digest(...args: any[]) {
return (this.subtle.digest as any)(...args);
}
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>;
public async generateKey(...args: any[]): Promise<CryptoKey | CryptoKeyPair> {
return (this.subtle.generateKey as any)(...args);
}
public deriveKey(algorithm: globalThis.AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: globalThis.AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
public deriveKey(algorithm: globalThis.AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: globalThis.AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
public async deriveKey(...args: any[]): Promise<CryptoKey> {
return (this.subtle.deriveKey as any)(...args);
}
public deriveBits(algorithm: globalThis.AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>;
public async deriveBits(...args: any[]): Promise<ArrayBuffer> {
return (this.subtle.deriveBits as any)(...args);
}
public wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: globalThis.AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise<ArrayBuffer>;
public async wrapKey(...args: any[]): Promise<ArrayBuffer> {
return (this.subtle.wrapKey as any)(...args);
}
public unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: globalThis.AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: globalThis.AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
public unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: globalThis.AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: globalThis.AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
public async unwrapKey(...args: any[]): Promise<CryptoKey> {
return (this.subtle.unwrapKey as any)(...args);
}
exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>;
exportKey(format: "pkcs8" | "raw" | "spki", key: CryptoKey): Promise<ArrayBuffer>;
exportKey(...args: any[]): Promise<ArrayBuffer> | Promise<JsonWebKey> {
return (this.subtle.exportKey as any)(...args);
}
importKey(format: "jwk", keyData: JsonWebKey, algorithm: globalThis.AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
importKey(format: "pkcs8" | "raw" | "spki", keyData: BufferSource, algorithm: globalThis.AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
importKey(format: "jwk", keyData: JsonWebKey, algorithm: globalThis.AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
importKey(format: "pkcs8" | "raw" | "spki", keyData: BufferSource, algorithm: globalThis.AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
importKey(...args: any[]): Promise<CryptoKey> {
return (this.subtle.importKey as any)(...args);
}
public getRandomValues<T extends ArrayBufferView | null>(array: T): T {
return this.crypto.getRandomValues(array);
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,23 +0,0 @@
import * as common from "../common";
import { CryptoEngine } from "./CryptoEngine";
export function initCryptoEngine() {
if (typeof self !== "undefined") {
if ("crypto" in self) {
let engineName = "webcrypto";
// Apple Safari support
if ("webkitSubtle" in self.crypto) {
engineName = "safari";
}
common.setEngine(engineName, new CryptoEngine({ name: engineName, crypto: crypto }));
}
} else if (typeof crypto !== "undefined" && "webcrypto" in crypto) {
// NodeJS ^15
const name = "NodeJS ^15";
const nodeCrypto = (crypto as any).webcrypto as Crypto;
common.setEngine(name, new CryptoEngine({ name, crypto: nodeCrypto }));
}
}

Просмотреть файл

@ -1,183 +0,0 @@
import type * as asn1js from "asn1js";
import type { AlgorithmIdentifier } from "../AlgorithmIdentifier";
import type { EncryptedContentInfo } from "../EncryptedContentInfo";
import type { PublicKeyInfo } from "../PublicKeyInfo";
export type CryptoEngineAlgorithmOperation = "sign" | "encrypt" | "generateKey" | "importKey" | "exportKey" | "verify";
/**
* Algorithm parameters
*/
export interface CryptoEngineAlgorithmParams {
/**
* Algorithm
*/
algorithm: Algorithm | object;
/**
* Key usages
*/
usages: KeyUsage[];
}
export interface CryptoEngineSignatureParams {
signatureAlgorithm: AlgorithmIdentifier;
parameters: CryptoEngineAlgorithmParams;
}
export interface CryptoEngineSignWithPrivateKeyParams {
algorithm: Algorithm;
}
/**
* Public key parameters
*/
export interface CryptoEnginePublicKeyParams {
/**
* Algorithm
*/
algorithm: CryptoEngineAlgorithmParams;
}
export type ContentEncryptionAesCbcParams = AesCbcParams & AesDerivedKeyParams;
export type ContentEncryptionAesGcmParams = AesGcmParams & AesDerivedKeyParams;
export type ContentEncryptionAlgorithm = ContentEncryptionAesCbcParams | ContentEncryptionAesGcmParams;
export interface CryptoEngineEncryptParams {
password: ArrayBuffer;
contentEncryptionAlgorithm: ContentEncryptionAlgorithm;
hmacHashAlgorithm: string;
iterationCount: number;
contentToEncrypt: ArrayBuffer;
contentType: string;
}
export interface CryptoEngineDecryptParams {
password: ArrayBuffer;
encryptedContentInfo: EncryptedContentInfo;
}
export interface CryptoEngineStampDataWithPasswordParams {
password: ArrayBuffer;
hashAlgorithm: string;
salt: ArrayBuffer;
iterationCount: number;
contentToStamp: ArrayBuffer;
}
export interface CryptoEngineVerifyDataStampedWithPasswordParams {
password: ArrayBuffer;
hashAlgorithm: string;
salt: ArrayBuffer;
iterationCount: number;
contentToVerify: ArrayBuffer;
signatureToVerify: ArrayBuffer;
}
export interface ICryptoEngine extends SubtleCrypto {
name: string;
crypto: Crypto;
subtle: SubtleCrypto;
getRandomValues<T extends ArrayBufferView | null>(array: T): T;
/**
* Get OID for each specific algorithm
* @param algorithm WebCrypto Algorithm
* @param safety If `true` throws exception on unknown algorithm. Default is `false`
* @param target Name of the target
* @throws Throws {@link Error} exception if unknown WebCrypto algorithm
*/
getOIDByAlgorithm(algorithm: Algorithm, safety?: boolean, target?: string): string;
/**
* Get default algorithm parameters for each kind of operation
* @param algorithmName Algorithm name to get common parameters for
* @param operation Kind of operation: "sign", "encrypt", "generateKey", "importKey", "exportKey", "verify"
*/
// TODO Use safety
getAlgorithmParameters(algorithmName: string, operation: CryptoEngineAlgorithmOperation): CryptoEngineAlgorithmParams;
/**
* Gets WebCrypto algorithm by wel-known OID
* @param oid algorithm identifier
* @param safety if `true` throws exception on unknown algorithm identifier
* @param target name of the target
* @returns Returns WebCrypto algorithm or an empty object
*/
getAlgorithmByOID<T extends Algorithm = Algorithm>(oid: string, safety?: boolean, target?: string): T | object;
/**
* Gets WebCrypto algorithm by wel-known OID
* @param oid algorithm identifier
* @param safety if `true` throws exception on unknown algorithm identifier
* @param target name of the target
* @returns Returns WebCrypto algorithm
* @throws Throws {@link Error} exception if unknown algorithm identifier
*/
getAlgorithmByOID<T extends Algorithm = Algorithm>(oid: string, safety: true, target?: string): T;
/**
* Getting hash algorithm by signature algorithm
* @param signatureAlgorithm Signature algorithm
*/
// TODO use safety
getHashAlgorithm(signatureAlgorithm: AlgorithmIdentifier): string;
/**
* Get signature parameters by analyzing private key algorithm
* @param privateKey The private key user would like to use
* @param hashAlgorithm Hash algorithm user would like to use. Default is SHA-1
*/
getSignatureParameters(privateKey: CryptoKey, hashAlgorithm?: string): Promise<CryptoEngineSignatureParams>;
/**
* Sign data with pre-defined private key
* @param data Data to be signed
* @param privateKey Private key to use
* @param parameters Parameters for used algorithm
*/
signWithPrivateKey(data: BufferSource, privateKey: CryptoKey, parameters: CryptoEngineSignWithPrivateKeyParams): Promise<ArrayBuffer>;
/**
* Verify data with the public key
* @param data Data to be verified
* @param signature Signature value
* @param publicKeyInfo Public key information
* @param signatureAlgorithm Signature algorithm
* @param shaAlgorithm Hash algorithm
*/
verifyWithPublicKey(data: BufferSource, signature: asn1js.BitString | asn1js.OctetString, publicKeyInfo: PublicKeyInfo, signatureAlgorithm: AlgorithmIdentifier, shaAlgorithm?: string): Promise<boolean>;
getPublicKey(publicKeyInfo: PublicKeyInfo, signatureAlgorithm: AlgorithmIdentifier, parameters?: CryptoEnginePublicKeyParams): Promise<CryptoKey>;
/**
* Specialized function encrypting "EncryptedContentInfo" object using parameters
* @param parameters
*/
encryptEncryptedContentInfo(parameters: CryptoEngineEncryptParams): Promise<EncryptedContentInfo>;
/**
* Decrypt data stored in "EncryptedContentInfo" object using parameters
* @param parameters
*/
decryptEncryptedContentInfo(parameters: CryptoEngineDecryptParams): Promise<ArrayBuffer>;
/**
* Stamping (signing) data using algorithm similar to HMAC
* @param parameters
*/
stampDataWithPassword(parameters: CryptoEngineStampDataWithPasswordParams): Promise<ArrayBuffer>;
verifyDataStampedWithPassword(parameters: CryptoEngineVerifyDataStampedWithPasswordParams): Promise<boolean>;
}
export interface CryptoEngineParameters {
name?: string;
crypto: Crypto;
/**
* @deprecated
*/
subtle?: SubtleCrypto;
}
export interface CryptoEngineConstructor {
new(params: CryptoEngineParameters): ICryptoEngine;
}

162
third_party/js/PKI.js/src/DigestInfo.ts поставляемый
Просмотреть файл

@ -1,162 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const DIGEST_ALGORITHM = "digestAlgorithm";
const DIGEST = "digest";
const CLEAR_PROPS = [
DIGEST_ALGORITHM,
DIGEST
];
export interface IDigestInfo {
digestAlgorithm: AlgorithmIdentifier;
digest: asn1js.OctetString;
}
export interface DigestInfoJson {
digestAlgorithm: AlgorithmIdentifierJson;
digest: asn1js.OctetStringJson;
}
export type DigestInfoParameters = PkiObjectParameters & Partial<IDigestInfo>;
export type DigestInfoSchema = Schema.SchemaParameters<{
digestAlgorithm?: AlgorithmIdentifierSchema;
digest?: string;
}>;
/**
* Represents the DigestInfo structure described in [RFC3447](https://datatracker.ietf.org/doc/html/rfc3447)
*/
export class DigestInfo extends PkiObject implements IDigestInfo {
public static override CLASS_NAME = "DigestInfo";
public digestAlgorithm!: AlgorithmIdentifier;
public digest!: asn1js.OctetString;
/**
* Initializes a new instance of the {@link DigestInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: DigestInfoParameters = {}) {
super();
this.digestAlgorithm = pvutils.getParametersValue(parameters, DIGEST_ALGORITHM, DigestInfo.defaultValues(DIGEST_ALGORITHM));
this.digest = pvutils.getParametersValue(parameters, DIGEST, DigestInfo.defaultValues(DIGEST));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof DIGEST_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof DIGEST): asn1js.OctetString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case DIGEST_ALGORITHM:
return new AlgorithmIdentifier();
case DIGEST:
return new asn1js.OctetString();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case DIGEST_ALGORITHM:
return ((AlgorithmIdentifier.compareWithDefault("algorithmId", memberValue.algorithmId)) &&
(("algorithmParams" in memberValue) === false));
case DIGEST:
return (memberValue.isEqual(DigestInfo.defaultValues(memberName)));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* DigestInfo ::= SEQUENCE {
* digestAlgorithm DigestAlgorithmIdentifier,
* digest Digest }
*
* Digest ::= OCTET STRING
*```
*/
public static override schema(parameters: DigestInfoSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AlgorithmIdentifier.schema(names.digestAlgorithm || {
names: {
blockName: DIGEST_ALGORITHM
}
}),
new asn1js.OctetString({ name: (names.digest || DIGEST) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
DigestInfo.schema({
names: {
digestAlgorithm: {
names: {
blockName: DIGEST_ALGORITHM
}
},
digest: DIGEST
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.digestAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.digestAlgorithm });
this.digest = asn1.result.digest;
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
this.digestAlgorithm.toSchema(),
this.digest
]
}));
}
public toJSON(): DigestInfoJson {
return {
digestAlgorithm: this.digestAlgorithm.toJSON(),
digest: this.digest.toJSON(),
};
}
}

328
third_party/js/PKI.js/src/DistributionPoint.ts поставляемый
Просмотреть файл

@ -1,328 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { GeneralName, GeneralNameJson } from "./GeneralName";
import { DistributionPointName, DistributionPointNameJson } from "./IssuingDistributionPoint";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { RelativeDistinguishedNames } from "./RelativeDistinguishedNames";
import * as Schema from "./Schema";
const DISTRIBUTION_POINT = "distributionPoint";
const DISTRIBUTION_POINT_NAMES = "distributionPointNames";
const REASONS = "reasons";
const CRL_ISSUER = "cRLIssuer";
const CRL_ISSUER_NAMES = "cRLIssuerNames";
const CLEAR_PROPS = [
DISTRIBUTION_POINT,
DISTRIBUTION_POINT_NAMES,
REASONS,
CRL_ISSUER,
CRL_ISSUER_NAMES,
];
export interface IDistributionPoint {
distributionPoint?: DistributionPointName;
reasons?: asn1js.BitString;
cRLIssuer?: GeneralName[];
}
export interface DistributionPointJson {
distributionPoint?: DistributionPointNameJson;
reasons?: asn1js.BitStringJson;
cRLIssuer?: GeneralNameJson[];
}
export type DistributionPointParameters = PkiObjectParameters & Partial<IDistributionPoint>;
/**
* Represents the DistributionPoint structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class DistributionPoint extends PkiObject implements IDistributionPoint {
public static override CLASS_NAME = "DistributionPoint";
public distributionPoint?: DistributionPointName;
public reasons?: asn1js.BitString;
public cRLIssuer?: GeneralName[];
/**
* Initializes a new instance of the {@link DistributionPoint} class
* @param parameters Initialization parameters
*/
constructor(parameters: DistributionPointParameters = {}) {
super();
if (DISTRIBUTION_POINT in parameters) {
this.distributionPoint = pvutils.getParametersValue(parameters, DISTRIBUTION_POINT, DistributionPoint.defaultValues(DISTRIBUTION_POINT));
}
if (REASONS in parameters) {
this.reasons = pvutils.getParametersValue(parameters, REASONS, DistributionPoint.defaultValues(REASONS));
}
if (CRL_ISSUER in parameters) {
this.cRLIssuer = pvutils.getParametersValue(parameters, CRL_ISSUER, DistributionPoint.defaultValues(CRL_ISSUER));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof DISTRIBUTION_POINT): DistributionPointName;
public static override defaultValues(memberName: typeof REASONS): asn1js.BitString;
public static override defaultValues(memberName: typeof CRL_ISSUER): GeneralName[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case DISTRIBUTION_POINT:
return [];
case REASONS:
return new asn1js.BitString();
case CRL_ISSUER:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* DistributionPoint ::= SEQUENCE {
* distributionPoint [0] DistributionPointName OPTIONAL,
* reasons [1] ReasonFlags OPTIONAL,
* cRLIssuer [2] GeneralNames OPTIONAL }
*
* DistributionPointName ::= CHOICE {
* fullName [0] GeneralNames,
* nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
*
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
* cACompromise (2),
* affiliationChanged (3),
* superseded (4),
* cessationOfOperation (5),
* certificateHold (6),
* privilegeWithdrawn (7),
* aACompromise (8) }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
distributionPoint?: string;
distributionPointNames?: string;
reasons?: string;
cRLIssuer?: string;
cRLIssuerNames?: string;
}> = {}): Schema.SchemaType {
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [distributionPoint]
* @property {string} [distributionPointNames]
* @property {string} [reasons]
* @property {string} [cRLIssuer]
* @property {string} [cRLIssuerNames]
*/
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Choice({
value: [
new asn1js.Constructed({
name: (names.distributionPoint || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Repeated({
name: (names.distributionPointNames || EMPTY_STRING),
value: GeneralName.schema()
})
]
}),
new asn1js.Constructed({
name: (names.distributionPoint || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: RelativeDistinguishedNames.schema().valueBlock.value
})
]
})
]
}),
new asn1js.Primitive({
name: (names.reasons || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
}
}), // IMPLICIT BitString value
new asn1js.Constructed({
name: (names.cRLIssuer || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
value: [
new asn1js.Repeated({
name: (names.cRLIssuerNames || EMPTY_STRING),
value: GeneralName.schema()
})
]
}) // IMPLICIT BitString value
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
DistributionPoint.schema({
names: {
distributionPoint: DISTRIBUTION_POINT,
distributionPointNames: DISTRIBUTION_POINT_NAMES,
reasons: REASONS,
cRLIssuer: CRL_ISSUER,
cRLIssuerNames: CRL_ISSUER_NAMES
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
if (DISTRIBUTION_POINT in asn1.result) {
if (asn1.result.distributionPoint.idBlock.tagNumber === 0) { // GENERAL_NAMES variant
this.distributionPoint = Array.from(asn1.result.distributionPointNames, element => new GeneralName({ schema: element }));
}
if (asn1.result.distributionPoint.idBlock.tagNumber === 1) {// RDN variant
this.distributionPoint = new RelativeDistinguishedNames({
schema: new asn1js.Sequence({
value: asn1.result.distributionPoint.valueBlock.value
})
});
}
}
if (REASONS in asn1.result) {
this.reasons = new asn1js.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 }));
}
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
if (this.distributionPoint) {
let internalValue;
if (this.distributionPoint instanceof Array) {
internalValue = new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: Array.from(this.distributionPoint, o => o.toSchema())
});
} else {
internalValue = new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [this.distributionPoint.toSchema()]
});
}
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [internalValue]
}));
}
if (this.reasons) {
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
valueHex: this.reasons.valueBlock.valueHexView
}));
}
if (this.cRLIssuer) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
value: Array.from(this.cRLIssuer, o => o.toSchema())
}));
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): DistributionPointJson {
const object: DistributionPointJson = {};
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;
}
}

213
third_party/js/PKI.js/src/ECCCMSSharedInfo.ts поставляемый
Просмотреть файл

@ -1,213 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const KEY_INFO = "keyInfo";
const ENTITY_U_INFO = "entityUInfo";
const SUPP_PUB_INFO = "suppPubInfo";
const CLEAR_PROPS = [
KEY_INFO,
ENTITY_U_INFO,
SUPP_PUB_INFO
];
export interface IECCCMSSharedInfo {
keyInfo: AlgorithmIdentifier;
entityUInfo?: asn1js.OctetString;
suppPubInfo: asn1js.OctetString;
}
export interface ECCCMSSharedInfoJson {
keyInfo: AlgorithmIdentifierJson;
entityUInfo?: asn1js.OctetStringJson;
suppPubInfo: asn1js.OctetStringJson;
}
export type ECCCMSSharedInfoParameters = PkiObjectParameters & Partial<IECCCMSSharedInfo>;
/**
* Represents the ECCCMSSharedInfo structure described in [RFC6318](https://datatracker.ietf.org/doc/html/rfc6318)
*/
export class ECCCMSSharedInfo extends PkiObject implements IECCCMSSharedInfo {
public static override CLASS_NAME = "ECCCMSSharedInfo";
public keyInfo!: AlgorithmIdentifier;
public entityUInfo?: asn1js.OctetString;
public suppPubInfo!: asn1js.OctetString;
/**
* Initializes a new instance of the {@link ECCCMSSharedInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: ECCCMSSharedInfoParameters = {}) {
super();
this.keyInfo = pvutils.getParametersValue(parameters, KEY_INFO, ECCCMSSharedInfo.defaultValues(KEY_INFO));
if (ENTITY_U_INFO in parameters) {
this.entityUInfo = pvutils.getParametersValue(parameters, ENTITY_U_INFO, ECCCMSSharedInfo.defaultValues(ENTITY_U_INFO));
}
this.suppPubInfo = pvutils.getParametersValue(parameters, SUPP_PUB_INFO, ECCCMSSharedInfo.defaultValues(SUPP_PUB_INFO));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof KEY_INFO): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ENTITY_U_INFO): asn1js.OctetString;
public static override defaultValues(memberName: typeof SUPP_PUB_INFO): asn1js.OctetString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case KEY_INFO:
return new AlgorithmIdentifier();
case ENTITY_U_INFO:
return new asn1js.OctetString();
case SUPP_PUB_INFO:
return new asn1js.OctetString();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case KEY_INFO:
case ENTITY_U_INFO:
case SUPP_PUB_INFO:
return (memberValue.isEqual(ECCCMSSharedInfo.defaultValues(memberName as typeof SUPP_PUB_INFO)));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* ECC-CMS-SharedInfo ::= SEQUENCE {
* keyInfo AlgorithmIdentifier,
* entityUInfo [0] EXPLICIT OCTET STRING OPTIONAL,
* suppPubInfo [2] EXPLICIT OCTET STRING }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
keyInfo?: AlgorithmIdentifierSchema;
entityUInfo?: string;
suppPubInfo?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AlgorithmIdentifier.schema(names.keyInfo || {}),
new asn1js.Constructed({
name: (names.entityUInfo || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
optional: true,
value: [new asn1js.OctetString()]
}),
new asn1js.Constructed({
name: (names.suppPubInfo || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
value: [new asn1js.OctetString()]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
ECCCMSSharedInfo.schema({
names: {
keyInfo: {
names: {
blockName: KEY_INFO
}
},
entityUInfo: ENTITY_U_INFO,
suppPubInfo: SUPP_PUB_INFO
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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];
}
public toSchema(): asn1js.Sequence {
//#region Create output array for sequence
const outputArray = [];
outputArray.push(this.keyInfo.toSchema());
if (this.entityUInfo) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [this.entityUInfo]
}));
}
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
value: [this.suppPubInfo]
}));
//#endregion
//#region Construct and return new ASN.1 schema for this object
return new asn1js.Sequence({
value: outputArray
});
//#endregion
}
public toJSON(): ECCCMSSharedInfoJson {
const res: ECCCMSSharedInfoJson = {
keyInfo: this.keyInfo.toJSON(),
suppPubInfo: this.suppPubInfo.toJSON(),
};
if (this.entityUInfo) {
res.entityUInfo = this.entityUInfo.toJSON();
}
return res;
}
}

53
third_party/js/PKI.js/src/ECNamedCurves.ts поставляемый
Просмотреть файл

@ -1,53 +0,0 @@
export interface ECNamedCurve {
/**
* The curve ASN.1 object identifier
*/
id: string;
/**
* The name of the curve
*/
name: string;
/**
* The coordinate length in bytes
*/
size: number;
}
export class ECNamedCurves {
public static readonly namedCurves: Record<string, ECNamedCurve> = {};
/**
* Registers an ECC named curve
* @param name The name o the curve
* @param id The curve ASN.1 object identifier
* @param size The coordinate length in bytes
*/
public static register(name: string, id: string, size: number): void {
this.namedCurves[name.toLowerCase()] = this.namedCurves[id] = { name, id, size };
}
/**
* Returns an ECC named curve object
* @param nameOrId Name or identifier of the named curve
* @returns
*/
static find(nameOrId: string): ECNamedCurve | null {
return this.namedCurves[nameOrId.toLowerCase()] || null;
}
static {
// Register default curves
// NIST
this.register("P-256", "1.2.840.10045.3.1.7", 32);
this.register("P-384", "1.3.132.0.34", 48);
this.register("P-521", "1.3.132.0.35", 66);
// Brainpool
this.register("brainpoolP256r1", "1.3.36.3.3.2.8.1.1.7", 32);
this.register("brainpoolP384r1", "1.3.36.3.3.2.8.1.1.11", 48);
this.register("brainpoolP512r1", "1.3.36.3.3.2.8.1.1.13", 64);
}
}

297
third_party/js/PKI.js/src/ECPrivateKey.ts поставляемый
Просмотреть файл

@ -1,297 +0,0 @@
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { ECNamedCurves } from "./ECNamedCurves";
import { ECPublicKey, ECPublicKeyParameters } from "./ECPublicKey";
import { AsnError, ParameterError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const VERSION = "version";
const PRIVATE_KEY = "privateKey";
const NAMED_CURVE = "namedCurve";
const PUBLIC_KEY = "publicKey";
const CLEAR_PROPS = [
VERSION,
PRIVATE_KEY,
NAMED_CURVE,
PUBLIC_KEY
];
export interface IECPrivateKey {
version: number;
privateKey: asn1js.OctetString;
namedCurve?: string;
publicKey?: ECPublicKey;
}
export type ECPrivateKeyParameters = PkiObjectParameters & Partial<IECPrivateKey> & { json?: ECPrivateKeyJson; };
export interface ECPrivateKeyJson {
crv: string;
y?: string;
x?: string;
d: string;
}
/**
* Represents the PrivateKeyInfo structure described in [RFC5915](https://datatracker.ietf.org/doc/html/rfc5915)
*/
export class ECPrivateKey extends PkiObject implements IECPrivateKey {
public static override CLASS_NAME = "ECPrivateKey";
public version!: number;
public privateKey!: asn1js.OctetString;
public namedCurve?: string;
public publicKey?: ECPublicKey;
/**
* Initializes a new instance of the {@link ECPrivateKey} class
* @param parameters Initialization parameters
*/
constructor(parameters: ECPrivateKeyParameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, ECPrivateKey.defaultValues(VERSION));
this.privateKey = pvutils.getParametersValue(parameters, PRIVATE_KEY, ECPrivateKey.defaultValues(PRIVATE_KEY));
if (NAMED_CURVE in parameters) {
this.namedCurve = pvutils.getParametersValue(parameters, NAMED_CURVE, ECPrivateKey.defaultValues(NAMED_CURVE));
}
if (PUBLIC_KEY in parameters) {
this.publicKey = pvutils.getParametersValue(parameters, PUBLIC_KEY, ECPrivateKey.defaultValues(PUBLIC_KEY));
}
if (parameters.json) {
this.fromJSON(parameters.json);
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): 1;
public static override defaultValues(memberName: typeof PRIVATE_KEY): asn1js.OctetString;
public static override defaultValues(memberName: typeof NAMED_CURVE): string;
public static override defaultValues(memberName: typeof PUBLIC_KEY): ECPublicKey;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return 1;
case PRIVATE_KEY:
return new asn1js.OctetString();
case NAMED_CURVE:
return EMPTY_STRING;
case PUBLIC_KEY:
return new ECPublicKey();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VERSION:
return (memberValue === ECPrivateKey.defaultValues(memberName));
case PRIVATE_KEY:
return (memberValue.isEqual(ECPrivateKey.defaultValues(memberName)));
case NAMED_CURVE:
return (memberValue === EMPTY_STRING);
case PUBLIC_KEY:
return ((ECPublicKey.compareWithDefault(NAMED_CURVE, memberValue.namedCurve)) &&
(ECPublicKey.compareWithDefault("x", memberValue.x)) &&
(ECPublicKey.compareWithDefault("y", memberValue.y)));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* ECPrivateKey ::= SEQUENCE {
* version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
* privateKey OCTET STRING,
* parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
* publicKey [1] BIT STRING OPTIONAL
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
version?: string;
privateKey?: string;
namedCurve?: string;
publicKey?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || EMPTY_STRING) }),
new asn1js.OctetString({ name: (names.privateKey || EMPTY_STRING) }),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.ObjectIdentifier({ name: (names.namedCurve || EMPTY_STRING) })
]
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [
new asn1js.BitString({ name: (names.publicKey || EMPTY_STRING) })
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
ECPrivateKey.schema({
names: {
version: VERSION,
privateKey: PRIVATE_KEY,
namedCurve: NAMED_CURVE,
publicKey: PUBLIC_KEY
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
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 in asn1.result) {
const publicKeyData: ECPublicKeyParameters = { schema: asn1.result.publicKey.valueBlock.valueHex };
if (NAMED_CURVE in this) {
publicKeyData.namedCurve = this.namedCurve;
}
this.publicKey = new ECPublicKey(publicKeyData);
}
//#endregion
}
public toSchema(): asn1js.Sequence {
const outputArray: any = [
new asn1js.Integer({ value: this.version }),
this.privateKey
];
if (this.namedCurve) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.ObjectIdentifier({ value: this.namedCurve })
]
}));
}
if (this.publicKey) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [
new asn1js.BitString({ valueHex: this.publicKey.toSchema().toBER(false) })
]
}));
}
return new asn1js.Sequence({
value: outputArray
});
}
public toJSON(): ECPrivateKeyJson {
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: ECPrivateKeyJson = {
crv: curve ? curve.name : this.namedCurve,
d: pvtsutils.Convert.ToBase64Url(this.privateKey.valueBlock.valueHexView),
};
if (this.publicKey) {
const publicKeyJSON = this.publicKey.toJSON();
privateKeyJSON.x = publicKeyJSON.x;
privateKeyJSON.y = publicKeyJSON.y;
}
return privateKeyJSON;
}
/**
* Converts JSON value into current object
* @param json JSON object
*/
public fromJSON(json: any): void {
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 = pvtsutils.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 asn1js.OctetString({ valueHex: buffer });
} else {
this.privateKey = new asn1js.OctetString({ valueHex: convertBuffer.slice(0, coordinateLength) });
}
if (json.x && json.y) {
this.publicKey = new ECPublicKey({ json });
}
}
}

192
third_party/js/PKI.js/src/ECPublicKey.ts поставляемый
Просмотреть файл

@ -1,192 +0,0 @@
import * as asn1js from "asn1js";
import { BufferSourceConverter } from "pvtsutils";
import * as pvutils from "pvutils";
import { EMPTY_BUFFER, EMPTY_STRING } from "./constants";
import { ECNamedCurves } from "./ECNamedCurves";
import { ParameterError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const X = "x";
const Y = "y";
const NAMED_CURVE = "namedCurve";
export interface IECPublicKey {
namedCurve: string;
x: ArrayBuffer;
y: ArrayBuffer;
}
export interface ECPublicKeyJson {
crv: string;
x: string;
y: string;
}
export type ECPublicKeyParameters = PkiObjectParameters & Partial<IECPublicKey> & { json?: ECPublicKeyJson; };
/**
* Represents the PrivateKeyInfo structure described in [RFC5480](https://datatracker.ietf.org/doc/html/rfc5480)
*/
export class ECPublicKey extends PkiObject implements IECPublicKey {
public static override CLASS_NAME = "ECPublicKey";
public namedCurve!: string;
public x!: ArrayBuffer;
public y!: ArrayBuffer;
/**
* Initializes a new instance of the {@link ECPublicKey} class
* @param parameters Initialization parameters
*/
constructor(parameters: ECPublicKeyParameters = {}) {
super();
this.x = pvutils.getParametersValue(parameters, X, ECPublicKey.defaultValues(X));
this.y = pvutils.getParametersValue(parameters, Y, ECPublicKey.defaultValues(Y));
this.namedCurve = pvutils.getParametersValue(parameters, NAMED_CURVE, ECPublicKey.defaultValues(NAMED_CURVE));
if (parameters.json) {
this.fromJSON(parameters.json);
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof NAMED_CURVE): string;
public static override defaultValues(memberName: typeof X | typeof Y): ArrayBuffer;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case X:
case Y:
return EMPTY_BUFFER;
case NAMED_CURVE:
return EMPTY_STRING;
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
static compareWithDefault<T>(memberName: string, memberValue: T): memberValue is T {
switch (memberName) {
case X:
case Y:
return memberValue instanceof ArrayBuffer &&
(pvutils.isEqualBuffer(memberValue, ECPublicKey.defaultValues(memberName)));
case NAMED_CURVE:
return typeof memberValue === "string" &&
memberValue === ECPublicKey.defaultValues(memberName);
default:
return super.defaultValues(memberName);
}
}
/**
* Returns value of pre-defined ASN.1 schema for current class
* @param parameters Input parameters for the schema
* @returns ASN.1 schema object
*/
public static override schema(): Schema.SchemaType {
return new asn1js.RawData();
}
public fromSchema(schema1: BufferSource): any {
//#region Check the schema is valid
const view = BufferSourceConverter.toUint8Array(schema1);
if (view[0] !== 0x04) {
throw new Error("Object's schema was not verified against input data for ECPublicKey");
}
//#endregion
//#region Get internal properties from parsed schema
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;
//#endregion
}
public toSchema(): asn1js.RawData {
return new asn1js.RawData({
data: pvutils.utilConcatBuf(
(new Uint8Array([0x04])).buffer,
this.x,
this.y
)
});
}
public toJSON(): ECPublicKeyJson {
const namedCurve = ECNamedCurves.find(this.namedCurve);
return {
crv: namedCurve ? namedCurve.name : this.namedCurve,
x: pvutils.toBase64(pvutils.arrayBufferToString(this.x), true, true, false),
y: pvutils.toBase64(pvutils.arrayBufferToString(this.y), true, true, false)
};
}
/**
* Converts JSON value into current object
* @param json JSON object
*/
public fromJSON(json: any): void {
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;
}
// TODO Simplify Base64url encoding
const xConvertBuffer = pvutils.stringToArrayBuffer(pvutils.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);
}
// TODO Simplify Base64url encoding
const yConvertBuffer = pvutils.stringToArrayBuffer(pvutils.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);
}
}
}

Просмотреть файл

@ -1,221 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const E_CONTENT_TYPE = "eContentType";
const E_CONTENT = "eContent";
const CLEAR_PROPS = [
E_CONTENT_TYPE,
E_CONTENT,
];
export interface IEncapsulatedContentInfo {
eContentType: string;
eContent?: asn1js.OctetString;
}
export interface EncapsulatedContentInfoJson {
eContentType: string;
eContent?: asn1js.OctetStringJson;
}
export type EncapsulatedContentInfoParameters = PkiObjectParameters & Partial<IEncapsulatedContentInfo>;
export type EncapsulatedContentInfoSchema = Schema.SchemaParameters<{
eContentType?: string;
eContent?: string;
}>;
/**
* Represents the EncapsulatedContentInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class EncapsulatedContentInfo extends PkiObject implements IEncapsulatedContentInfo {
public static override CLASS_NAME = "EncapsulatedContentInfo";
public eContentType!: string;
public eContent?: asn1js.OctetString;
/**
* Initializes a new instance of the {@link EncapsulatedContentInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: EncapsulatedContentInfoParameters = {}) {
super();
this.eContentType = pvutils.getParametersValue(parameters, E_CONTENT_TYPE, EncapsulatedContentInfo.defaultValues(E_CONTENT_TYPE));
if (E_CONTENT in parameters) {
this.eContent = pvutils.getParametersValue(parameters, E_CONTENT, EncapsulatedContentInfo.defaultValues(E_CONTENT));
if ((this.eContent.idBlock.tagClass === 1) &&
(this.eContent.idBlock.tagNumber === 4)) {
//#region Divide OCTET STRING value down to small pieces
if (this.eContent.idBlock.isConstructed === false) {
const constrString = new asn1js.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 asn1js.OctetString({ valueHex: _array }));
length -= pieceView.length;
offset += pieceView.length;
}
this.eContent = constrString;
}
//#endregion
}
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof E_CONTENT_TYPE): string;
public static override defaultValues(memberName: typeof E_CONTENT): asn1js.OctetString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case E_CONTENT_TYPE:
return EMPTY_STRING;
case E_CONTENT:
return new asn1js.OctetString();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* EncapsulatedContentInfo ::= SEQUENCE {
* eContentType ContentType,
* eContent [0] EXPLICIT OCTET STRING OPTIONAL } * Changed it to ANY, as in PKCS#7
*```
*/
public static override schema(parameters: EncapsulatedContentInfoSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.eContentType || EMPTY_STRING) }),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Any({ name: (names.eContent || EMPTY_STRING) }) // In order to aling this with PKCS#7 and CMS as well
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
EncapsulatedContentInfo.schema({
names: {
eContentType: E_CONTENT_TYPE,
eContent: E_CONTENT
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.eContentType = asn1.result.eContentType.valueBlock.toString();
if (E_CONTENT in asn1.result)
this.eContent = asn1.result.eContent;
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(new asn1js.ObjectIdentifier({ value: this.eContentType }));
if (this.eContent) {
if (EncapsulatedContentInfo.compareWithDefault(E_CONTENT, this.eContent) === false) {
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [this.eContent]
}));
}
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): EncapsulatedContentInfoJson {
const res: EncapsulatedContentInfoJson = {
eContentType: this.eContentType
};
if (this.eContent && EncapsulatedContentInfo.compareWithDefault(E_CONTENT, this.eContent) === false) {
res.eContent = this.eContent.toJSON();
}
return res;
}
}

Просмотреть файл

@ -1,285 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const CONTENT_TYPE = "contentType";
const CONTENT_ENCRYPTION_ALGORITHM = "contentEncryptionAlgorithm";
const ENCRYPTED_CONTENT = "encryptedContent";
const CLEAR_PROPS = [
CONTENT_TYPE,
CONTENT_ENCRYPTION_ALGORITHM,
ENCRYPTED_CONTENT,
];
export interface IEncryptedContentInfo {
contentType: string;
contentEncryptionAlgorithm: AlgorithmIdentifier;
encryptedContent?: asn1js.OctetString;
}
export interface EncryptedContentInfoJson {
contentType: string;
contentEncryptionAlgorithm: AlgorithmIdentifierJson;
encryptedContent?: asn1js.OctetStringJson;
}
export type EncryptedContentParameters = PkiObjectParameters & Partial<IEncryptedContentInfo>;
export type EncryptedContentInfoSchema = Schema.SchemaParameters<{
contentType?: string;
contentEncryptionAlgorithm?: AlgorithmIdentifierSchema;
encryptedContent?: string;
}>;
/**
* Represents the EncryptedContentInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class EncryptedContentInfo extends PkiObject implements IEncryptedContentInfo {
public static override CLASS_NAME = "EncryptedContentInfo";
public contentType!: string;
public contentEncryptionAlgorithm!: AlgorithmIdentifier;
public encryptedContent?: asn1js.OctetString;
/**
* Initializes a new instance of the {@link EncryptedContent} class
* @param parameters Initialization parameters
*/
constructor(parameters: EncryptedContentParameters = {}) {
super();
this.contentType = pvutils.getParametersValue(parameters, CONTENT_TYPE, EncryptedContentInfo.defaultValues(CONTENT_TYPE));
this.contentEncryptionAlgorithm = pvutils.getParametersValue(parameters, CONTENT_ENCRYPTION_ALGORITHM, EncryptedContentInfo.defaultValues(CONTENT_ENCRYPTION_ALGORITHM));
if (ENCRYPTED_CONTENT in parameters && parameters.encryptedContent) {
// encryptedContent (!!!) could be constructive or primitive value (!!!)
this.encryptedContent = parameters.encryptedContent;
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) {
const constrString = new asn1js.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 asn1js.OctetString({ valueHex: _array }));
length -= pieceView.length;
offset += pieceView.length;
}
this.encryptedContent = constrString;
}
//#endregion
}
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CONTENT_TYPE): string;
public static override defaultValues(memberName: typeof CONTENT_ENCRYPTION_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ENCRYPTED_CONTENT): asn1js.OctetString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CONTENT_TYPE:
return EMPTY_STRING;
case CONTENT_ENCRYPTION_ALGORITHM:
return new AlgorithmIdentifier();
case ENCRYPTED_CONTENT:
return new asn1js.OctetString();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case CONTENT_TYPE:
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* EncryptedContentInfo ::= SEQUENCE {
* contentType ContentType,
* contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
* encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }
*
* Comment: Strange, but modern crypto engines create ENCRYPTED_CONTENT as "[0] EXPLICIT EncryptedContent"
*
* EncryptedContent ::= OCTET STRING
*```
*/
public static override schema(parameters: EncryptedContentInfoSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.contentType || EMPTY_STRING) }),
AlgorithmIdentifier.schema(names.contentEncryptionAlgorithm || {}),
// The CHOICE we need because ENCRYPTED_CONTENT could have either "constructive"
// or "primitive" form of encoding and we need to handle both variants
new asn1js.Choice({
value: [
new asn1js.Constructed({
name: (names.encryptedContent || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Repeated({
value: new asn1js.OctetString()
})
]
}),
new asn1js.Primitive({
name: (names.encryptedContent || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
}
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
EncryptedContentInfo.schema({
names: {
contentType: CONTENT_TYPE,
contentEncryptionAlgorithm: {
names: {
blockName: CONTENT_ENCRYPTION_ALGORITHM
}
},
encryptedContent: ENCRYPTED_CONTENT
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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 as asn1js.OctetString;
this.encryptedContent.idBlock.tagClass = 1; // UNIVERSAL
this.encryptedContent.idBlock.tagNumber = 4; // OCTET STRING (!!!) The value still has instance of "in_window.org.pkijs.asn1.ASN1_CONSTRUCTED / ASN1_PRIMITIVE"
}
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const sequenceLengthBlock = {
isIndefiniteForm: false
};
const outputArray = [];
outputArray.push(new asn1js.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; // CONTEXT-SPECIFIC
encryptedValue.idBlock.tagNumber = 0; // [0]
encryptedValue.lenBlock.isIndefiniteForm = this.encryptedContent.idBlock.isConstructed;
outputArray.push(encryptedValue);
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
lenBlock: sequenceLengthBlock,
value: outputArray
}));
//#endregion
}
public toJSON(): EncryptedContentInfoJson {
const res: EncryptedContentInfoJson = {
contentType: this.contentType,
contentEncryptionAlgorithm: this.contentEncryptionAlgorithm.toJSON()
};
if (this.encryptedContent) {
res.encryptedContent = this.encryptedContent.toJSON();
}
return res;
}
/**
* Returns concatenated buffer from `encryptedContent` field.
* @returns Array buffer
* @since 3.0.0
* @throws Throws Error if `encryptedContent` is undefined
*/
public getEncryptedContent(): ArrayBuffer {
if (!this.encryptedContent) {
throw new Error("Parameter 'encryptedContent' is undefined");
}
// NOTE encryptedContent can be CONSTRUCTED/PRIMITIVE
return asn1js.OctetString.prototype.getValue.call(this.encryptedContent);
}
}

303
third_party/js/PKI.js/src/EncryptedData.ts поставляемый
Просмотреть файл

@ -1,303 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import * as common from "./common";
import { EncryptedContentInfo, EncryptedContentInfoJson, EncryptedContentInfoSchema } from "./EncryptedContentInfo";
import { Attribute, AttributeJson } from "./Attribute";
import * as Schema from "./Schema";
import { ArgumentError, AsnError } from "./errors";
import { CryptoEngineEncryptParams } from "./CryptoEngine/CryptoEngineInterface";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_STRING } from "./constants";
const VERSION = "version";
const ENCRYPTED_CONTENT_INFO = "encryptedContentInfo";
const UNPROTECTED_ATTRS = "unprotectedAttrs";
const CLEAR_PROPS = [
VERSION,
ENCRYPTED_CONTENT_INFO,
UNPROTECTED_ATTRS,
];
export interface IEncryptedData {
/**
* Version number.
*
* If `unprotectedAttrs` is present, then the version MUST be 2. If `unprotectedAttrs` is absent, then version MUST be 0.
*/
version: number;
/**
* Encrypted content information
*/
encryptedContentInfo: EncryptedContentInfo;
/**
* Collection of attributes that are not encrypted
*/
unprotectedAttrs?: Attribute[];
}
export interface EncryptedDataJson {
version: number;
encryptedContentInfo: EncryptedContentInfoJson;
unprotectedAttrs?: AttributeJson[];
}
export type EncryptedDataParameters = PkiObjectParameters & Partial<IEncryptedData>;
export type EncryptedDataEncryptParams = Omit<CryptoEngineEncryptParams, "contentType">;
/**
* Represents the EncryptedData structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*
* @example The following example demonstrates how to create and encrypt CMS Encrypted Data
* ```js
* const cmsEncrypted = new pkijs.EncryptedData();
*
* await cmsEncrypted.encrypt({
* contentEncryptionAlgorithm: {
* name: "AES-GCM",
* length: 256,
* },
* hmacHashAlgorithm: "SHA-256",
* iterationCount: 1000,
* password: password,
* contentToEncrypt: dataToEncrypt,
* });
*
* // Add Encrypted Data into CMS Content Info
* const cmsContent = new pkijs.ContentInfo();
* cmsContent.contentType = pkijs.ContentInfo.ENCRYPTED_DATA;
* cmsContent.content = cmsEncrypted.toSchema();
*
* const cmsContentRaw = cmsContent.toSchema().toBER();
* ```
*
* @example The following example demonstrates how to decrypt CMS Encrypted Data
* ```js
* // Parse CMS Content Info
* const cmsContent = pkijs.ContentInfo.fromBER(cmsContentRaw);
* if (cmsContent.contentType !== pkijs.ContentInfo.ENCRYPTED_DATA) {
* throw new Error("CMS is not Encrypted Data");
* }
* // Parse CMS Encrypted Data
* const cmsEncrypted = new pkijs.EncryptedData({ schema: cmsContent.content });
*
* // Decrypt data
* const decryptedData = await cmsEncrypted.decrypt({
* password: password,
* });
* ```
*/
export class EncryptedData extends PkiObject implements IEncryptedData {
public static override CLASS_NAME = "EncryptedData";
public version!: number;
public encryptedContentInfo!: EncryptedContentInfo;
public unprotectedAttrs?: Attribute[];
/**
* Initializes a new instance of the {@link EncryptedData} class
* @param parameters Initialization parameters
*/
constructor(parameters: EncryptedDataParameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, EncryptedData.defaultValues(VERSION));
this.encryptedContentInfo = pvutils.getParametersValue(parameters, ENCRYPTED_CONTENT_INFO, EncryptedData.defaultValues(ENCRYPTED_CONTENT_INFO));
if (UNPROTECTED_ATTRS in parameters) {
this.unprotectedAttrs = pvutils.getParametersValue(parameters, UNPROTECTED_ATTRS, EncryptedData.defaultValues(UNPROTECTED_ATTRS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof ENCRYPTED_CONTENT_INFO): EncryptedContentInfo;
public static override defaultValues(memberName: typeof UNPROTECTED_ATTRS): Attribute[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return 0;
case ENCRYPTED_CONTENT_INFO:
return new EncryptedContentInfo();
case UNPROTECTED_ATTRS:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VERSION:
return (memberValue === 0);
case ENCRYPTED_CONTENT_INFO:
// TODO move to isEmpty method
return ((EncryptedContentInfo.compareWithDefault("contentType", memberValue.contentType)) &&
(EncryptedContentInfo.compareWithDefault("contentEncryptionAlgorithm", memberValue.contentEncryptionAlgorithm)) &&
(EncryptedContentInfo.compareWithDefault("encryptedContent", memberValue.encryptedContent)));
case UNPROTECTED_ATTRS:
return (memberValue.length === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* EncryptedData ::= SEQUENCE {
* version CMSVersion,
* encryptedContentInfo EncryptedContentInfo,
* unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
version?: string;
encryptedContentInfo?: EncryptedContentInfoSchema;
unprotectedAttrs?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || EMPTY_STRING) }),
EncryptedContentInfo.schema(names.encryptedContentInfo || {}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [
new asn1js.Repeated({
name: (names.unprotectedAttrs || EMPTY_STRING),
value: Attribute.schema()
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
EncryptedData.schema({
names: {
version: VERSION,
encryptedContentInfo: {
names: {
blockName: ENCRYPTED_CONTENT_INFO
}
},
unprotectedAttrs: UNPROTECTED_ATTRS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.version = asn1.result.version.valueBlock.valueDec;
this.encryptedContentInfo = new EncryptedContentInfo({ schema: asn1.result.encryptedContentInfo });
if (UNPROTECTED_ATTRS in asn1.result)
this.unprotectedAttrs = Array.from(asn1.result.unprotectedAttrs, element => new Attribute({ schema: element }));
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(new asn1js.Integer({ value: this.version }));
outputArray.push(this.encryptedContentInfo.toSchema());
if (this.unprotectedAttrs) {
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: Array.from(this.unprotectedAttrs, o => o.toSchema())
}));
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): EncryptedDataJson {
const res: EncryptedDataJson = {
version: this.version,
encryptedContentInfo: this.encryptedContentInfo.toJSON()
};
if (this.unprotectedAttrs)
res.unprotectedAttrs = Array.from(this.unprotectedAttrs, o => o.toJSON());
return res;
}
/**
* Creates a new CMS Encrypted Data content
* @param parameters Parameters necessary for encryption
*/
public async encrypt(parameters: EncryptedDataEncryptParams): Promise<void> {
//#region Check for input parameters
ArgumentError.assert(parameters, "parameters", "object");
//#endregion
//#region Set "contentType" parameter
const encryptParams: CryptoEngineEncryptParams = {
...parameters,
contentType: "1.2.840.113549.1.7.1",
};
//#endregion
this.encryptedContentInfo = await common.getCrypto(true).encryptEncryptedContentInfo(encryptParams);
}
/**
* Creates a new CMS Encrypted Data content
* @param parameters Parameters necessary for encryption
* @param crypto Crypto engine
* @returns Returns decrypted raw data
*/
async decrypt(parameters: {
password: ArrayBuffer;
}, crypto = common.getCrypto(true)): Promise<ArrayBuffer> {
// Check for input parameters
ArgumentError.assert(parameters, "parameters", "object");
// Set ENCRYPTED_CONTENT_INFO value
const decryptParams = {
...parameters,
encryptedContentInfo: this.encryptedContentInfo,
};
return crypto.decryptEncryptedContentInfo(decryptParams);
}
}

1531
third_party/js/PKI.js/src/EnvelopedData.ts поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

123
third_party/js/PKI.js/src/ExtKeyUsage.ts поставляемый
Просмотреть файл

@ -1,123 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const KEY_PURPOSES = "keyPurposes";
const CLEAR_PROPS = [
KEY_PURPOSES,
];
export interface IExtKeyUsage {
keyPurposes: string[];
}
export interface ExtKeyUsageJson {
keyPurposes: string[];
}
export type ExtKeyUsageParameters = PkiObjectParameters & Partial<IExtKeyUsage>;
/**
* Represents the ExtKeyUsage structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class ExtKeyUsage extends PkiObject implements IExtKeyUsage {
public static override CLASS_NAME = "ExtKeyUsage";
public keyPurposes!: string[];
/**
* Initializes a new instance of the {@link ExtKeyUsage} class
* @param parameters Initialization parameters
*/
constructor(parameters: ExtKeyUsageParameters = {}) {
super();
this.keyPurposes = pvutils.getParametersValue(parameters, KEY_PURPOSES, ExtKeyUsage.defaultValues(KEY_PURPOSES));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof KEY_PURPOSES): string[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case KEY_PURPOSES:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* ExtKeyUsage ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
*
* KeyPurposeId ::= OBJECT IDENTIFIER
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
keyPurposes?: string;
}> = {}): Schema.SchemaType {
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [keyPurposes]
*/
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.keyPurposes || EMPTY_STRING),
value: new asn1js.ObjectIdentifier()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
ExtKeyUsage.schema({
names: {
keyPurposes: KEY_PURPOSES
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.keyPurposes = Array.from(asn1.result.keyPurposes, (element: asn1js.ObjectIdentifier) => element.valueBlock.toString());
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: Array.from(this.keyPurposes, element => new asn1js.ObjectIdentifier({ value: element }))
}));
}
public toJSON(): ExtKeyUsageJson {
return {
keyPurposes: Array.from(this.keyPurposes)
};
}
}

206
third_party/js/PKI.js/src/Extension.ts поставляемый
Просмотреть файл

@ -1,206 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import * as Schema from "./Schema";
import { ExtensionParsedValue, ExtensionValueFactory } from "./ExtensionValueFactory";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_STRING } from "./constants";
const EXTN_ID = "extnID";
const CRITICAL = "critical";
const EXTN_VALUE = "extnValue";
const PARSED_VALUE = "parsedValue";
const CLEAR_PROPS = [
EXTN_ID,
CRITICAL,
EXTN_VALUE
];
export interface IExtension {
extnID: string;
critical: boolean;
extnValue: asn1js.OctetString;
parsedValue?: ExtensionParsedValue;
}
export interface ExtensionConstructorParameters {
extnID?: string;
critical?: boolean;
extnValue?: ArrayBuffer;
parsedValue?: ExtensionParsedValue;
}
export type ExtensionParameters = PkiObjectParameters & ExtensionConstructorParameters;
export type ExtensionSchema = Schema.SchemaParameters<{
extnID?: string;
critical?: string;
extnValue?: string;
}>;
export interface ExtensionJson {
extnID: string;
extnValue: asn1js.OctetStringJson;
critical?: boolean;
parsedValue?: any;
}
/**
* Represents the Extension structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class Extension extends PkiObject implements IExtension {
public static override CLASS_NAME = "Extension";
public extnID!: string;
public critical!: boolean;
public extnValue!: asn1js.OctetString;
private _parsedValue?: ExtensionParsedValue | null;
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);
this._parsedValue = parsedValue;
}
return this._parsedValue || undefined;
}
public set parsedValue(value: ExtensionParsedValue | undefined) {
this._parsedValue = value;
}
/**
* Initializes a new instance of the {@link Extension} class
* @param parameters Initialization parameters
*/
constructor(parameters: ExtensionParameters = {}) {
super();
this.extnID = pvutils.getParametersValue(parameters, EXTN_ID, Extension.defaultValues(EXTN_ID));
this.critical = pvutils.getParametersValue(parameters, CRITICAL, Extension.defaultValues(CRITICAL));
if (EXTN_VALUE in parameters) {
this.extnValue = new asn1js.OctetString({ valueHex: parameters.extnValue });
} else {
this.extnValue = Extension.defaultValues(EXTN_VALUE);
}
if (PARSED_VALUE in parameters) {
this.parsedValue = pvutils.getParametersValue(parameters, PARSED_VALUE, Extension.defaultValues(PARSED_VALUE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof EXTN_ID): string;
public static override defaultValues(memberName: typeof CRITICAL): boolean;
public static override defaultValues(memberName: typeof EXTN_VALUE): asn1js.OctetString;
public static override defaultValues(memberName: typeof PARSED_VALUE): ExtensionParsedValue;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case EXTN_ID:
return EMPTY_STRING;
case CRITICAL:
return false;
case EXTN_VALUE:
return new asn1js.OctetString();
case PARSED_VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING
* }
*```
*/
public static override schema(parameters: ExtensionSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.extnID || EMPTY_STRING) }),
new asn1js.Boolean({
name: (names.critical || EMPTY_STRING),
optional: true
}),
new asn1js.OctetString({ name: (names.extnValue || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
Extension.schema({
names: {
extnID: EXTN_ID,
critical: CRITICAL,
extnValue: EXTN_VALUE
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.extnID = asn1.result.extnID.valueBlock.toString();
if (CRITICAL in asn1.result) {
this.critical = asn1.result.critical.valueBlock.value;
}
this.extnValue = asn1.result.extnValue;
}
public toSchema(): asn1js.Sequence {
// Create array for output sequence
const outputArray = [];
outputArray.push(new asn1js.ObjectIdentifier({ value: this.extnID }));
if (this.critical !== Extension.defaultValues(CRITICAL)) {
outputArray.push(new asn1js.Boolean({ value: this.critical }));
}
outputArray.push(this.extnValue);
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
}
public toJSON(): ExtensionJson {
const object: ExtensionJson = {
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;
}
}

Просмотреть файл

@ -1,106 +0,0 @@
import * as asn1js from "asn1js";
import * as OID from "./ObjectIdentifiers";
import * as Schema from "./Schema";
export type ExtensionParsedValue = (Schema.SchemaCompatible & {
parsingError?: string;
}) | Schema.SchemaType;
export interface ExtensionValueType {
name: string;
type: ExtensionValueConstructor;
}
export interface ExtensionValueConstructor {
new(params?: { schema: any; }): Schema.SchemaCompatible;
}
export class ExtensionValueFactory {
public static types?: Record<string, ExtensionValueType>;
private static getItems(): Record<string, ExtensionValueType> {
if (!this.types) {
this.types = {};
// Register wellknown extensions
ExtensionValueFactory.register(OID.id_SubjectAltName, "SubjectAltName", AltName);
ExtensionValueFactory.register(OID.id_IssuerAltName, "IssuerAltName", AltName);
ExtensionValueFactory.register(OID.id_AuthorityKeyIdentifier, "AuthorityKeyIdentifier", AuthorityKeyIdentifier);
ExtensionValueFactory.register(OID.id_BasicConstraints, "BasicConstraints", BasicConstraints);
ExtensionValueFactory.register(OID.id_MicrosoftCaVersion, "MicrosoftCaVersion", CAVersion);
ExtensionValueFactory.register(OID.id_CertificatePolicies, "CertificatePolicies", CertificatePolicies);
ExtensionValueFactory.register(OID.id_MicrosoftAppPolicies, "CertificatePoliciesMicrosoft", CertificatePolicies);
ExtensionValueFactory.register(OID.id_MicrosoftCertTemplateV2, "MicrosoftCertTemplateV2", CertificateTemplate);
ExtensionValueFactory.register(OID.id_CRLDistributionPoints, "CRLDistributionPoints", CRLDistributionPoints);
ExtensionValueFactory.register(OID.id_FreshestCRL, "FreshestCRL", CRLDistributionPoints);
ExtensionValueFactory.register(OID.id_ExtKeyUsage, "ExtKeyUsage", ExtKeyUsage);
ExtensionValueFactory.register(OID.id_CertificateIssuer, "CertificateIssuer", GeneralNames);
ExtensionValueFactory.register(OID.id_AuthorityInfoAccess, "AuthorityInfoAccess", InfoAccess);
ExtensionValueFactory.register(OID.id_SubjectInfoAccess, "SubjectInfoAccess", InfoAccess);
ExtensionValueFactory.register(OID.id_IssuingDistributionPoint, "IssuingDistributionPoint", IssuingDistributionPoint);
ExtensionValueFactory.register(OID.id_NameConstraints, "NameConstraints", NameConstraints);
ExtensionValueFactory.register(OID.id_PolicyConstraints, "PolicyConstraints", PolicyConstraints);
ExtensionValueFactory.register(OID.id_PolicyMappings, "PolicyMappings", PolicyMappings);
ExtensionValueFactory.register(OID.id_PrivateKeyUsagePeriod, "PrivateKeyUsagePeriod", PrivateKeyUsagePeriod);
ExtensionValueFactory.register(OID.id_QCStatements, "QCStatements", QCStatements);
ExtensionValueFactory.register(OID.id_SignedCertificateTimestampList, "SignedCertificateTimestampList", SignedCertificateTimestampList);
ExtensionValueFactory.register(OID.id_SubjectDirectoryAttributes, "SubjectDirectoryAttributes", SubjectDirectoryAttributes);
}
return this.types;
}
public static fromBER(id: string, raw: BufferSource): ExtensionParsedValue | null {
const asn1 = asn1js.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: ExtensionParsedValue = new item.type();
res.parsingError = `Incorrectly formatted value of extension ${item.name} (${id})`;
return res;
}
}
return asn1.result;
}
public static find(id: string): ExtensionValueType | null {
const types = this.getItems();
return types[id] || null;
}
public static register(id: string, name: string, type: ExtensionValueConstructor) {
this.getItems()[id] = { name, type };
}
}
import { AltName } from "./AltName";
import { AuthorityKeyIdentifier } from "./AuthorityKeyIdentifier";
import { BasicConstraints } from "./BasicConstraints";
import { CAVersion } from "./CAVersion";
import { CertificatePolicies } from "./CertificatePolicies";
import { CertificateTemplate } from "./CertificateTemplate";
import { CRLDistributionPoints } from "./CRLDistributionPoints";
import { ExtKeyUsage } from "./ExtKeyUsage";
import { GeneralNames } from "./GeneralNames";
import { InfoAccess } from "./InfoAccess";
import { IssuingDistributionPoint } from "./IssuingDistributionPoint";
import { NameConstraints } from "./NameConstraints";
import { PolicyConstraints } from "./PolicyConstraints";
import { PolicyMappings } from "./PolicyMappings";
import { PrivateKeyUsagePeriod } from "./PrivateKeyUsagePeriod";
import { QCStatements } from "./QCStatements";
import { SignedCertificateTimestampList } from "./SignedCertificateTimestampList";
import { SubjectDirectoryAttributes } from "./SubjectDirectoryAttributes";

129
third_party/js/PKI.js/src/Extensions.ts поставляемый
Просмотреть файл

@ -1,129 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { Extension, ExtensionJson, ExtensionSchema } from "./Extension";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const EXTENSIONS = "extensions";
const CLEAR_PROPS = [
EXTENSIONS,
];
export interface IExtensions {
/**
* List of extensions
*/
extensions: Extension[];
}
export type ExtensionsParameters = PkiObjectParameters & Partial<IExtensions>;
export type ExtensionsSchema = Schema.SchemaParameters<{
extensions?: string;
extension?: ExtensionSchema;
}>;
export interface ExtensionsJson {
extensions: ExtensionJson[];
}
/**
* Represents the Extensions structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class Extensions extends PkiObject implements IExtensions {
public static override CLASS_NAME = "Extensions";
public extensions!: Extension[];
/**
* Initializes a new instance of the {@link Extensions} class
* @param parameters Initialization parameters
*/
constructor(parameters: ExtensionsParameters = {}) {
super();
this.extensions = pvutils.getParametersValue(parameters, EXTENSIONS, Extensions.defaultValues(EXTENSIONS));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof EXTENSIONS): Extension[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case EXTENSIONS:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
* ```
*
* @param parameters Input parameters for the schema
* @param optional Flag that current schema should be optional
* @returns ASN.1 schema object
*/
public static override schema(parameters: ExtensionsSchema = {}, optional = false) {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
optional,
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.extensions || EMPTY_STRING),
value: Extension.schema(names.extension || {})
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
Extensions.schema({
names: {
extensions: EXTENSIONS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.extensions = Array.from(asn1.result.extensions, element => new Extension({ schema: element }));
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: Array.from(this.extensions, o => o.toSchema())
}));
//#endregion
}
public toJSON(): ExtensionsJson {
return {
extensions: this.extensions.map(o => o.toJSON())
};
}
}

642
third_party/js/PKI.js/src/GeneralName.ts поставляемый
Просмотреть файл

@ -1,642 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { RelativeDistinguishedNames } from "./RelativeDistinguishedNames";
import * as Schema from "./Schema";
export const TYPE = "type";
export const VALUE = "value";
//#region Additional asn1js schema elements existing inside GeneralName schema
/**
* Schema for "builtInStandardAttributes" of "ORAddress"
* @param parameters
* @property names
* @param optional
* @returns
*/
function builtInStandardAttributes(parameters: Schema.SchemaParameters<{
country_name?: string;
administration_domain_name?: string;
network_address?: string;
terminal_identifier?: string;
private_domain_name?: string;
organization_name?: string;
numeric_user_identifier?: string;
personal_name?: string;
organizational_unit_names?: string;
}> = {}, optional = false) {
//builtInStandardAttributes ::= Sequence {
// country-name CountryName OPTIONAL,
// administration-domain-name AdministrationDomainName OPTIONAL,
// network-address [0] IMPLICIT NetworkAddress OPTIONAL,
// terminal-identifier [1] IMPLICIT TerminalIdentifier OPTIONAL,
// private-domain-name [2] PrivateDomainName OPTIONAL,
// organization-name [3] IMPLICIT OrganizationName OPTIONAL,
// numeric-user-identifier [4] IMPLICIT NumericUserIdentifier OPTIONAL,
// personal-name [5] IMPLICIT PersonalName OPTIONAL,
// organizational-unit-names [6] IMPLICIT OrganizationalUnitNames OPTIONAL }
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
optional,
value: [
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 2, // APPLICATION-SPECIFIC
tagNumber: 1 // [1]
},
name: (names.country_name || EMPTY_STRING),
value: [
new asn1js.Choice({
value: [
new asn1js.NumericString(),
new asn1js.PrintableString()
]
})
]
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 2, // APPLICATION-SPECIFIC
tagNumber: 2 // [2]
},
name: (names.administration_domain_name || EMPTY_STRING),
value: [
new asn1js.Choice({
value: [
new asn1js.NumericString(),
new asn1js.PrintableString()
]
})
]
}),
new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
name: (names.network_address || EMPTY_STRING),
isHexOnly: true
}),
new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
name: (names.terminal_identifier || EMPTY_STRING),
isHexOnly: true
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
name: (names.private_domain_name || EMPTY_STRING),
value: [
new asn1js.Choice({
value: [
new asn1js.NumericString(),
new asn1js.PrintableString()
]
})
]
}),
new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
},
name: (names.organization_name || EMPTY_STRING),
isHexOnly: true
}),
new asn1js.Primitive({
optional: true,
name: (names.numeric_user_identifier || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 4 // [4]
},
isHexOnly: true
}),
new asn1js.Constructed({
optional: true,
name: (names.personal_name || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 5 // [5]
},
value: [
new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
isHexOnly: true
}),
new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
isHexOnly: true
}),
new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
},
isHexOnly: true
}),
new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
},
isHexOnly: true
})
]
}),
new asn1js.Constructed({
optional: true,
name: (names.organizational_unit_names || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 6 // [6]
},
value: [
new asn1js.Repeated({
value: new asn1js.PrintableString()
})
]
})
]
}));
}
/**
* Schema for "builtInDomainDefinedAttributes" of "ORAddress"
* @param optional
*/
function builtInDomainDefinedAttributes(optional = false): Schema.SchemaType {
return (new asn1js.Sequence({
optional,
value: [
new asn1js.PrintableString(),
new asn1js.PrintableString()
]
}));
}
/**
* Schema for "builtInDomainDefinedAttributes" of "ORAddress"
* @param optional
*/
function extensionAttributes(optional = false): Schema.SchemaType {
return (new asn1js.Set({
optional,
value: [
new asn1js.Primitive({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
isHexOnly: true
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [new asn1js.Any()]
})
]
}));
}
//#endregion
export interface IGeneralName {
/**
* value type - from a tagged value (0 for "otherName", 1 for "rfc822Name" etc.)
*/
type: number;
/**
* ASN.1 object having GeneralName value (type depends on TYPE value)
*/
value: any;
}
export type GeneralNameParameters = PkiObjectParameters & Partial<{ type: 1 | 2 | 6; value: string; } | { type: 0 | 3 | 4 | 7 | 8; value: any; }>;
export interface GeneralNameSchema {
names?: {
blockName?: string;
directoryName?: object;
builtInStandardAttributes?: object;
otherName?: string;
rfc822Name?: string;
dNSName?: string;
x400Address?: string;
ediPartyName?: string;
uniformResourceIdentifier?: string;
iPAddress?: string;
registeredID?: string;
};
}
export interface GeneralNameJson {
type: number;
value: string;
}
/**
* Represents the GeneralName structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class GeneralName extends PkiObject implements IGeneralName {
public static override CLASS_NAME = "GeneralName";
public type!: number;
public value: any;
/**
* Initializes a new instance of the {@link GeneralName} class
* @param parameters Initialization parameters
*/
constructor(parameters: GeneralNameParameters = {}) {
super();
this.type = pvutils.getParametersValue(parameters, TYPE, GeneralName.defaultValues(TYPE));
this.value = pvutils.getParametersValue(parameters, VALUE, GeneralName.defaultValues(VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TYPE): number;
public static override defaultValues(memberName: typeof VALUE): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TYPE:
return 9;
case VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compares values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case TYPE:
return (memberValue === GeneralName.defaultValues(memberName));
case VALUE:
return (Object.keys(memberValue).length === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* GeneralName ::= Choice {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] value,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*```
*/
static override schema(parameters: GeneralNameSchema = {}): asn1js.Choice {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Choice({
value: [
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier(),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [new asn1js.Any()]
})
]
}),
new asn1js.Primitive({
name: (names.blockName || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
}
}),
new asn1js.Primitive({
name: (names.blockName || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
}
}),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
},
name: (names.blockName || EMPTY_STRING),
value: [
builtInStandardAttributes((names.builtInStandardAttributes || {}), false),
builtInDomainDefinedAttributes(true),
extensionAttributes(true)
]
}),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 4 // [4]
},
name: (names.blockName || EMPTY_STRING),
value: [RelativeDistinguishedNames.schema(names.directoryName || {})]
}),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 5 // [5]
},
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Choice({
value: [
new asn1js.TeletexString(),
new asn1js.PrintableString(),
new asn1js.UniversalString(),
new asn1js.Utf8String(),
new asn1js.BmpString()
]
})
]
}),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [
new asn1js.Choice({
value: [
new asn1js.TeletexString(),
new asn1js.PrintableString(),
new asn1js.UniversalString(),
new asn1js.Utf8String(),
new asn1js.BmpString()
]
})
]
})
]
}),
new asn1js.Primitive({
name: (names.blockName || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 6 // [6]
}
}),
new asn1js.Primitive({
name: (names.blockName || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 7 // [7]
}
}),
new asn1js.Primitive({
name: (names.blockName || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 8 // [8]
}
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
//#region Clear input data first
pvutils.clearProps(schema, [
"blockName",
"otherName",
"rfc822Name",
"dNSName",
"x400Address",
"directoryName",
"ediPartyName",
"uniformResourceIdentifier",
"iPAddress",
"registeredID"
]);
//#endregion
//#region Check the schema is valid
const asn1 = asn1js.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);
//#endregion
//#region Get internal properties from parsed schema
this.type = asn1.result.blockName.idBlock.tagNumber;
switch (this.type) {
case 0: // otherName
this.value = asn1.result.blockName;
break;
case 1: // rfc822Name + dNSName + uniformResourceIdentifier
case 2:
case 6:
{
const value = asn1.result.blockName;
value.idBlock.tagClass = 1; // UNIVERSAL
value.idBlock.tagNumber = 22; // IA5STRING
const valueBER = value.toBER(false);
const asnValue = asn1js.fromBER(valueBER);
AsnError.assert(asnValue, "GeneralName value");
this.value = (asnValue.result as asn1js.BaseStringBlock).valueBlock.value;
}
break;
case 3: // x400Address
this.value = asn1.result.blockName;
break;
case 4: // directoryName
this.value = new RelativeDistinguishedNames({ schema: asn1.result.directoryName });
break;
case 5: // ediPartyName
this.value = asn1.result.ediPartyName;
break;
case 7: // iPAddress
this.value = new asn1js.OctetString({ valueHex: asn1.result.blockName.valueBlock.valueHex });
break;
case 8: // registeredID
{
const value = asn1.result.blockName;
value.idBlock.tagClass = 1; // UNIVERSAL
value.idBlock.tagNumber = 6; // ObjectIdentifier
const valueBER = value.toBER(false);
const asnValue = asn1js.fromBER(valueBER);
AsnError.assert(asnValue, "GeneralName registeredID");
this.value = asnValue.result.valueBlock.toString(); // Getting a string representation of the ObjectIdentifier
}
break;
default:
}
//#endregion
}
public toSchema(): asn1js.Constructed | asn1js.IA5String | asn1js.ObjectIdentifier | asn1js.Choice {
//#region Construct and return new ASN.1 schema for this object
switch (this.type) {
case 0:
case 3:
case 5:
return new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: this.type
},
value: [
this.value
]
});
case 1:
case 2:
case 6:
{
const value = new asn1js.IA5String({ value: this.value });
value.idBlock.tagClass = 3;
value.idBlock.tagNumber = this.type;
return value;
}
case 4:
return new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
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 asn1js.ObjectIdentifier({ value: this.value });
value.idBlock.tagClass = 3;
value.idBlock.tagNumber = this.type;
return value;
}
default:
return GeneralName.schema();
}
//#endregion
}
public toJSON(): GeneralNameJson {
const _object = {
type: this.type,
value: EMPTY_STRING
} as GeneralNameJson;
if ((typeof this.value) === "string")
_object.value = this.value;
else {
try {
_object.value = this.value.toJSON();
}
catch (ex) {
// nothing
}
}
return _object;
}
}

130
third_party/js/PKI.js/src/GeneralNames.ts поставляемый
Просмотреть файл

@ -1,130 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import * as Schema from "./Schema";
import { GeneralName, GeneralNameJson } from "./GeneralName";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_STRING } from "./constants";
const NAMES = "names";
const GENERAL_NAMES = "generalNames";
export interface IGeneralNames {
names: GeneralName[];
}
export type GeneralNamesParameters = PkiObjectParameters & Partial<IGeneralNames>;
export type GeneralNamesSchema = Schema.SchemaParameters<{
generalNames?: string;
}>;
export interface GeneralNamesJson {
names: GeneralNameJson[];
}
/**
* Represents the GeneralNames structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class GeneralNames extends PkiObject implements IGeneralNames {
public static override CLASS_NAME = "GeneralNames";
/**
* Array of "general names"
*/
public names!: GeneralName[];
/**
* Initializes a new instance of the {@link GeneralNames} class
* @param parameters Initialization parameters
*/
constructor(parameters: GeneralNamesParameters = {}) {
super();
this.names = pvutils.getParametersValue(parameters, NAMES, GeneralNames.defaultValues(NAMES));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof NAMES): GeneralName[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case "names":
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
* ```
*
* @param parameters Input parameters for the schema
* @param optional Flag would be element optional or not
* @returns ASN.1 schema object
*/
public static override schema(parameters: GeneralNamesSchema = {}, optional = false): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, NAMES, {});
return (new asn1js.Sequence({
optional,
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.generalNames || EMPTY_STRING),
value: GeneralName.schema()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
//#region Clear input data first
pvutils.clearProps(schema, [
NAMES,
GENERAL_NAMES
]);
//#endregion
//#region Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
GeneralNames.schema({
names: {
blockName: NAMES,
generalNames: GENERAL_NAMES
}
})
);
AsnError.assertSchema(asn1, this.className);
//#endregion
this.names = Array.from(asn1.result.generalNames, element => new GeneralName({ schema: element }));
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: Array.from(this.names, o => o.toSchema())
}));
}
public toJSON(): GeneralNamesJson {
return {
names: Array.from(this.names, o => o.toJSON())
};
}
}

240
third_party/js/PKI.js/src/GeneralSubtree.ts поставляемый
Просмотреть файл

@ -1,240 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { GeneralName, GeneralNameJson, GeneralNameSchema } from "./GeneralName";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const BASE = "base";
const MINIMUM = "minimum";
const MAXIMUM = "maximum";
const CLEAR_PROPS = [
BASE,
MINIMUM,
MAXIMUM
];
export interface IGeneralSubtree {
base: GeneralName;
minimum: number | asn1js.Integer;
maximum?: number | asn1js.Integer;
}
export interface GeneralSubtreeJson {
base: GeneralNameJson;
minimum?: number | asn1js.IntegerJson;
maximum?: number | asn1js.IntegerJson;
}
export type GeneralSubtreeParameters = PkiObjectParameters & Partial<IGeneralSubtree>;
/**
* Represents the GeneralSubtree structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class GeneralSubtree extends PkiObject implements IGeneralSubtree {
public static override CLASS_NAME = "GeneralSubtree";
public base!: GeneralName;
public minimum!: number | asn1js.Integer;
public maximum?: number | asn1js.Integer;
/**
* Initializes a new instance of the {@link GeneralSubtree} class
* @param parameters Initialization parameters
*/
constructor(parameters: GeneralSubtreeParameters = {}) {
super();
this.base = pvutils.getParametersValue(parameters, BASE, GeneralSubtree.defaultValues(BASE));
this.minimum = pvutils.getParametersValue(parameters, MINIMUM, GeneralSubtree.defaultValues(MINIMUM));
if (MAXIMUM in parameters) {
this.maximum = pvutils.getParametersValue(parameters, MAXIMUM, GeneralSubtree.defaultValues(MAXIMUM));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof BASE): GeneralName;
public static override defaultValues(memberName: typeof MINIMUM): number;
public static override defaultValues(memberName: typeof MAXIMUM): number;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case BASE:
return new GeneralName();
case MINIMUM:
return 0;
case MAXIMUM:
return 0;
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* GeneralSubtree ::= SEQUENCE {
* base GeneralName,
* minimum [0] BaseDistance DEFAULT 0,
* maximum [1] BaseDistance OPTIONAL }
*
* BaseDistance ::= INTEGER (0..MAX)
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
base?: GeneralNameSchema;
minimum?: string;
maximum?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
GeneralName.schema(names.base || {}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [new asn1js.Integer({ name: (names.minimum || EMPTY_STRING) })]
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [new asn1js.Integer({ name: (names.maximum || EMPTY_STRING) })]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
GeneralSubtree.schema({
names: {
base: {
names: {
blockName: BASE
}
},
minimum: MINIMUM,
maximum: MAXIMUM
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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;
}
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(this.base.toSchema());
if (this.minimum !== 0) {
let valueMinimum: number | asn1js.Integer = 0;
if (this.minimum instanceof asn1js.Integer) {
valueMinimum = this.minimum;
} else {
valueMinimum = new asn1js.Integer({ value: this.minimum });
}
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [valueMinimum]
}));
}
if (MAXIMUM in this) {
let valueMaximum: number | asn1js.Integer = 0;
if (this.maximum instanceof asn1js.Integer) {
valueMaximum = this.maximum;
} else {
valueMaximum = new asn1js.Integer({ value: this.maximum });
}
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [valueMaximum]
}));
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): GeneralSubtreeJson {
const res: GeneralSubtreeJson = {
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;
}
}

34
third_party/js/PKI.js/src/Helpers.ts поставляемый
Просмотреть файл

@ -1,34 +0,0 @@
import { EMPTY_STRING } from "./constants";
/**
* String preparation function. In a future here will be realization of algorithm from RFC4518
* @param inputString JavaScript string. As soon as for each ASN.1 string type we have a specific
* transformation function here we will work with pure JavaScript string
* @returns Formatted string
*/
export function stringPrep(inputString: string): string {
//#region Initial variables
let isSpace = false;
let cutResult = EMPTY_STRING;
//#endregion
const result = inputString.trim(); // Trim input string
//#region Change all sequence of SPACE down to SPACE char
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];
}
}
//#endregion
return cutResult.toLowerCase();
}

118
third_party/js/PKI.js/src/InfoAccess.ts поставляемый
Просмотреть файл

@ -1,118 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AccessDescription, AccessDescriptionJson } from "./AccessDescription";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const ACCESS_DESCRIPTIONS = "accessDescriptions";
export interface IInfoAccess {
accessDescriptions: AccessDescription[];
}
export interface InfoAccessJson {
accessDescriptions: AccessDescriptionJson[];
}
export type InfoAccessParameters = PkiObjectParameters & Partial<IInfoAccess>;
/**
* Represents the InfoAccess structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class InfoAccess extends PkiObject implements IInfoAccess {
public static override CLASS_NAME = "InfoAccess";
public accessDescriptions!: AccessDescription[];
/**
* Initializes a new instance of the {@link InfoAccess} class
* @param parameters Initialization parameters
*/
constructor(parameters: InfoAccessParameters = {}) {
super();
this.accessDescriptions = pvutils.getParametersValue(parameters, ACCESS_DESCRIPTIONS, InfoAccess.defaultValues(ACCESS_DESCRIPTIONS));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ACCESS_DESCRIPTIONS): AccessDescription[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ACCESS_DESCRIPTIONS:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* AuthorityInfoAccessSyntax ::=
* SEQUENCE SIZE (1..MAX) OF AccessDescription
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
accessDescriptions?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.accessDescriptions || EMPTY_STRING),
value: AccessDescription.schema()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, [
ACCESS_DESCRIPTIONS
]);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
InfoAccess.schema({
names: {
accessDescriptions: ACCESS_DESCRIPTIONS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.accessDescriptions = Array.from(asn1.result.accessDescriptions, element => new AccessDescription({ schema: element }));
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: Array.from(this.accessDescriptions, o => o.toSchema())
}));
}
public toJSON(): InfoAccessJson {
return {
accessDescriptions: Array.from(this.accessDescriptions, o => o.toJSON())
};
}
}

Просмотреть файл

@ -1,153 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { RelativeDistinguishedNames, RelativeDistinguishedNamesJson, RelativeDistinguishedNamesSchema } from "./RelativeDistinguishedNames";
import * as Schema from "./Schema";
const ISSUER = "issuer";
const SERIAL_NUMBER = "serialNumber";
const CLEAR_PROPS = [
ISSUER,
SERIAL_NUMBER,
];
export interface IIssuerAndSerialNumber {
/**
* Certificate issuer name
*/
issuer: RelativeDistinguishedNames;
/**
* Certificate serial number
*/
serialNumber: asn1js.Integer;
}
export interface IssuerAndSerialNumberJson {
issuer: RelativeDistinguishedNamesJson;
serialNumber: asn1js.IntegerJson;
}
export type IssuerAndSerialNumberParameters = PkiObjectParameters & Partial<IIssuerAndSerialNumber>;
export type IssuerAndSerialNumberSchema = Schema.SchemaParameters<{
issuer?: RelativeDistinguishedNamesSchema;
serialNumber?: string;
}>;
/**
* Represents the IssuerAndSerialNumber structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class IssuerAndSerialNumber extends PkiObject implements IIssuerAndSerialNumber {
public static override CLASS_NAME = "IssuerAndSerialNumber";
public issuer!: RelativeDistinguishedNames;
public serialNumber!: asn1js.Integer;
/**
* Initializes a new instance of the {@link IssuerAndSerialNumber} class
* @param parameters Initialization parameters
*/
constructor(parameters: IssuerAndSerialNumberParameters = {}) {
super();
this.issuer = pvutils.getParametersValue(parameters, ISSUER, IssuerAndSerialNumber.defaultValues(ISSUER));
this.serialNumber = pvutils.getParametersValue(parameters, SERIAL_NUMBER, IssuerAndSerialNumber.defaultValues(SERIAL_NUMBER));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ISSUER): RelativeDistinguishedNames;
public static override defaultValues(memberName: typeof SERIAL_NUMBER): asn1js.Integer;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ISSUER:
return new RelativeDistinguishedNames();
case SERIAL_NUMBER:
return new asn1js.Integer();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* IssuerAndSerialNumber ::= SEQUENCE {
* issuer Name,
* serialNumber CertificateSerialNumber }
*
* CertificateSerialNumber ::= INTEGER
*```
*/
public static override schema(parameters: IssuerAndSerialNumberSchema = {}): Schema.SchemaType {
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [issuer]
* @property {string} [serialNumber]
*/
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
RelativeDistinguishedNames.schema(names.issuer || {}),
new asn1js.Integer({ name: (names.serialNumber || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
IssuerAndSerialNumber.schema({
names: {
issuer: {
names: {
blockName: ISSUER
}
},
serialNumber: SERIAL_NUMBER
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.issuer = new RelativeDistinguishedNames({ schema: asn1.result.issuer });
this.serialNumber = asn1.result.serialNumber;
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
this.issuer.toSchema(),
this.serialNumber
]
}));
}
public toJSON(): IssuerAndSerialNumberJson {
return {
issuer: this.issuer.toJSON(),
serialNumber: this.serialNumber.toJSON(),
};
}
}

Просмотреть файл

@ -1,429 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { GeneralName, GeneralNameJson } from "./GeneralName";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { RelativeDistinguishedNames, RelativeDistinguishedNamesJson } from "./RelativeDistinguishedNames";
import * as Schema from "./Schema";
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 = [
DISTRIBUTION_POINT,
DISTRIBUTION_POINT_NAMES,
ONLY_CONTAINS_USER_CERTS,
ONLY_CONTAINS_CA_CERTS,
ONLY_SOME_REASON,
INDIRECT_CRL,
ONLY_CONTAINS_ATTRIBUTE_CERTS,
];
export interface IIssuingDistributionPoint {
distributionPoint?: DistributionPointName;
onlyContainsUserCerts: boolean;
onlyContainsCACerts: boolean;
onlySomeReasons?: number;
indirectCRL: boolean;
onlyContainsAttributeCerts: boolean;
}
export interface IssuingDistributionPointJson {
distributionPoint?: DistributionPointNameJson;
onlyContainsUserCerts?: boolean;
onlyContainsCACerts?: boolean;
onlySomeReasons?: number;
indirectCRL?: boolean;
onlyContainsAttributeCerts?: boolean;
}
export type DistributionPointName = GeneralName[] | RelativeDistinguishedNames;
export type DistributionPointNameJson = GeneralNameJson[] | RelativeDistinguishedNamesJson;
export type IssuingDistributionPointParameters = PkiObjectParameters & Partial<IIssuingDistributionPoint>;
/**
* Represents the IssuingDistributionPoint structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class IssuingDistributionPoint extends PkiObject implements IIssuingDistributionPoint {
public static override CLASS_NAME = "IssuingDistributionPoint";
public distributionPoint?: DistributionPointName;
public onlyContainsUserCerts!: boolean;
public onlyContainsCACerts!: boolean;
public onlySomeReasons?: number;
public indirectCRL!: boolean;
public onlyContainsAttributeCerts!: boolean;
/**
* Initializes a new instance of the {@link IssuingDistributionPoint} class
* @param parameters Initialization parameters
*/
constructor(parameters: IssuingDistributionPointParameters = {}) {
super();
if (DISTRIBUTION_POINT in parameters) {
this.distributionPoint = pvutils.getParametersValue(parameters, DISTRIBUTION_POINT, IssuingDistributionPoint.defaultValues(DISTRIBUTION_POINT));
}
this.onlyContainsUserCerts = pvutils.getParametersValue(parameters, ONLY_CONTAINS_USER_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS));
this.onlyContainsCACerts = pvutils.getParametersValue(parameters, ONLY_CONTAINS_CA_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS));
if (ONLY_SOME_REASON in parameters) {
this.onlySomeReasons = pvutils.getParametersValue(parameters, ONLY_SOME_REASON, IssuingDistributionPoint.defaultValues(ONLY_SOME_REASON));
}
this.indirectCRL = pvutils.getParametersValue(parameters, INDIRECT_CRL, IssuingDistributionPoint.defaultValues(INDIRECT_CRL));
this.onlyContainsAttributeCerts = pvutils.getParametersValue(parameters, ONLY_CONTAINS_ATTRIBUTE_CERTS, IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof DISTRIBUTION_POINT): DistributionPointName;
public static override defaultValues(memberName: typeof ONLY_CONTAINS_USER_CERTS): boolean;
public static override defaultValues(memberName: typeof ONLY_CONTAINS_CA_CERTS): boolean;
public static override defaultValues(memberName: typeof ONLY_SOME_REASON): number;
public static override defaultValues(memberName: typeof INDIRECT_CRL): boolean;
public static override defaultValues(memberName: typeof ONLY_CONTAINS_ATTRIBUTE_CERTS): boolean;
public static override defaultValues(memberName: string): any {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* IssuingDistributionPoint ::= SEQUENCE {
* distributionPoint [0] DistributionPointName OPTIONAL,
* onlyContainsUserCerts [1] BOOLEAN DEFAULT FALSE,
* onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE,
* onlySomeReasons [3] ReasonFlags OPTIONAL,
* indirectCRL [4] BOOLEAN DEFAULT FALSE,
* onlyContainsAttributeCerts [5] BOOLEAN DEFAULT FALSE }
*
* ReasonFlags ::= BIT STRING {
* unused (0),
* keyCompromise (1),
* cACompromise (2),
* affiliationChanged (3),
* superseded (4),
* cessationOfOperation (5),
* certificateHold (6),
* privilegeWithdrawn (7),
* aACompromise (8) }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
distributionPoint?: string;
distributionPointNames?: string;
onlyContainsUserCerts?: string;
onlyContainsCACerts?: string;
onlySomeReasons?: string;
indirectCRL?: string;
onlyContainsAttributeCerts?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Choice({
value: [
new asn1js.Constructed({
name: (names.distributionPoint || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Repeated({
name: (names.distributionPointNames || EMPTY_STRING),
value: GeneralName.schema()
})
]
}),
new asn1js.Constructed({
name: (names.distributionPoint || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: RelativeDistinguishedNames.schema().valueBlock.value
})
]
})
]
}),
new asn1js.Primitive({
name: (names.onlyContainsUserCerts || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
}
}), // IMPLICIT boolean value
new asn1js.Primitive({
name: (names.onlyContainsCACerts || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [2]
}
}), // IMPLICIT boolean value
new asn1js.Primitive({
name: (names.onlySomeReasons || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
}
}), // IMPLICIT BitString value
new asn1js.Primitive({
name: (names.indirectCRL || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 4 // [4]
}
}), // IMPLICIT boolean value
new asn1js.Primitive({
name: (names.onlyContainsAttributeCerts || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 5 // [5]
}
}) // IMPLICIT boolean value
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.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);
// Get internal properties from parsed schema
if (DISTRIBUTION_POINT in asn1.result) {
switch (true) {
case (asn1.result.distributionPoint.idBlock.tagNumber === 0): // GENERAL_NAMES variant
this.distributionPoint = Array.from(asn1.result.distributionPointNames, element => new GeneralName({ schema: element }));
break;
case (asn1.result.distributionPoint.idBlock.tagNumber === 1): // RDN variant
{
this.distributionPoint = new RelativeDistinguishedNames({
schema: new asn1js.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);
}
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
if (this.distributionPoint) {
let value;
if (this.distributionPoint instanceof Array) {
value = new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: Array.from(this.distributionPoint, o => o.toSchema())
});
} else {
value = this.distributionPoint.toSchema();
value.idBlock.tagClass = 3; // CONTEXT - SPECIFIC
value.idBlock.tagNumber = 1; // [1]
}
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [value]
}));
}
if (this.onlyContainsUserCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_USER_CERTS)) {
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
valueHex: (new Uint8Array([0xFF])).buffer
}));
}
if (this.onlyContainsCACerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_CA_CERTS)) {
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 2 // [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 asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 3 // [3]
},
valueHex: buffer
}));
}
if (this.indirectCRL !== IssuingDistributionPoint.defaultValues(INDIRECT_CRL)) {
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 4 // [4]
},
valueHex: (new Uint8Array([0xFF])).buffer
}));
}
if (this.onlyContainsAttributeCerts !== IssuingDistributionPoint.defaultValues(ONLY_CONTAINS_ATTRIBUTE_CERTS)) {
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 5 // [5]
},
valueHex: (new Uint8Array([0xFF])).buffer
}));
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): IssuingDistributionPointJson {
const obj: IssuingDistributionPointJson = {};
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;
}
}

207
third_party/js/PKI.js/src/KEKIdentifier.ts поставляемый
Просмотреть файл

@ -1,207 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { OtherKeyAttribute, OtherKeyAttributeJson, OtherKeyAttributeSchema } from "./OtherKeyAttribute";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const KEY_IDENTIFIER = "keyIdentifier";
const DATE = "date";
const OTHER = "other";
const CLEAR_PROPS = [
KEY_IDENTIFIER,
DATE,
OTHER,
];
export interface IKEKIdentifier {
keyIdentifier: asn1js.OctetString;
date?: asn1js.GeneralizedTime;
other?: OtherKeyAttribute;
}
export interface KEKIdentifierJson {
keyIdentifier: asn1js.OctetStringJson;
date?: asn1js.GeneralizedTime;
other?: OtherKeyAttributeJson;
}
export type KEKIdentifierParameters = PkiObjectParameters & Partial<IKEKIdentifier>;
export type KEKIdentifierSchema = Schema.SchemaParameters<{
keyIdentifier?: string;
date?: string;
other?: OtherKeyAttributeSchema;
}>;
/**
* Represents the KEKIdentifier structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class KEKIdentifier extends PkiObject implements IKEKIdentifier {
public static override CLASS_NAME = "KEKIdentifier";
public keyIdentifier!: asn1js.OctetString;
public date?: asn1js.GeneralizedTime;
public other?: OtherKeyAttribute;
/**
* Initializes a new instance of the {@link KEKIdentifier} class
* @param parameters Initialization parameters
*/
constructor(parameters: KEKIdentifierParameters = {}) {
super();
this.keyIdentifier = pvutils.getParametersValue(parameters, KEY_IDENTIFIER, KEKIdentifier.defaultValues(KEY_IDENTIFIER));
if (DATE in parameters) {
this.date = pvutils.getParametersValue(parameters, DATE, KEKIdentifier.defaultValues(DATE));
}
if (OTHER in parameters) {
this.other = pvutils.getParametersValue(parameters, OTHER, KEKIdentifier.defaultValues(OTHER));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof KEY_IDENTIFIER): asn1js.OctetString;
public static override defaultValues(memberName: typeof DATE): asn1js.GeneralizedTime;
public static override defaultValues(memberName: typeof OTHER): OtherKeyAttribute;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case KEY_IDENTIFIER:
return new asn1js.OctetString();
case DATE:
return new asn1js.GeneralizedTime();
case OTHER:
return new OtherKeyAttribute();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* KEKIdentifier ::= SEQUENCE {
* keyIdentifier OCTET STRING,
* date GeneralizedTime OPTIONAL,
* other OtherKeyAttribute OPTIONAL }
*```
*/
public static override schema(parameters: KEKIdentifierSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.OctetString({ name: (names.keyIdentifier || EMPTY_STRING) }),
new asn1js.GeneralizedTime({
optional: true,
name: (names.date || EMPTY_STRING)
}),
OtherKeyAttribute.schema(names.other || {})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
KEKIdentifier.schema({
names: {
keyIdentifier: KEY_IDENTIFIER,
date: DATE,
other: {
names: {
blockName: OTHER
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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 });
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(this.keyIdentifier);
if (this.date) {
outputArray.push(this.date);
}
if (this.other) {
outputArray.push(this.other.toSchema());
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): KEKIdentifierJson {
const res: KEKIdentifierJson = {
keyIdentifier: this.keyIdentifier.toJSON()
};
if (this.date) {
res.date = this.date;
}
if (this.other) {
res.other = this.other.toJSON();
}
return res;
}
}

213
third_party/js/PKI.js/src/KEKRecipientInfo.ts поставляемый
Просмотреть файл

@ -1,213 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { KEKIdentifier, KEKIdentifierJson, KEKIdentifierSchema } from "./KEKIdentifier";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import * as Schema from "./Schema";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_BUFFER, EMPTY_STRING } from "./constants";
const VERSION = "version";
const KEK_ID = "kekid";
const KEY_ENCRYPTION_ALGORITHM = "keyEncryptionAlgorithm";
const ENCRYPTED_KEY = "encryptedKey";
const PER_DEFINED_KEK = "preDefinedKEK";
const CLEAR_PROPS = [
VERSION,
KEK_ID,
KEY_ENCRYPTION_ALGORITHM,
ENCRYPTED_KEY,
];
export interface IKEKRecipientInfo {
version: number;
kekid: KEKIdentifier;
keyEncryptionAlgorithm: AlgorithmIdentifier;
encryptedKey: asn1js.OctetString;
preDefinedKEK: ArrayBuffer;
}
export interface KEKRecipientInfoJson {
version: number;
kekid: KEKIdentifierJson;
keyEncryptionAlgorithm: AlgorithmIdentifierJson;
encryptedKey: asn1js.OctetStringJson;
}
export type KEKRecipientInfoParameters = PkiObjectParameters & Partial<IKEKRecipientInfo>;
/**
* Represents the KEKRecipientInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class KEKRecipientInfo extends PkiObject implements IKEKRecipientInfo {
public static override CLASS_NAME = "KEKRecipientInfo";
public version!: number;
public kekid!: KEKIdentifier;
public keyEncryptionAlgorithm!: AlgorithmIdentifier;
public encryptedKey!: asn1js.OctetString;
public preDefinedKEK!: ArrayBuffer;
/**
* Initializes a new instance of the {@link KEKRecipientInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: KEKRecipientInfoParameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, KEKRecipientInfo.defaultValues(VERSION));
this.kekid = pvutils.getParametersValue(parameters, KEK_ID, KEKRecipientInfo.defaultValues(KEK_ID));
this.keyEncryptionAlgorithm = pvutils.getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM, KEKRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM));
this.encryptedKey = pvutils.getParametersValue(parameters, ENCRYPTED_KEY, KEKRecipientInfo.defaultValues(ENCRYPTED_KEY));
this.preDefinedKEK = pvutils.getParametersValue(parameters, PER_DEFINED_KEK, KEKRecipientInfo.defaultValues(PER_DEFINED_KEK));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof KEK_ID): KEKIdentifier;
public static override defaultValues(memberName: typeof KEY_ENCRYPTION_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ENCRYPTED_KEY): asn1js.OctetString;
public static override defaultValues(memberName: typeof PER_DEFINED_KEK): ArrayBuffer;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return 0;
case KEK_ID:
return new KEKIdentifier();
case KEY_ENCRYPTION_ALGORITHM:
return new AlgorithmIdentifier();
case ENCRYPTED_KEY:
return new asn1js.OctetString();
case PER_DEFINED_KEK:
return EMPTY_BUFFER;
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case "KEKRecipientInfo":
return (memberValue === KEKRecipientInfo.defaultValues(VERSION));
case KEK_ID:
return ((memberValue.compareWithDefault("keyIdentifier", memberValue.keyIdentifier)) &&
(("date" in memberValue) === false) &&
(("other" in memberValue) === false));
case KEY_ENCRYPTION_ALGORITHM:
return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false));
case ENCRYPTED_KEY:
return (memberValue.isEqual(KEKRecipientInfo.defaultValues(ENCRYPTED_KEY)));
case PER_DEFINED_KEK:
return (memberValue.byteLength === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* KEKRecipientInfo ::= SEQUENCE {
* version CMSVersion, -- always set to 4
* kekid KEKIdentifier,
* keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
* encryptedKey EncryptedKey }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
version?: string;
kekid?: KEKIdentifierSchema;
keyEncryptionAlgorithm?: AlgorithmIdentifierSchema;
encryptedKey?: string;
}> = {}): Schema.SchemaType {
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [version]
* @property {string} [kekid]
* @property {string} [keyEncryptionAlgorithm]
* @property {string} [encryptedKey]
*/
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || EMPTY_STRING) }),
KEKIdentifier.schema(names.kekid || {}),
AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}),
new asn1js.OctetString({ name: (names.encryptedKey || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
KEKRecipientInfo.schema({
names: {
version: VERSION,
kekid: {
names: {
blockName: KEK_ID
}
},
keyEncryptionAlgorithm: {
names: {
blockName: KEY_ENCRYPTION_ALGORITHM
}
},
encryptedKey: ENCRYPTED_KEY
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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;
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.Integer({ value: this.version }),
this.kekid.toSchema(),
this.keyEncryptionAlgorithm.toSchema(),
this.encryptedKey
]
}));
}
public toJSON(): KEKRecipientInfoJson {
return {
version: this.version,
kekid: this.kekid.toJSON(),
keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(),
encryptedKey: this.encryptedKey.toJSON(),
};
}
}

Просмотреть файл

@ -1,188 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { IssuerAndSerialNumber, IssuerAndSerialNumberJson, IssuerAndSerialNumberSchema } from "./IssuerAndSerialNumber";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { RecipientKeyIdentifier, RecipientKeyIdentifierJson, RecipientKeyIdentifierSchema } from "./RecipientKeyIdentifier";
import * as Schema from "./Schema";
const VARIANT = "variant";
const VALUE = "value";
const CLEAR_PROPS = [
"blockName",
];
export interface IKeyAgreeRecipientIdentifier {
variant: number;
value: any;
}
export interface KeyAgreeRecipientIdentifierJson {
variant: number;
value?: IssuerAndSerialNumberJson | RecipientKeyIdentifierJson;
}
export type KeyAgreeRecipientIdentifierParameters = PkiObjectParameters & Partial<IKeyAgreeRecipientIdentifier>;
export type KeyAgreeRecipientIdentifierSchema = Schema.SchemaParameters<{
issuerAndSerialNumber?: IssuerAndSerialNumberSchema;
rKeyId?: RecipientKeyIdentifierSchema;
}>;
/**
* Represents the KeyAgreeRecipientIdentifier structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class KeyAgreeRecipientIdentifier extends PkiObject implements IKeyAgreeRecipientIdentifier {
public static override CLASS_NAME = "KeyAgreeRecipientIdentifier";
public variant!: number;
public value: any;
/**
* Initializes a new instance of the {@link KeyAgreeRecipientIdentifier} class
* @param parameters Initialization parameters
*/
constructor(parameters: KeyAgreeRecipientIdentifierParameters = {}) {
super();
this.variant = pvutils.getParametersValue(parameters, VARIANT, KeyAgreeRecipientIdentifier.defaultValues(VARIANT));
this.value = pvutils.getParametersValue(parameters, VALUE, KeyAgreeRecipientIdentifier.defaultValues(VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VARIANT): number;
public static override defaultValues(memberName: typeof VALUE): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VARIANT:
return (-1);
case VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VARIANT:
return (memberValue === (-1));
case VALUE:
return (Object.keys(memberValue).length === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* KeyAgreeRecipientIdentifier ::= CHOICE {
* issuerAndSerialNumber IssuerAndSerialNumber,
* rKeyId [0] IMPLICIT RecipientKeyIdentifier }
*```
*/
public static override schema(parameters: KeyAgreeRecipientIdentifierSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Choice({
value: [
IssuerAndSerialNumber.schema(names.issuerAndSerialNumber || {
names: {
blockName: (names.blockName || EMPTY_STRING)
}
}),
new asn1js.Constructed({
name: (names.blockName || EMPTY_STRING),
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: RecipientKeyIdentifier.schema(names.rKeyId || {
names: {
blockName: (names.blockName || EMPTY_STRING)
}
}).valueBlock.value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
KeyAgreeRecipientIdentifier.schema({
names: {
blockName: "blockName"
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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 asn1js.Sequence({
value: asn1.result.blockName.valueBlock.value
})
});
}
}
public toSchema(): asn1js.BaseBlock<any> {
//#region Construct and return new ASN.1 schema for this object
switch (this.variant) {
case 1:
return this.value.toSchema();
case 2:
return new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: this.value.toSchema().valueBlock.value
});
default:
return new asn1js.Any() as any;
}
//#endregion
}
public toJSON(): KeyAgreeRecipientIdentifierJson {
const res: KeyAgreeRecipientIdentifierJson = {
variant: this.variant,
};
if ((this.variant === 1) || (this.variant === 2)) {
res.value = this.value.toJSON();
}
return res;
}
}

Просмотреть файл

@ -1,285 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { OriginatorIdentifierOrKey, OriginatorIdentifierOrKeyJson, OriginatorIdentifierOrKeySchema } from "./OriginatorIdentifierOrKey";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { RecipientEncryptedKeys, RecipientEncryptedKeysJson, RecipientEncryptedKeysSchema } from "./RecipientEncryptedKeys";
import { Certificate } from "./Certificate";
import * as Schema from "./Schema";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_STRING } from "./constants";
const VERSION = "version";
const ORIGINATOR = "originator";
const UKM = "ukm";
const KEY_ENCRYPTION_ALGORITHM = "keyEncryptionAlgorithm";
const RECIPIENT_ENCRYPTED_KEY = "recipientEncryptedKeys";
const RECIPIENT_CERTIFICATE = "recipientCertificate";
const RECIPIENT_PUBLIC_KEY = "recipientPublicKey";
const CLEAR_PROPS = [
VERSION,
ORIGINATOR,
UKM,
KEY_ENCRYPTION_ALGORITHM,
RECIPIENT_ENCRYPTED_KEY,
];
export interface IKeyAgreeRecipientInfo {
version: number;
originator: OriginatorIdentifierOrKey;
ukm?: asn1js.OctetString;
keyEncryptionAlgorithm: AlgorithmIdentifier;
recipientEncryptedKeys: RecipientEncryptedKeys;
recipientCertificate: Certificate;
recipientPublicKey: CryptoKey | null;
}
export interface KeyAgreeRecipientInfoJson {
version: number;
originator: OriginatorIdentifierOrKeyJson;
ukm?: asn1js.OctetStringJson;
keyEncryptionAlgorithm: AlgorithmIdentifierJson;
recipientEncryptedKeys: RecipientEncryptedKeysJson;
}
export type KeyAgreeRecipientInfoParameters = PkiObjectParameters & Partial<IKeyAgreeRecipientInfo>;
/**
* Represents the KeyAgreeRecipientInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class KeyAgreeRecipientInfo extends PkiObject implements IKeyAgreeRecipientInfo {
public static override CLASS_NAME = "KeyAgreeRecipientInfo";
public version!: number;
public originator!: OriginatorIdentifierOrKey;
public ukm?: asn1js.OctetString;
public keyEncryptionAlgorithm!: AlgorithmIdentifier;
public recipientEncryptedKeys!: RecipientEncryptedKeys;
public recipientCertificate!: Certificate;
public recipientPublicKey!: CryptoKey | null;
/**
* Initializes a new instance of the {@link KeyAgreeRecipientInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: KeyAgreeRecipientInfoParameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, KeyAgreeRecipientInfo.defaultValues(VERSION));
this.originator = pvutils.getParametersValue(parameters, ORIGINATOR, KeyAgreeRecipientInfo.defaultValues(ORIGINATOR));
if (UKM in parameters) {
this.ukm = pvutils.getParametersValue(parameters, UKM, KeyAgreeRecipientInfo.defaultValues(UKM));
}
this.keyEncryptionAlgorithm = pvutils.getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM, KeyAgreeRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM));
this.recipientEncryptedKeys = pvutils.getParametersValue(parameters, RECIPIENT_ENCRYPTED_KEY, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_ENCRYPTED_KEY));
this.recipientCertificate = pvutils.getParametersValue(parameters, RECIPIENT_CERTIFICATE, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_CERTIFICATE));
this.recipientPublicKey = pvutils.getParametersValue(parameters, RECIPIENT_PUBLIC_KEY, KeyAgreeRecipientInfo.defaultValues(RECIPIENT_PUBLIC_KEY));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof ORIGINATOR): OriginatorIdentifierOrKey;
public static override defaultValues(memberName: typeof UKM): asn1js.OctetString;
public static override defaultValues(memberName: typeof KEY_ENCRYPTION_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof RECIPIENT_ENCRYPTED_KEY): RecipientEncryptedKeys;
public static override defaultValues(memberName: typeof RECIPIENT_CERTIFICATE): Certificate;
public static override defaultValues(memberName: typeof RECIPIENT_PUBLIC_KEY): null;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return 0;
case ORIGINATOR:
return new OriginatorIdentifierOrKey();
case UKM:
return new asn1js.OctetString();
case KEY_ENCRYPTION_ALGORITHM:
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);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VERSION:
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:
return ((memberValue.algorithmId === EMPTY_STRING) && (("algorithmParams" in memberValue) === false));
case RECIPIENT_ENCRYPTED_KEY:
return (memberValue.encryptedKeys.length === 0);
case RECIPIENT_CERTIFICATE:
return false; // For now leave it as is
case RECIPIENT_PUBLIC_KEY:
return false;
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* KeyAgreeRecipientInfo ::= SEQUENCE {
* version CMSVersion, -- always set to 3
* originator [0] EXPLICIT OriginatorIdentifierOrKey,
* ukm [1] EXPLICIT UserKeyingMaterial OPTIONAL,
* keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
* recipientEncryptedKeys RecipientEncryptedKeys }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
version?: string;
originator?: OriginatorIdentifierOrKeySchema;
ukm?: string;
keyEncryptionAlgorithm?: AlgorithmIdentifierSchema;
recipientEncryptedKeys?: RecipientEncryptedKeysSchema;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: names.blockName || EMPTY_STRING,
value: [
new asn1js.Integer({ name: names.version || EMPTY_STRING }),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
OriginatorIdentifierOrKey.schema(names.originator || {})
]
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [new asn1js.OctetString({ name: names.ukm || EMPTY_STRING })]
}),
AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}),
RecipientEncryptedKeys.schema(names.recipientEncryptedKeys || {})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
KeyAgreeRecipientInfo.schema({
names: {
version: VERSION,
originator: {
names: {
blockName: ORIGINATOR
}
},
ukm: UKM,
keyEncryptionAlgorithm: {
names: {
blockName: KEY_ENCRYPTION_ALGORITHM
}
},
recipientEncryptedKeys: {
names: {
blockName: RECIPIENT_ENCRYPTED_KEY
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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 });
}
public toSchema(): asn1js.Sequence {
//#region Create array for final sequence
const outputArray = [];
outputArray.push(new asn1js.Integer({ value: this.version }));
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [this.originator.toSchema()]
}));
if (this.ukm) {
outputArray.push(new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [this.ukm]
}));
}
outputArray.push(this.keyEncryptionAlgorithm.toSchema());
outputArray.push(this.recipientEncryptedKeys.toSchema());
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
/**
* Conversion for the class to JSON object
* @returns
*/
public toJSON(): KeyAgreeRecipientInfoJson {
const res: KeyAgreeRecipientInfoJson = {
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;
}
}

18
third_party/js/PKI.js/src/KeyBag.ts поставляемый
Просмотреть файл

@ -1,18 +0,0 @@
import { PrivateKeyInfo } from "./PrivateKeyInfo";
/**
* Class from RFC5208
*/
// TODO looks odd
export class KeyBag extends PrivateKeyInfo {
/**
* Constructor for Attribute class
* @param parameters
*/
constructor(parameters = {}) {
super(parameters);
}
}

Просмотреть файл

@ -1,233 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { Certificate } from "./Certificate";
import { RecipientIdentifier, RecipientIdentifierSchema } from "./RecipientIdentifier";
import { IssuerAndSerialNumber, IssuerAndSerialNumberJson } from "./IssuerAndSerialNumber";
import * as Schema from "./Schema";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_STRING } from "./constants";
const VERSION = "version";
const RID = "rid";
const KEY_ENCRYPTION_ALGORITHM = "keyEncryptionAlgorithm";
const ENCRYPTED_KEY = "encryptedKey";
const RECIPIENT_CERTIFICATE = "recipientCertificate";
const CLEAR_PROPS = [
VERSION,
RID,
KEY_ENCRYPTION_ALGORITHM,
ENCRYPTED_KEY,
];
export interface IKeyTransRecipientInfo {
version: number;
rid: RecipientIdentifierType;
keyEncryptionAlgorithm: AlgorithmIdentifier;
encryptedKey: asn1js.OctetString;
recipientCertificate: Certificate;
}
export interface KeyTransRecipientInfoJson {
version: number;
rid: RecipientIdentifierMixedJson;
keyEncryptionAlgorithm: AlgorithmIdentifierJson;
encryptedKey: asn1js.OctetStringJson;
}
export type RecipientIdentifierType = IssuerAndSerialNumber | asn1js.OctetString;
export type RecipientIdentifierMixedJson = IssuerAndSerialNumberJson | asn1js.OctetStringJson;
export type KeyTransRecipientInfoParameters = PkiObjectParameters & Partial<IKeyTransRecipientInfo>;
/**
* Represents the KeyTransRecipientInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class KeyTransRecipientInfo extends PkiObject implements IKeyTransRecipientInfo {
public static override CLASS_NAME = "KeyTransRecipientInfo";
public version!: number;
public rid!: RecipientIdentifierType;
public keyEncryptionAlgorithm!: AlgorithmIdentifier;
public encryptedKey!: asn1js.OctetString;
public recipientCertificate!: Certificate;
/**
* Initializes a new instance of the {@link KeyTransRecipientInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: KeyTransRecipientInfoParameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, KeyTransRecipientInfo.defaultValues(VERSION));
this.rid = pvutils.getParametersValue(parameters, RID, KeyTransRecipientInfo.defaultValues(RID));
this.keyEncryptionAlgorithm = pvutils.getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM, KeyTransRecipientInfo.defaultValues(KEY_ENCRYPTION_ALGORITHM));
this.encryptedKey = pvutils.getParametersValue(parameters, ENCRYPTED_KEY, KeyTransRecipientInfo.defaultValues(ENCRYPTED_KEY));
this.recipientCertificate = pvutils.getParametersValue(parameters, RECIPIENT_CERTIFICATE, KeyTransRecipientInfo.defaultValues(RECIPIENT_CERTIFICATE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof RID): RecipientIdentifierType;
public static override defaultValues(memberName: typeof KEY_ENCRYPTION_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ENCRYPTED_KEY): asn1js.OctetString;
public static override defaultValues(memberName: typeof RECIPIENT_CERTIFICATE): Certificate;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return (-1);
case RID:
return {};
case KEY_ENCRYPTION_ALGORITHM:
return new AlgorithmIdentifier();
case ENCRYPTED_KEY:
return new asn1js.OctetString();
case RECIPIENT_CERTIFICATE:
return new Certificate();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VERSION:
return (memberValue === KeyTransRecipientInfo.defaultValues(VERSION));
case RID:
return (Object.keys(memberValue).length === 0);
case KEY_ENCRYPTION_ALGORITHM:
case ENCRYPTED_KEY:
return memberValue.isEqual(KeyTransRecipientInfo.defaultValues(memberName as typeof ENCRYPTED_KEY));
case RECIPIENT_CERTIFICATE:
return false; // For now we do not need to compare any values with the RECIPIENT_CERTIFICATE
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* KeyTransRecipientInfo ::= SEQUENCE {
* version CMSVersion, -- always set to 0 or 2
* rid RecipientIdentifier,
* keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
* encryptedKey EncryptedKey }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
version?: string;
rid?: RecipientIdentifierSchema;
keyEncryptionAlgorithm?: AlgorithmIdentifierSchema;
encryptedKey?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || EMPTY_STRING) }),
RecipientIdentifier.schema(names.rid || {}),
AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}),
new asn1js.OctetString({ name: (names.encryptedKey || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
KeyTransRecipientInfo.schema({
names: {
version: VERSION,
rid: {
names: {
blockName: RID
}
},
keyEncryptionAlgorithm: {
names: {
blockName: KEY_ENCRYPTION_ALGORITHM
}
},
encryptedKey: ENCRYPTED_KEY
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.version = asn1.result.version.valueBlock.valueDec;
if (asn1.result.rid.idBlock.tagClass === 3) {
this.rid = new asn1js.OctetString({ valueHex: asn1.result.rid.valueBlock.valueHex }); // SubjectKeyIdentifier
} else {
this.rid = new IssuerAndSerialNumber({ schema: asn1.result.rid });
}
this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm });
this.encryptedKey = asn1.result.encryptedKey;
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
if (this.rid instanceof IssuerAndSerialNumber) {
this.version = 0;
outputArray.push(new asn1js.Integer({ value: this.version }));
outputArray.push(this.rid.toSchema());
}
else {
this.version = 2;
outputArray.push(new asn1js.Integer({ value: this.version }));
outputArray.push(new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
valueHex: this.rid.valueBlock.valueHexView
}));
}
outputArray.push(this.keyEncryptionAlgorithm.toSchema());
outputArray.push(this.encryptedKey);
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): KeyTransRecipientInfoJson {
return {
version: this.version,
rid: this.rid.toJSON(),
keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(),
encryptedKey: this.encryptedKey.toJSON(),
};
}
}

199
third_party/js/PKI.js/src/MacData.ts поставляемый
Просмотреть файл

@ -1,199 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { DigestInfo, DigestInfoJson, DigestInfoSchema } from "./DigestInfo";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const MAC = "mac";
const MAC_SALT = "macSalt";
const ITERATIONS = "iterations";
const CLEAR_PROPS = [
MAC,
MAC_SALT,
ITERATIONS
];
export interface IMacData {
mac: DigestInfo;
macSalt: asn1js.OctetString;
iterations?: number;
}
export interface MacDataJson {
mac: DigestInfoJson;
macSalt: asn1js.OctetStringJson;
iterations?: number;
}
export type MacDataParameters = PkiObjectParameters & Partial<IMacData>;
export type MacDataSchema = Schema.SchemaParameters<{
mac?: DigestInfoSchema;
macSalt?: string;
iterations?: string;
}>;
/**
* Represents the MacData structure described in [RFC7292](https://datatracker.ietf.org/doc/html/rfc7292)
*/
export class MacData extends PkiObject implements IMacData {
public static override CLASS_NAME = "MacData";
public mac!: DigestInfo;
public macSalt!: asn1js.OctetString;
public iterations?: number;
/**
* Initializes a new instance of the {@link MacData} class
* @param parameters Initialization parameters
*/
constructor(parameters: MacDataParameters = {}) {
super();
this.mac = pvutils.getParametersValue(parameters, MAC, MacData.defaultValues(MAC));
this.macSalt = pvutils.getParametersValue(parameters, MAC_SALT, MacData.defaultValues(MAC_SALT));
if (ITERATIONS in parameters) {
this.iterations = pvutils.getParametersValue(parameters, ITERATIONS, MacData.defaultValues(ITERATIONS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof MAC): DigestInfo;
public static override defaultValues(memberName: typeof MAC_SALT): asn1js.OctetString;
public static override defaultValues(memberName: typeof ITERATIONS): number;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case MAC:
return new DigestInfo();
case MAC_SALT:
return new asn1js.OctetString();
case ITERATIONS:
return 1;
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* MacData ::= SEQUENCE {
* mac DigestInfo,
* macSalt OCTET STRING,
* iterations INTEGER DEFAULT 1
* -- Note: The default is for historical reasons and its use is
* -- deprecated. A higher value, like 1024 is recommended.
* }
*```
*/
public static override schema(parameters: MacDataSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
optional: (names.optional || true),
value: [
DigestInfo.schema(names.mac || {
names: {
blockName: MAC
}
}),
new asn1js.OctetString({ name: (names.macSalt || MAC_SALT) }),
new asn1js.Integer({
optional: true,
name: (names.iterations || ITERATIONS)
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
MacData.schema({
names: {
mac: {
names: {
blockName: MAC
}
},
macSalt: MAC_SALT,
iterations: ITERATIONS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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;
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
const outputArray: any[] = [
this.mac.toSchema(),
this.macSalt
];
if (this.iterations !== undefined) {
outputArray.push(new asn1js.Integer({ value: this.iterations }));
}
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): MacDataJson {
const res: MacDataJson = {
mac: this.mac.toJSON(),
macSalt: this.macSalt.toJSON(),
};
if (this.iterations !== undefined) {
res.iterations = this.iterations;
}
return res;
}
}

181
third_party/js/PKI.js/src/MessageImprint.ts поставляемый
Просмотреть файл

@ -1,181 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
import * as common from "./common";
import { EMPTY_STRING } from "./constants";
export const HASH_ALGORITHM = "hashAlgorithm";
export const HASHED_MESSAGE = "hashedMessage";
const CLEAR_PROPS = [
HASH_ALGORITHM,
HASHED_MESSAGE,
];
export interface IMessageImprint {
hashAlgorithm: AlgorithmIdentifier;
hashedMessage: asn1js.OctetString;
}
export interface MessageImprintJson {
hashAlgorithm: AlgorithmIdentifierJson;
hashedMessage: asn1js.OctetStringJson;
}
export type MessageImprintParameters = PkiObjectParameters & Partial<IMessageImprint>;
export type MessageImprintSchema = Schema.SchemaParameters<{
hashAlgorithm?: AlgorithmIdentifierSchema;
hashedMessage?: string;
}>;
/**
* Represents the MessageImprint structure described in [RFC3161](https://www.ietf.org/rfc/rfc3161.txt)
*/
export class MessageImprint extends PkiObject implements IMessageImprint {
public static override CLASS_NAME = "MessageImprint";
/**
* Creates and fills a new instance of {@link MessageImprint}
* @param hashAlgorithm
* @param message
* @param crypto Crypto engine
* @returns New instance of {@link MessageImprint}
*/
public static async create(hashAlgorithm: string, message: BufferSource, crypto = common.getCrypto(true)): Promise<MessageImprint> {
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 asn1js.Null(),
}),
hashedMessage: new asn1js.OctetString({ valueHex: hashedMessage })
});
return res;
}
public hashAlgorithm!: AlgorithmIdentifier;
public hashedMessage!: asn1js.OctetString;
/**
* Initializes a new instance of the {@link MessageImprint} class
* @param parameters Initialization parameters
*/
constructor(parameters: MessageImprintParameters = {}) {
super();
this.hashAlgorithm = pvutils.getParametersValue(parameters, HASH_ALGORITHM, MessageImprint.defaultValues(HASH_ALGORITHM));
this.hashedMessage = pvutils.getParametersValue(parameters, HASHED_MESSAGE, MessageImprint.defaultValues(HASHED_MESSAGE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof HASH_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof HASHED_MESSAGE): asn1js.OctetString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case HASH_ALGORITHM:
return new AlgorithmIdentifier();
case HASHED_MESSAGE:
return new asn1js.OctetString();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* MessageImprint ::= SEQUENCE {
* hashAlgorithm AlgorithmIdentifier,
* hashedMessage OCTET STRING }
*```
*/
public static override schema(parameters: MessageImprintSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AlgorithmIdentifier.schema(names.hashAlgorithm || {}),
new asn1js.OctetString({ name: (names.hashedMessage || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
MessageImprint.schema({
names: {
hashAlgorithm: {
names: {
blockName: HASH_ALGORITHM
}
},
hashedMessage: HASHED_MESSAGE
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.hashAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.hashAlgorithm });
this.hashedMessage = asn1.result.hashedMessage;
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
this.hashAlgorithm.toSchema(),
this.hashedMessage
]
}));
//#endregion
}
public toJSON(): MessageImprintJson {
return {
hashAlgorithm: this.hashAlgorithm.toJSON(),
hashedMessage: this.hashedMessage.toJSON(),
};
}
}

191
third_party/js/PKI.js/src/NameConstraints.ts поставляемый
Просмотреть файл

@ -1,191 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { GeneralSubtree, GeneralSubtreeJson } from "./GeneralSubtree";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const PERMITTED_SUBTREES = "permittedSubtrees";
const EXCLUDED_SUBTREES = "excludedSubtrees";
const CLEAR_PROPS = [
PERMITTED_SUBTREES,
EXCLUDED_SUBTREES
];
export interface INameConstraints {
permittedSubtrees?: GeneralSubtree[];
excludedSubtrees?: GeneralSubtree[];
}
export interface NameConstraintsJson {
permittedSubtrees?: GeneralSubtreeJson[];
excludedSubtrees?: GeneralSubtreeJson[];
}
export type NameConstraintsParameters = PkiObjectParameters & Partial<INameConstraints>;
/**
* Represents the NameConstraints structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class NameConstraints extends PkiObject implements INameConstraints {
public static override CLASS_NAME = "NameConstraints";
public permittedSubtrees?: GeneralSubtree[];
public excludedSubtrees?: GeneralSubtree[];
/**
* Initializes a new instance of the {@link NameConstraints} class
* @param parameters Initialization parameters
*/
constructor(parameters: NameConstraintsParameters = {}) {
super();
if (PERMITTED_SUBTREES in parameters) {
this.permittedSubtrees = pvutils.getParametersValue(parameters, PERMITTED_SUBTREES, NameConstraints.defaultValues(PERMITTED_SUBTREES));
}
if (EXCLUDED_SUBTREES in parameters) {
this.excludedSubtrees = pvutils.getParametersValue(parameters, EXCLUDED_SUBTREES, NameConstraints.defaultValues(EXCLUDED_SUBTREES));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof PERMITTED_SUBTREES): GeneralSubtree[];
public static override defaultValues(memberName: typeof EXCLUDED_SUBTREES): GeneralSubtree[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case PERMITTED_SUBTREES:
case EXCLUDED_SUBTREES:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* NameConstraints ::= SEQUENCE {
* permittedSubtrees [0] GeneralSubtrees OPTIONAL,
* excludedSubtrees [1] GeneralSubtrees OPTIONAL }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
permittedSubtrees?: string;
excludedSubtrees?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
new asn1js.Repeated({
name: (names.permittedSubtrees || EMPTY_STRING),
value: GeneralSubtree.schema()
})
]
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: [
new asn1js.Repeated({
name: (names.excludedSubtrees || EMPTY_STRING),
value: GeneralSubtree.schema()
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
NameConstraints.schema({
names: {
permittedSubtrees: PERMITTED_SUBTREES,
excludedSubtrees: EXCLUDED_SUBTREES
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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 }));
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
if (this.permittedSubtrees) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: Array.from(this.permittedSubtrees, o => o.toSchema())
}));
}
if (this.excludedSubtrees) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: Array.from(this.excludedSubtrees, o => o.toSchema())
}));
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): NameConstraintsJson {
const object: NameConstraintsJson = {};
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;
}
}

279
third_party/js/PKI.js/src/OCSPRequest.ts поставляемый
Просмотреть файл

@ -1,279 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import * as common from "./common";
import { TBSRequest, TBSRequestJson, TBSRequestSchema } from "./TBSRequest";
import { Signature, SignatureJson, SignatureSchema } from "./Signature";
import { Request } from "./Request";
import { CertID, CertIDCreateParams } from "./CertID";
import * as Schema from "./Schema";
import { Certificate } from "./Certificate";
import { AsnError, ParameterError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
const TBS_REQUEST = "tbsRequest";
const OPTIONAL_SIGNATURE = "optionalSignature";
const CLEAR_PROPS = [
TBS_REQUEST,
OPTIONAL_SIGNATURE
];
export interface IOCSPRequest {
tbsRequest: TBSRequest;
optionalSignature?: Signature;
}
export interface OCSPRequestJson {
tbsRequest: TBSRequestJson;
optionalSignature?: SignatureJson;
}
export type OCSPRequestParameters = PkiObjectParameters & Partial<IOCSPRequest>;
/**
* Represents an OCSP request described in [RFC6960 Section 4.1](https://datatracker.ietf.org/doc/html/rfc6960#section-4.1)
*
* @example The following example demonstrates how to create OCSP request
* ```js
* // Create OCSP request
* const ocspReq = new pkijs.OCSPRequest();
*
* ocspReq.tbsRequest.requestorName = new pkijs.GeneralName({
* type: 4,
* value: cert.subject,
* });
*
* await ocspReq.createForCertificate(cert, {
* hashAlgorithm: "SHA-256",
* issuerCertificate: issuerCert,
* });
*
* const nonce = pkijs.getRandomValues(new Uint8Array(10));
* ocspReq.tbsRequest.requestExtensions = [
* new pkijs.Extension({
* extnID: "1.3.6.1.5.5.7.48.1.2", // nonce
* extnValue: new asn1js.OctetString({ valueHex: nonce.buffer }).toBER(),
* })
* ];
*
* // Encode OCSP request
* const ocspReqRaw = ocspReq.toSchema(true).toBER();
* ```
*/
export class OCSPRequest extends PkiObject implements IOCSPRequest {
public static override CLASS_NAME = "OCSPRequest";
public tbsRequest!: TBSRequest;
public optionalSignature?: Signature;
/**
* Initializes a new instance of the {@link OCSPRequest} class
* @param parameters Initialization parameters
*/
constructor(parameters: OCSPRequestParameters = {}) {
super();
this.tbsRequest = pvutils.getParametersValue(parameters, TBS_REQUEST, OCSPRequest.defaultValues(TBS_REQUEST));
if (OPTIONAL_SIGNATURE in parameters) {
this.optionalSignature = pvutils.getParametersValue(parameters, OPTIONAL_SIGNATURE, OCSPRequest.defaultValues(OPTIONAL_SIGNATURE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof TBS_REQUEST): TBSRequest;
public static override defaultValues(memberName: typeof OPTIONAL_SIGNATURE): Signature;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case TBS_REQUEST:
return new TBSRequest();
case OPTIONAL_SIGNATURE:
return new Signature();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
* @returns Returns `true` if `memberValue` is equal to default value for selected class member
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OCSPRequest ::= SEQUENCE {
* tbsRequest TBSRequest,
* optionalSignature [0] EXPLICIT Signature OPTIONAL }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
tbsRequest?: TBSRequestSchema;
optionalSignature?: SignatureSchema;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: names.blockName || "OCSPRequest",
value: [
TBSRequest.schema(names.tbsRequest || {
names: {
blockName: TBS_REQUEST
}
}),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
Signature.schema(names.optionalSignature || {
names: {
blockName: OPTIONAL_SIGNATURE
}
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OCSPRequest.schema()
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.tbsRequest = new TBSRequest({ schema: asn1.result.tbsRequest });
if (OPTIONAL_SIGNATURE in asn1.result)
this.optionalSignature = new Signature({ schema: asn1.result.optionalSignature });
}
public toSchema(encodeFlag = false) {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(this.tbsRequest.toSchema(encodeFlag));
if (this.optionalSignature)
outputArray.push(
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
this.optionalSignature.toSchema()
]
}));
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): OCSPRequestJson {
const res: OCSPRequestJson = {
tbsRequest: this.tbsRequest.toJSON()
};
if (this.optionalSignature) {
res.optionalSignature = this.optionalSignature.toJSON();
}
return res;
}
/**
* Making OCSP Request for specific certificate
* @param certificate Certificate making OCSP Request for
* @param parameters Additional parameters
* @param crypto Crypto engine
*/
public async createForCertificate(certificate: Certificate, parameters: CertIDCreateParams, crypto = common.getCrypto(true)): Promise<void> {
//#region Initial variables
const certID = new CertID();
//#endregion
//#region Create OCSP certificate identifier for the certificate
await certID.createForCertificate(certificate, parameters, crypto);
//#endregion
//#region Make final request data
this.tbsRequest.requestList.push(new Request({
reqCert: certID,
}));
//#endregion
}
/**
* Make signature for current OCSP Request
* @param privateKey Private key for "subjectPublicKeyInfo" structure
* @param hashAlgorithm Hashing algorithm. Default SHA-1
* @param crypto Crypto engine
*/
public async sign(privateKey: CryptoKey, hashAlgorithm = "SHA-1", crypto = common.getCrypto(true)) {
// Initial checking
ParameterError.assertEmpty(privateKey, "privateKey", "OCSPRequest.sign method");
// Check that OPTIONAL_SIGNATURE exists in the current request
if (!this.optionalSignature) {
throw new Error("Need to create \"optionalSignature\" field before signing");
}
//#region Get a "default parameters" for current algorithm and set correct signature algorithm
const signatureParams = await crypto.getSignatureParameters(privateKey, hashAlgorithm);
const parameters = signatureParams.parameters;
this.optionalSignature.signatureAlgorithm = signatureParams.signatureAlgorithm;
//#endregion
//#region Create TBS data for signing
const tbs = this.tbsRequest.toSchema(true).toBER(false);
//#endregion
// Signing TBS data on provided private key
const signature = await crypto.signWithPrivateKey(tbs, privateKey, parameters as any);
this.optionalSignature.signature = new asn1js.BitString({ valueHex: signature });
}
verify() {
// TODO: Create the function
}
}

335
third_party/js/PKI.js/src/OCSPResponse.ts поставляемый
Просмотреть файл

@ -1,335 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { ResponseBytes, ResponseBytesJson, ResponseBytesSchema } from "./ResponseBytes";
import { BasicOCSPResponse } from "./BasicOCSPResponse";
import * as Schema from "./Schema";
import { Certificate } from "./Certificate";
import { id_PKIX_OCSP_Basic } from "./ObjectIdentifiers";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as common from "./common";
const RESPONSE_STATUS = "responseStatus";
const RESPONSE_BYTES = "responseBytes";
export interface IOCSPResponse {
responseStatus: asn1js.Enumerated;
responseBytes?: ResponseBytes;
}
export interface OCSPResponseJson {
responseStatus: asn1js.EnumeratedJson;
responseBytes?: ResponseBytesJson;
}
export type OCSPResponseParameters = PkiObjectParameters & Partial<IOCSPResponse>;
/**
* Represents an OCSP response described in [RFC6960 Section 4.2](https://datatracker.ietf.org/doc/html/rfc6960#section-4.2)
*
* @example The following example demonstrates how to verify OCSP response
* ```js
* const asnOcspResp = asn1js.fromBER(ocspRespRaw);
* const ocspResp = new pkijs.OCSPResponse({ schema: asnOcspResp.result });
*
* if (!ocspResp.responseBytes) {
* throw new Error("No \"ResponseBytes\" in the OCSP Response - nothing to verify");
* }
*
* const asnOcspRespBasic = asn1js.fromBER(ocspResp.responseBytes.response.valueBlock.valueHex);
* const ocspBasicResp = new pkijs.BasicOCSPResponse({ schema: asnOcspRespBasic.result });
* const ok = await ocspBasicResp.verify({ trustedCerts: [cert] });
* ```
*
* @example The following example demonstrates how to create OCSP response
* ```js
* const ocspBasicResp = new pkijs.BasicOCSPResponse();
*
* // Create specific TST info structure to sign
* ocspBasicResp.tbsResponseData.responderID = issuerCert.subject;
* ocspBasicResp.tbsResponseData.producedAt = new Date();
*
* const certID = new pkijs.CertID();
* await certID.createForCertificate(cert, {
* hashAlgorithm: "SHA-256",
* issuerCertificate: issuerCert,
* });
* const response = new pkijs.SingleResponse({
* certID,
* });
* response.certStatus = new asn1js.Primitive({
* idBlock: {
* tagClass: 3, // CONTEXT-SPECIFIC
* tagNumber: 0 // [0]
* },
* lenBlockLength: 1 // The length contains one byte 0x00
* }); // status - success
* response.thisUpdate = new Date();
*
* ocspBasicResp.tbsResponseData.responses.push(response);
*
* // Add certificates for chain OCSP response validation
* ocspBasicResp.certs = [issuerCert];
*
* await ocspBasicResp.sign(keys.privateKey, "SHA-256");
*
* // Finally create completed OCSP response structure
* const ocspBasicRespRaw = ocspBasicResp.toSchema().toBER(false);
*
* const ocspResp = new pkijs.OCSPResponse({
* responseStatus: new asn1js.Enumerated({ value: 0 }), // success
* responseBytes: new pkijs.ResponseBytes({
* responseType: pkijs.id_PKIX_OCSP_Basic,
* response: new asn1js.OctetString({ valueHex: ocspBasicRespRaw }),
* }),
* });
*
* const ocspRespRaw = ocspResp.toSchema().toBER();
* ```
*/
export class OCSPResponse extends PkiObject implements IOCSPResponse {
public static override CLASS_NAME = "OCSPResponse";
public responseStatus!: asn1js.Enumerated;
public responseBytes?: ResponseBytes;
/**
* Initializes a new instance of the {@link OCSPResponse} class
* @param parameters Initialization parameters
*/
constructor(parameters: OCSPResponseParameters = {}) {
super();
this.responseStatus = pvutils.getParametersValue(parameters, RESPONSE_STATUS, OCSPResponse.defaultValues(RESPONSE_STATUS));
if (RESPONSE_BYTES in parameters) {
this.responseBytes = pvutils.getParametersValue(parameters, RESPONSE_BYTES, OCSPResponse.defaultValues(RESPONSE_BYTES));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof RESPONSE_STATUS): asn1js.Enumerated;
public static override defaultValues(memberName: typeof RESPONSE_BYTES): ResponseBytes;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case RESPONSE_STATUS:
return new asn1js.Enumerated();
case RESPONSE_BYTES:
return new ResponseBytes();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OCSPResponse ::= SEQUENCE {
* responseStatus OCSPResponseStatus,
* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL }
*
* OCSPResponseStatus ::= ENUMERATED {
* successful (0), -- Response has valid confirmations
* malformedRequest (1), -- Illegal confirmation request
* internalError (2), -- Internal error in issuer
* tryLater (3), -- Try again later
* -- (4) is not used
* sigRequired (5), -- Must sign the request
* unauthorized (6) -- Request unauthorized
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
responseStatus?: string;
responseBytes?: ResponseBytesSchema;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || "OCSPResponse"),
value: [
new asn1js.Enumerated({ name: (names.responseStatus || RESPONSE_STATUS) }),
new asn1js.Constructed({
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [
ResponseBytes.schema(names.responseBytes || {
names: {
blockName: RESPONSE_BYTES
}
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, [
RESPONSE_STATUS,
RESPONSE_BYTES
]);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OCSPResponse.schema()
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.responseStatus = asn1.result.responseStatus;
if (RESPONSE_BYTES in asn1.result)
this.responseBytes = new ResponseBytes({ schema: asn1.result.responseBytes });
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(this.responseStatus);
if (this.responseBytes) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: [this.responseBytes.toSchema()]
}));
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): OCSPResponseJson {
const res: OCSPResponseJson = {
responseStatus: this.responseStatus.toJSON()
};
if (this.responseBytes) {
res.responseBytes = this.responseBytes.toJSON();
}
return res;
}
/**
* Get OCSP response status for specific certificate
* @param certificate
* @param issuerCertificate
* @param crypto Crypto engine
*/
public async getCertificateStatus(certificate: Certificate, issuerCertificate: Certificate, crypto = common.getCrypto(true)) {
//#region Initial variables
let basicResponse;
const result = {
isForCertificate: false,
status: 2 // 0 = good, 1 = revoked, 2 = unknown
};
//#endregion
//#region Check that RESPONSE_BYTES contain "OCSP_BASIC_RESPONSE"
if (!this.responseBytes)
return result;
if (this.responseBytes.responseType !== id_PKIX_OCSP_Basic) // id-pkix-ocsp-basic
return result;
try {
const asn1Basic = asn1js.fromBER(this.responseBytes.response.valueBlock.valueHexView);
AsnError.assert(asn1Basic, "Basic OCSP response");
basicResponse = new BasicOCSPResponse({ schema: asn1Basic.result });
}
catch (ex) {
return result;
}
//#endregion
return basicResponse.getCertificateStatus(certificate, issuerCertificate, crypto);
}
/**
* Make a signature for current OCSP Response
* @param privateKey Private key for "subjectPublicKeyInfo" structure
* @param hashAlgorithm Hashing algorithm. Default SHA-1
*/
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);
return basicResponse.sign(privateKey, hashAlgorithm, crypto);
}
throw new Error(`Unknown ResponseBytes type: ${this.responseBytes?.responseType || "Unknown"}`);
//#endregion
}
/**
* Verify current OCSP Response
* @param issuerCertificate In order to decrease size of resp issuer cert could be omitted. In such case you need manually provide it.
* @param crypto Crypto engine
*/
public async verify(issuerCertificate: Certificate | null = null, crypto = common.getCrypto(true)): Promise<boolean> {
//#region Check that ResponseBytes exists in the object
if ((RESPONSE_BYTES in this) === false)
throw new Error("Empty ResponseBytes field");
//#endregion
//#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);
if (issuerCertificate !== null) {
if (!basicResponse.certs) {
basicResponse.certs = [];
}
basicResponse.certs.push(issuerCertificate);
}
return basicResponse.verify({}, crypto);
}
throw new Error(`Unknown ResponseBytes type: ${this.responseBytes?.responseType || "Unknown"}`);
//#endregion
}
}

Просмотреть файл

@ -1,64 +0,0 @@
// Extensions
export const id_SubjectDirectoryAttributes = "2.5.29.9";
export const id_SubjectKeyIdentifier = "2.5.29.14";
export const id_KeyUsage = "2.5.29.15";
export const id_PrivateKeyUsagePeriod = "2.5.29.16";
export const id_SubjectAltName = "2.5.29.17";
export const id_IssuerAltName = "2.5.29.18";
export const id_BasicConstraints = "2.5.29.19";
export const id_CRLNumber = "2.5.29.20";
export const id_BaseCRLNumber = "2.5.29.27"; // BaseCRLNumber (delta CRL indicator)
export const id_CRLReason = "2.5.29.21";
export const id_InvalidityDate = "2.5.29.24";
export const id_IssuingDistributionPoint = "2.5.29.28";
export const id_CertificateIssuer = "2.5.29.29";
export const id_NameConstraints = "2.5.29.30";
export const id_CRLDistributionPoints = "2.5.29.31";
export const id_FreshestCRL = "2.5.29.46";
export const id_CertificatePolicies = "2.5.29.32";
export const id_AnyPolicy = "2.5.29.32.0";
export const id_MicrosoftAppPolicies = "1.3.6.1.4.1.311.21.10"; // szOID_APPLICATION_CERT_POLICIES - Microsoft-specific OID
export const id_PolicyMappings = "2.5.29.33";
export const id_AuthorityKeyIdentifier = "2.5.29.35";
export const id_PolicyConstraints = "2.5.29.36";
export const id_ExtKeyUsage = "2.5.29.37";
export const id_InhibitAnyPolicy = "2.5.29.54";
export const id_AuthorityInfoAccess = "1.3.6.1.5.5.7.1.1";
export const id_SubjectInfoAccess = "1.3.6.1.5.5.7.1.11";
export const id_SignedCertificateTimestampList = "1.3.6.1.4.1.11129.2.4.2";
export const id_MicrosoftCertTemplateV1 = "1.3.6.1.4.1.311.20.2"; // szOID_ENROLL_CERTTYPE_EXTENSION - Microsoft-specific extension
export const id_MicrosoftPrevCaCertHash = "1.3.6.1.4.1.311.21.2"; // szOID_CERTSRV_PREVIOUS_CERT_HASH - Microsoft-specific extension
export const id_MicrosoftCertTemplateV2 = "1.3.6.1.4.1.311.21.7"; // szOID_CERTIFICATE_TEMPLATE - Microsoft-specific extension
export const id_MicrosoftCaVersion = "1.3.6.1.4.1.311.21.1"; // szOID_CERTSRV_CA_VERSION - Microsoft-specific extension
export const id_QCStatements = "1.3.6.1.5.5.7.1.3";
// ContentType
export const id_ContentType_Data = "1.2.840.113549.1.7.1";
export const id_ContentType_SignedData = "1.2.840.113549.1.7.2";
export const id_ContentType_EnvelopedData = "1.2.840.113549.1.7.3";
export const id_ContentType_EncryptedData = "1.2.840.113549.1.7.6";
export const id_eContentType_TSTInfo = "1.2.840.113549.1.9.16.1.4";
// CertBag
export const id_CertBag_X509Certificate = "1.2.840.113549.1.9.22.1";
export const id_CertBag_SDSICertificate = "1.2.840.113549.1.9.22.2";
export const id_CertBag_AttributeCertificate = "1.2.840.113549.1.9.22.3";
// CRLBag
export const id_CRLBag_X509CRL = "1.2.840.113549.1.9.23.1";
export const id_pkix = "1.3.6.1.5.5.7";
export const id_ad = `${id_pkix}.48`;
export const id_PKIX_OCSP_Basic = `${id_ad}.1.1`;
export const id_ad_caIssuers = `${id_ad}.2`;
export const id_ad_ocsp = `${id_ad}.1`;
// Algorithms
export const id_sha1 = "1.3.14.3.2.26";
export const id_sha256 = "2.16.840.1.101.3.4.2.1";
export const id_sha384 = "2.16.840.1.101.3.4.2.2";
export const id_sha512 = "2.16.840.1.101.3.4.2.3";

Просмотреть файл

@ -1,209 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { IssuerAndSerialNumber } from "./IssuerAndSerialNumber";
import { OriginatorPublicKey } from "./OriginatorPublicKey";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const VARIANT = "variant";
const VALUE = "value";
const CLEAR_PROPS = [
"blockName",
];
export interface IOriginatorIdentifierOrKey {
variant: number;
value?: any;
}
export interface OriginatorIdentifierOrKeyJson {
variant: number;
value?: any;
}
export type OriginatorIdentifierOrKeyParameters = PkiObjectParameters & Partial<IOriginatorIdentifierOrKey>;
export type OriginatorIdentifierOrKeySchema = Schema.SchemaParameters;
/**
* Represents the OriginatorIdentifierOrKey structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class OriginatorIdentifierOrKey extends PkiObject implements IOriginatorIdentifierOrKey {
public static override CLASS_NAME = "OriginatorIdentifierOrKey";
public variant!: number;
public value?: any;
/**
* Initializes a new instance of the {@link OriginatorIdentifierOrKey} class
* @param parameters Initialization parameters
*/
constructor(parameters: OriginatorIdentifierOrKeyParameters = {}) {
super();
this.variant = pvutils.getParametersValue(parameters, VARIANT, OriginatorIdentifierOrKey.defaultValues(VARIANT));
if (VALUE in parameters) {
this.value = pvutils.getParametersValue(parameters, VALUE, OriginatorIdentifierOrKey.defaultValues(VALUE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VARIANT): number;
public static override defaultValues(memberName: typeof VALUE): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VARIANT:
return (-1);
case VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VARIANT:
return (memberValue === (-1));
case VALUE:
return (Object.keys(memberValue).length === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OriginatorIdentifierOrKey ::= CHOICE {
* issuerAndSerialNumber IssuerAndSerialNumber,
* subjectKeyIdentifier [0] SubjectKeyIdentifier,
* originatorKey [1] OriginatorPublicKey }
*```
*/
public static override schema(parameters: OriginatorIdentifierOrKeySchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Choice({
value: [
IssuerAndSerialNumber.schema({
names: {
blockName: (names.blockName || EMPTY_STRING)
}
}),
new asn1js.Primitive({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
name: (names.blockName || EMPTY_STRING)
}),
new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
name: (names.blockName || EMPTY_STRING),
value: OriginatorPublicKey.schema().valueBlock.value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OriginatorIdentifierOrKey.schema({
names: {
blockName: "blockName"
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
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) {
//#region Create "OCTETSTRING" from "ASN1_PRIMITIVE"
asn1.result.blockName.idBlock.tagClass = 1; // UNIVERSAL
asn1.result.blockName.idBlock.tagNumber = 4; // OCTETSTRING
//#endregion
this.variant = 2;
this.value = asn1.result.blockName;
}
else {
this.variant = 3;
this.value = new OriginatorPublicKey({
schema: new asn1js.Sequence({
value: asn1.result.blockName.valueBlock.value
})
});
}
}
//#endregion
}
public toSchema(): asn1js.BaseBlock<any> {
//#region Construct and return new ASN.1 schema for this object
switch (this.variant) {
case 1:
return this.value.toSchema();
case 2:
this.value.idBlock.tagClass = 3; // CONTEXT-SPECIFIC
this.value.idBlock.tagNumber = 0; // [0]
return this.value;
case 3:
{
const _schema = this.value.toSchema();
_schema.idBlock.tagClass = 3; // CONTEXT-SPECIFIC
_schema.idBlock.tagNumber = 1; // [1]
return _schema;
}
default:
return new asn1js.Any() as any;
}
//#endregion
}
public toJSON(): OriginatorIdentifierOrKeyJson {
const res: OriginatorIdentifierOrKeyJson = {
variant: this.variant
};
if ((this.variant === 1) || (this.variant === 2) || (this.variant === 3)) {
res.value = this.value.toJSON();
}
return res;
}
}

212
third_party/js/PKI.js/src/OriginatorInfo.ts поставляемый
Просмотреть файл

@ -1,212 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { CertificateSet, CertificateSetJson } from "./CertificateSet";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { RevocationInfoChoices, RevocationInfoChoicesJson } from "./RevocationInfoChoices";
import * as Schema from "./Schema";
const CERTS = "certs";
const CRLS = "crls";
const CLEAR_PROPS = [
CERTS,
CRLS,
];
export interface IOriginatorInfo {
/**
* Collection of certificates. In may contain originator certificates associated with several different
* key management algorithms. It may also contain attribute certificates associated with the originator.
*/
certs?: CertificateSet;
/**
* Collection of CRLs. It is intended that the set contain information sufficient to determine whether
* or not the certificates in the certs field are valid, but such correspondence is not necessary
*/
crls?: RevocationInfoChoices;
}
export interface OriginatorInfoJson {
certs?: CertificateSetJson;
crls?: RevocationInfoChoicesJson;
}
export type OriginatorInfoParameters = PkiObjectParameters & Partial<IOriginatorInfo>;
/**
* Represents the OriginatorInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class OriginatorInfo extends PkiObject implements IOriginatorInfo {
public static override CLASS_NAME = "OriginatorInfo";
public certs?: CertificateSet;
public crls?: RevocationInfoChoices;
/**
* Initializes a new instance of the {@link CertificateSet} class
* @param parameters Initialization parameters
*/
constructor(parameters: OriginatorInfoParameters = {}) {
super();
this.crls = pvutils.getParametersValue(parameters, CRLS, OriginatorInfo.defaultValues(CRLS));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof CERTS): CertificateSet;
public static override defaultValues(memberName: typeof CRLS): RevocationInfoChoices;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case CERTS:
return new CertificateSet();
case CRLS:
return new RevocationInfoChoices();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case CERTS:
return (memberValue.certificates.length === 0);
case CRLS:
return ((memberValue.crls.length === 0) && (memberValue.otherRevocationInfos.length === 0));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OriginatorInfo ::= SEQUENCE {
* certs [0] IMPLICIT CertificateSet OPTIONAL,
* crls [1] IMPLICIT RevocationInfoChoices OPTIONAL }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
certs?: string;
crls?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Constructed({
name: (names.certs || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: CertificateSet.schema().valueBlock.value
}),
new asn1js.Constructed({
name: (names.crls || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: RevocationInfoChoices.schema().valueBlock.value
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OriginatorInfo.schema({
names: {
certs: CERTS,
crls: CRLS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
if (CERTS in asn1.result) {
this.certs = new CertificateSet({
schema: new asn1js.Set({
value: asn1.result.certs.valueBlock.value
})
});
}
if (CRLS in asn1.result) {
this.crls = new RevocationInfoChoices({
schema: new asn1js.Set({
value: asn1.result.crls.valueBlock.value
})
});
}
}
public toSchema(): asn1js.Sequence {
const sequenceValue = [];
if (this.certs) {
sequenceValue.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: this.certs.toSchema().valueBlock.value
}));
}
if (this.crls) {
sequenceValue.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
},
value: this.crls.toSchema().valueBlock.value
}));
}
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: sequenceValue
}));
//#endregion
}
public toJSON(): OriginatorInfoJson {
const res: OriginatorInfoJson = {};
if (this.certs) {
res.certs = this.certs.toJSON();
}
if (this.crls) {
res.crls = this.crls.toJSON();
}
return res;
}
}

Просмотреть файл

@ -1,154 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const ALGORITHM = "algorithm";
const PUBLIC_KEY = "publicKey";
const CLEAR_PROPS = [
ALGORITHM,
PUBLIC_KEY
];
export interface IOriginatorPublicKey {
algorithm: AlgorithmIdentifier;
publicKey: asn1js.BitString;
}
export interface OriginatorPublicKeyJson {
algorithm: AlgorithmIdentifierJson;
publicKey: asn1js.BitStringJson;
}
export type OriginatorPublicKeyParameters = PkiObjectParameters & Partial<IOriginatorPublicKey>;
/**
* Represents the OriginatorPublicKey structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class OriginatorPublicKey extends PkiObject implements IOriginatorPublicKey {
public static override CLASS_NAME = "OriginatorPublicKey";
public algorithm!: AlgorithmIdentifier;
public publicKey!: asn1js.BitString;
/**
* Initializes a new instance of the {@link OriginatorPublicKey} class
* @param parameters Initialization parameters
*/
constructor(parameters: OriginatorPublicKeyParameters = {}) {
super();
this.algorithm = pvutils.getParametersValue(parameters, ALGORITHM, OriginatorPublicKey.defaultValues(ALGORITHM));
this.publicKey = pvutils.getParametersValue(parameters, PUBLIC_KEY, OriginatorPublicKey.defaultValues(PUBLIC_KEY));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof PUBLIC_KEY): asn1js.BitString;
public static override defaultValues(memberName: string): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ALGORITHM:
return new AlgorithmIdentifier();
case PUBLIC_KEY:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault<T extends { isEqual(data: any): boolean; }>(memberName: string, memberValue: T): memberValue is T {
switch (memberName) {
case ALGORITHM:
case PUBLIC_KEY:
return (memberValue.isEqual(OriginatorPublicKey.defaultValues(memberName)));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OriginatorPublicKey ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* publicKey BIT STRING }
*```
*/
static override schema(parameters: Schema.SchemaParameters<{
algorithm?: AlgorithmIdentifierSchema;
publicKey?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AlgorithmIdentifier.schema(names.algorithm || {}),
new asn1js.BitString({ name: (names.publicKey || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OriginatorPublicKey.schema({
names: {
algorithm: {
names: {
blockName: ALGORITHM
}
},
publicKey: PUBLIC_KEY
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.algorithm = new AlgorithmIdentifier({ schema: asn1.result.algorithm });
this.publicKey = asn1.result.publicKey;
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
this.algorithm.toSchema(),
this.publicKey
]
}));
//#endregion
}
public toJSON(): OriginatorPublicKeyJson {
return {
algorithm: this.algorithm.toJSON(),
publicKey: this.publicKey.toJSON(),
};
}
}

Просмотреть файл

@ -1,130 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const OTHER_CERT_FORMAT = "otherCertFormat";
const OTHER_CERT = "otherCert";
const CLEAR_PROPS = [
OTHER_CERT_FORMAT,
OTHER_CERT
];
export interface IOtherCertificateFormat {
otherCertFormat: string;
otherCert: any;
}
export interface OtherCertificateFormatJson {
otherCertFormat: string;
otherCert?: any;
}
export type OtherCertificateFormatParameters = PkiObjectParameters & Partial<IOtherCertificateFormat>;
/**
* Represents the OtherCertificateFormat structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class OtherCertificateFormat extends PkiObject implements IOtherCertificateFormat {
public otherCertFormat!: string;
public otherCert: any;
/**
* Initializes a new instance of the {@link OtherCertificateFormat} class
* @param parameters Initialization parameters
*/
constructor(parameters: OtherCertificateFormatParameters = {}) {
super();
this.otherCertFormat = pvutils.getParametersValue(parameters, OTHER_CERT_FORMAT, OtherCertificateFormat.defaultValues(OTHER_CERT_FORMAT));
this.otherCert = pvutils.getParametersValue(parameters, OTHER_CERT, OtherCertificateFormat.defaultValues(OTHER_CERT));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof OTHER_CERT_FORMAT): string;
public static override defaultValues(memberName: typeof OTHER_CERT): asn1js.Any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case OTHER_CERT_FORMAT:
return EMPTY_STRING;
case OTHER_CERT:
return new asn1js.Any();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OtherCertificateFormat ::= SEQUENCE {
* otherCertFormat OBJECT IDENTIFIER,
* otherCert ANY DEFINED BY otherCertFormat }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
otherCertFormat?: string;
otherCert?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.otherCertFormat || OTHER_CERT_FORMAT) }),
new asn1js.Any({ name: (names.otherCert || OTHER_CERT) })
]
}));
}
public fromSchema(schema: any): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OtherCertificateFormat.schema()
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.otherCertFormat = asn1.result.otherCertFormat.valueBlock.toString();
this.otherCert = asn1.result.otherCert;
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.otherCertFormat }),
this.otherCert
]
}));
}
public toJSON(): OtherCertificateFormatJson {
const res: OtherCertificateFormatJson = {
otherCertFormat: this.otherCertFormat
};
if (!(this.otherCert instanceof asn1js.Any)) {
res.otherCert = this.otherCert.toJSON();
}
return res;
}
}

168
third_party/js/PKI.js/src/OtherKeyAttribute.ts поставляемый
Просмотреть файл

@ -1,168 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const KEY_ATTR_ID = "keyAttrId";
const KEY_ATTR = "keyAttr";
const CLEAR_PROPS = [
KEY_ATTR_ID,
KEY_ATTR,
];
export interface IOtherKeyAttribute {
keyAttrId: string;
keyAttr?: any;
}
export interface OtherKeyAttributeJson {
keyAttrId: string;
keyAttr?: any;
}
export type OtherKeyAttributeParameters = PkiObjectParameters & Partial<IOtherKeyAttribute>;
export type OtherKeyAttributeSchema = Schema.SchemaType;
/**
* Represents the OtherKeyAttribute structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class OtherKeyAttribute extends PkiObject implements IOtherKeyAttribute {
public static override CLASS_NAME = "OtherKeyAttribute";
public keyAttrId!: string;
public keyAttr?: any;
/**
* Initializes a new instance of the {@link OtherKeyAttribute} class
* @param parameters Initialization parameters
*/
constructor(parameters: OtherKeyAttributeParameters = {}) {
super();
this.keyAttrId = pvutils.getParametersValue(parameters, KEY_ATTR_ID, OtherKeyAttribute.defaultValues(KEY_ATTR_ID));
if (KEY_ATTR in parameters) {
this.keyAttr = pvutils.getParametersValue(parameters, KEY_ATTR, OtherKeyAttribute.defaultValues(KEY_ATTR));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof KEY_ATTR_ID): string;
public static override defaultValues(memberName: typeof KEY_ATTR): any;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case KEY_ATTR_ID:
return EMPTY_STRING;
case KEY_ATTR:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @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 {
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OtherKeyAttribute ::= SEQUENCE {
* keyAttrId OBJECT IDENTIFIER,
* keyAttr ANY DEFINED BY keyAttrId OPTIONAL }
*```
*/
public static override schema(parameters: OtherKeyAttributeSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
optional: (names.optional || true),
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.keyAttrId || EMPTY_STRING) }),
new asn1js.Any({
optional: true,
name: (names.keyAttr || EMPTY_STRING)
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OtherKeyAttribute.schema({
names: {
keyAttrId: KEY_ATTR_ID,
keyAttr: KEY_ATTR
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.keyAttrId = asn1.result.keyAttrId.valueBlock.toString();
if (KEY_ATTR in asn1.result) {
this.keyAttr = asn1.result.keyAttr;
}
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(new asn1js.ObjectIdentifier({ value: this.keyAttrId }));
if (KEY_ATTR in this) {
outputArray.push(this.keyAttr);
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray,
}));
//#endregion
}
public toJSON(): OtherKeyAttributeJson {
const res: OtherKeyAttributeJson = {
keyAttrId: this.keyAttrId
};
if (KEY_ATTR in this) {
res.keyAttr = this.keyAttr.toJSON();
}
return res;
}
}

166
third_party/js/PKI.js/src/OtherPrimeInfo.ts поставляемый
Просмотреть файл

@ -1,166 +0,0 @@
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError, ParameterError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const PRIME = "prime";
const EXPONENT = "exponent";
const COEFFICIENT = "coefficient";
const CLEAR_PROPS = [
PRIME,
EXPONENT,
COEFFICIENT,
];
export interface IOtherPrimeInfo {
prime: asn1js.Integer;
exponent: asn1js.Integer;
coefficient: asn1js.Integer;
}
export type OtherPrimeInfoParameters = PkiObjectParameters & Partial<IOtherPrimeInfo> & { json?: OtherPrimeInfoJson; };
export interface OtherPrimeInfoJson {
r: string;
d: string;
t: string;
}
export type OtherPrimeInfoSchema = Schema.SchemaParameters<{
prime?: string;
exponent?: string;
coefficient?: string;
}>;
/**
* Represents the OtherPrimeInfo structure described in [RFC3447](https://datatracker.ietf.org/doc/html/rfc3447)
*/
export class OtherPrimeInfo extends PkiObject implements IOtherPrimeInfo {
public static override CLASS_NAME = "OtherPrimeInfo";
public prime!: asn1js.Integer;
public exponent!: asn1js.Integer;
public coefficient!: asn1js.Integer;
/**
* Initializes a new instance of the {@link OtherPrimeInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: OtherPrimeInfoParameters = {}) {
super();
this.prime = pvutils.getParametersValue(parameters, PRIME, OtherPrimeInfo.defaultValues(PRIME));
this.exponent = pvutils.getParametersValue(parameters, EXPONENT, OtherPrimeInfo.defaultValues(EXPONENT));
this.coefficient = pvutils.getParametersValue(parameters, COEFFICIENT, OtherPrimeInfo.defaultValues(COEFFICIENT));
if (parameters.json) {
this.fromJSON(parameters.json);
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof PRIME | typeof EXPONENT | typeof COEFFICIENT): asn1js.Integer;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case PRIME:
return new asn1js.Integer();
case EXPONENT:
return new asn1js.Integer();
case COEFFICIENT:
return new asn1js.Integer();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OtherPrimeInfo ::= Sequence {
* prime Integer, -- ri
* exponent Integer, -- di
* coefficient Integer -- ti
* }
*```
*/
public static override schema(parameters: OtherPrimeInfoSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.prime || EMPTY_STRING) }),
new asn1js.Integer({ name: (names.exponent || EMPTY_STRING) }),
new asn1js.Integer({ name: (names.coefficient || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OtherPrimeInfo.schema({
names: {
prime: PRIME,
exponent: EXPONENT,
coefficient: COEFFICIENT
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
this.prime = asn1.result.prime.convertFromDER();
this.exponent = asn1.result.exponent.convertFromDER();
this.coefficient = asn1.result.coefficient.convertFromDER();
//#endregion
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: [
this.prime.convertToDER(),
this.exponent.convertToDER(),
this.coefficient.convertToDER()
]
}));
}
public toJSON(): OtherPrimeInfoJson {
return {
r: pvtsutils.Convert.ToBase64Url(this.prime.valueBlock.valueHexView),
d: pvtsutils.Convert.ToBase64Url(this.exponent.valueBlock.valueHexView),
t: pvtsutils.Convert.ToBase64Url(this.coefficient.valueBlock.valueHexView),
};
}
/**
* Converts JSON value into current object
* @param json JSON object
*/
public fromJSON(json: OtherPrimeInfoJson): void {
ParameterError.assert("json", json, "r", "d", "r");
this.prime = new asn1js.Integer({ valueHex: pvtsutils.Convert.FromBase64Url(json.r) });
this.exponent = new asn1js.Integer({ valueHex: pvtsutils.Convert.FromBase64Url(json.d) });
this.coefficient = new asn1js.Integer({ valueHex: pvtsutils.Convert.FromBase64Url(json.t) });
}
}

Просмотреть файл

@ -1,154 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const ORI_TYPE = "oriType";
const ORI_VALUE = "oriValue";
const CLEAR_PROPS = [
ORI_TYPE,
ORI_VALUE
];
export interface IOtherRecipientInfo {
oriType: string;
oriValue: any;
}
export interface OtherRecipientInfoJson {
oriType: string;
oriValue?: any;
}
export type OtherRecipientInfoParameters = PkiObjectParameters & Partial<IOtherRecipientInfo>;
/**
* Represents the OtherRecipientInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class OtherRecipientInfo extends PkiObject implements IOtherRecipientInfo {
public static override CLASS_NAME = "OtherRecipientInfo";
public oriType!: string;
public oriValue: any;
/**
* Initializes a new instance of the {@link OtherRecipientInfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: OtherRecipientInfoParameters = {}) {
super();
this.oriType = pvutils.getParametersValue(parameters, ORI_TYPE, OtherRecipientInfo.defaultValues(ORI_TYPE));
this.oriValue = pvutils.getParametersValue(parameters, ORI_VALUE, OtherRecipientInfo.defaultValues(ORI_VALUE));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
static override defaultValues(memberName: typeof ORI_TYPE): string;
static override defaultValues(memberName: typeof ORI_VALUE): any;
static override defaultValues(memberName: string): any {
switch (memberName) {
case ORI_TYPE:
return EMPTY_STRING;
case ORI_VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case ORI_TYPE:
return (memberValue === EMPTY_STRING);
case ORI_VALUE:
return (Object.keys(memberValue).length === 0);
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OtherRecipientInfo ::= SEQUENCE {
* oriType OBJECT IDENTIFIER,
* oriValue ANY DEFINED BY oriType }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
oriType?: string;
oriValue?: string;
}> = {}) {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.oriType || EMPTY_STRING) }),
new asn1js.Any({ name: (names.oriValue || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OtherRecipientInfo.schema({
names: {
oriType: ORI_TYPE,
oriValue: ORI_VALUE
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.oriType = asn1.result.oriType.valueBlock.toString();
this.oriValue = asn1.result.oriValue;
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.oriType }),
this.oriValue
]
}));
//#endregion
}
public toJSON(): OtherRecipientInfoJson {
const res: OtherRecipientInfoJson = {
oriType: this.oriType
};
if (!OtherRecipientInfo.compareWithDefault(ORI_VALUE, this.oriValue)) {
res.oriValue = this.oriValue.toJSON();
}
return res;
}
}

Просмотреть файл

@ -1,132 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const OTHER_REV_INFO_FORMAT = "otherRevInfoFormat";
const OTHER_REV_INFO = "otherRevInfo";
const CLEAR_PROPS = [
OTHER_REV_INFO_FORMAT,
OTHER_REV_INFO
];
export interface IOtherRevocationInfoFormat {
otherRevInfoFormat: string;
otherRevInfo: any;
}
export interface OtherRevocationInfoFormatJson {
otherRevInfoFormat: string;
otherRevInfo?: any;
}
export type OtherRevocationInfoFormatParameters = PkiObjectParameters & Partial<IOtherRevocationInfoFormat>;
/**
* Represents the OtherRevocationInfoFormat structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
export class OtherRevocationInfoFormat extends PkiObject implements IOtherRevocationInfoFormat {
public static override CLASS_NAME = "OtherRevocationInfoFormat";
public otherRevInfoFormat!: string;
public otherRevInfo: any;
/**
* Initializes a new instance of the {@link OtherRevocationInfoFormat} class
* @param parameters Initialization parameters
*/
constructor(parameters: OtherRevocationInfoFormatParameters = {}) {
super();
this.otherRevInfoFormat = pvutils.getParametersValue(parameters, OTHER_REV_INFO_FORMAT, OtherRevocationInfoFormat.defaultValues(OTHER_REV_INFO_FORMAT));
this.otherRevInfo = pvutils.getParametersValue(parameters, OTHER_REV_INFO, OtherRevocationInfoFormat.defaultValues(OTHER_REV_INFO));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
static override defaultValues(memberName: typeof OTHER_REV_INFO_FORMAT): string;
static override defaultValues(memberName: typeof OTHER_REV_INFO): any;
static override defaultValues(memberName: string): any {
switch (memberName) {
case OTHER_REV_INFO_FORMAT:
return EMPTY_STRING;
case OTHER_REV_INFO:
return new asn1js.Any();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* OtherCertificateFormat ::= SEQUENCE {
* otherRevInfoFormat OBJECT IDENTIFIER,
* otherRevInfo ANY DEFINED BY otherCertFormat }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
otherRevInfoFormat?: string;
otherRevInfo?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.otherRevInfoFormat || OTHER_REV_INFO_FORMAT) }),
new asn1js.Any({ name: (names.otherRevInfo || OTHER_REV_INFO) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
OtherRevocationInfoFormat.schema()
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.otherRevInfoFormat = asn1.result.otherRevInfoFormat.valueBlock.toString();
this.otherRevInfo = asn1.result.otherRevInfo;
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.otherRevInfoFormat }),
this.otherRevInfo
]
}));
}
public toJSON(): OtherRevocationInfoFormatJson {
const res: OtherRevocationInfoFormatJson = {
otherRevInfoFormat: this.otherRevInfoFormat
};
if (!(this.otherRevInfo instanceof asn1js.Any)) {
res.otherRevInfo = this.otherRevInfo.toJSON();
}
return res;
}
}

141
third_party/js/PKI.js/src/PBES2Params.ts поставляемый
Просмотреть файл

@ -1,141 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const KEY_DERIVATION_FUNC = "keyDerivationFunc";
const ENCRYPTION_SCHEME = "encryptionScheme";
const CLEAR_PROPS = [
KEY_DERIVATION_FUNC,
ENCRYPTION_SCHEME
];
export interface IPBES2Params {
keyDerivationFunc: AlgorithmIdentifier;
encryptionScheme: AlgorithmIdentifier;
}
export interface PBES2ParamsJson {
keyDerivationFunc: AlgorithmIdentifierJson;
encryptionScheme: AlgorithmIdentifierJson;
}
export type PBES2ParamsParameters = PkiObjectParameters & Partial<IPBES2Params>;
/**
* Represents the PBES2Params structure described in [RFC2898](https://www.ietf.org/rfc/rfc2898.txt)
*/
export class PBES2Params extends PkiObject implements IPBES2Params {
public static override CLASS_NAME = "PBES2Params";
public keyDerivationFunc!: AlgorithmIdentifier;
public encryptionScheme!: AlgorithmIdentifier;
/**
* Initializes a new instance of the {@link PBES2Params} class
* @param parameters Initialization parameters
*/
constructor(parameters: PBES2ParamsParameters = {}) {
super();
this.keyDerivationFunc = pvutils.getParametersValue(parameters, KEY_DERIVATION_FUNC, PBES2Params.defaultValues(KEY_DERIVATION_FUNC));
this.encryptionScheme = pvutils.getParametersValue(parameters, ENCRYPTION_SCHEME, PBES2Params.defaultValues(ENCRYPTION_SCHEME));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof KEY_DERIVATION_FUNC): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ENCRYPTION_SCHEME): AlgorithmIdentifier;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case KEY_DERIVATION_FUNC:
return new AlgorithmIdentifier();
case ENCRYPTION_SCHEME:
return new AlgorithmIdentifier();
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PBES2-params ::= SEQUENCE {
* keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
* encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
keyDerivationFunc?: AlgorithmIdentifierSchema;
encryptionScheme?: AlgorithmIdentifierSchema;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AlgorithmIdentifier.schema(names.keyDerivationFunc || {}),
AlgorithmIdentifier.schema(names.encryptionScheme || {})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PBES2Params.schema({
names: {
keyDerivationFunc: {
names: {
blockName: KEY_DERIVATION_FUNC
}
},
encryptionScheme: {
names: {
blockName: ENCRYPTION_SCHEME
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.keyDerivationFunc = new AlgorithmIdentifier({ schema: asn1.result.keyDerivationFunc });
this.encryptionScheme = new AlgorithmIdentifier({ schema: asn1.result.encryptionScheme });
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
this.keyDerivationFunc.toSchema(),
this.encryptionScheme.toSchema()
]
}));
}
public toJSON(): PBES2ParamsJson {
return {
keyDerivationFunc: this.keyDerivationFunc.toJSON(),
encryptionScheme: this.encryptionScheme.toJSON()
};
}
}

223
third_party/js/PKI.js/src/PBKDF2Params.ts поставляемый
Просмотреть файл

@ -1,223 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const SALT = "salt";
const ITERATION_COUNT = "iterationCount";
const KEY_LENGTH = "keyLength";
const PRF = "prf";
const CLEAR_PROPS = [
SALT,
ITERATION_COUNT,
KEY_LENGTH,
PRF
];
export interface IPBKDF2Params {
salt: any;
iterationCount: number;
keyLength?: number;
prf?: AlgorithmIdentifier;
}
export interface PBKDF2ParamsJson {
salt: any;
iterationCount: number;
keyLength?: number;
prf?: AlgorithmIdentifierJson;
}
export type PBKDF2ParamsParameters = PkiObjectParameters & Partial<IPBKDF2Params>;
/**
* Represents the PBKDF2Params structure described in [RFC2898](https://www.ietf.org/rfc/rfc2898.txt)
*/
export class PBKDF2Params extends PkiObject implements IPBKDF2Params {
public static override CLASS_NAME = "PBKDF2Params";
public salt: any;
public iterationCount!: number;
public keyLength?: number;
public prf?: AlgorithmIdentifier;
/**
* Initializes a new instance of the {@link PBKDF2Params} class
* @param parameters Initialization parameters
*/
constructor(parameters: PBKDF2ParamsParameters = {}) {
super();
this.salt = pvutils.getParametersValue(parameters, SALT, PBKDF2Params.defaultValues(SALT));
this.iterationCount = pvutils.getParametersValue(parameters, ITERATION_COUNT, PBKDF2Params.defaultValues(ITERATION_COUNT));
if (KEY_LENGTH in parameters) {
this.keyLength = pvutils.getParametersValue(parameters, KEY_LENGTH, PBKDF2Params.defaultValues(KEY_LENGTH));
}
if (PRF in parameters) {
this.prf = pvutils.getParametersValue(parameters, PRF, PBKDF2Params.defaultValues(PRF));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof SALT): any;
public static override defaultValues(memberName: typeof ITERATION_COUNT): number;
public static override defaultValues(memberName: typeof KEY_LENGTH): number;
public static override defaultValues(memberName: typeof PRF): AlgorithmIdentifier;
public static override defaultValues(memberName: string): any {
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", // SHA-1
algorithmParams: new asn1js.Null()
});
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PBKDF2-params ::= SEQUENCE {
* salt CHOICE {
* specified OCTET STRING,
* otherSource AlgorithmIdentifier },
* iterationCount INTEGER (1..MAX),
* keyLength INTEGER (1..MAX) OPTIONAL,
* prf AlgorithmIdentifier
* DEFAULT { algorithm hMAC-SHA1, parameters NULL } }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
saltPrimitive?: string;
saltConstructed?: AlgorithmIdentifierSchema;
iterationCount?: string;
keyLength?: string;
prf?: AlgorithmIdentifierSchema;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Choice({
value: [
new asn1js.OctetString({ name: (names.saltPrimitive || EMPTY_STRING) }),
AlgorithmIdentifier.schema(names.saltConstructed || {})
]
}),
new asn1js.Integer({ name: (names.iterationCount || EMPTY_STRING) }),
new asn1js.Integer({
name: (names.keyLength || EMPTY_STRING),
optional: true
}),
AlgorithmIdentifier.schema(names.prf || {
names: {
optional: true
}
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.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);
// Get internal properties from parsed schema
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 });
}
public toSchema(): asn1js.Sequence {
//#region Create array for output sequence
const outputArray = [];
outputArray.push(this.salt);
outputArray.push(new asn1js.Integer({ value: this.iterationCount }));
if (KEY_LENGTH in this) {
if (PBKDF2Params.defaultValues(KEY_LENGTH) !== this.keyLength)
outputArray.push(new asn1js.Integer({ value: this.keyLength }));
}
if (this.prf) {
if (PBKDF2Params.defaultValues(PRF).isEqual(this.prf) === false)
outputArray.push(this.prf.toSchema());
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): PBKDF2ParamsJson {
const res: PBKDF2ParamsJson = {
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;
}
}

533
third_party/js/PKI.js/src/PFX.ts поставляемый
Просмотреть файл

@ -1,533 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import * as common from "./common";
import { ContentInfo, ContentInfoJson, ContentInfoSchema } from "./ContentInfo";
import { MacData, MacDataJson, MacDataSchema } from "./MacData";
import { DigestInfo } from "./DigestInfo";
import { AlgorithmIdentifier } from "./AlgorithmIdentifier";
import { SignedData } from "./SignedData";
import { EncapsulatedContentInfo } from "./EncapsulatedContentInfo";
import { Attribute } from "./Attribute";
import { SignerInfo } from "./SignerInfo";
import { IssuerAndSerialNumber } from "./IssuerAndSerialNumber";
import { SignedAndUnsignedAttributes } from "./SignedAndUnsignedAttributes";
import { AuthenticatedSafe } from "./AuthenticatedSafe";
import * as Schema from "./Schema";
import { Certificate } from "./Certificate";
import { ArgumentError, AsnError, ParameterError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { BufferSourceConverter } from "pvtsutils";
import { EMPTY_STRING } from "./constants";
const VERSION = "version";
const AUTH_SAFE = "authSafe";
const MAC_DATA = "macData";
const PARSED_VALUE = "parsedValue";
const CLERA_PROPS = [
VERSION,
AUTH_SAFE,
MAC_DATA
];
export interface IPFX {
version: number;
authSafe: ContentInfo;
macData?: MacData;
parsedValue?: PFXParsedValue;
}
export interface PFXJson {
version: number;
authSafe: ContentInfoJson;
macData?: MacDataJson;
}
export type PFXParameters = PkiObjectParameters & Partial<IPFX>;
export interface PFXParsedValue {
authenticatedSafe?: AuthenticatedSafe;
integrityMode?: number;
}
export type MakeInternalValuesParams =
{
// empty
}
|
{
iterations: number;
pbkdf2HashAlgorithm: Algorithm;
hmacHashAlgorithm: string;
password: ArrayBuffer;
}
|
{
signingCertificate: Certificate;
privateKey: CryptoKey;
hashAlgorithm: string;
};
/**
* Represents the PFX structure described in [RFC7292](https://datatracker.ietf.org/doc/html/rfc7292)
*/
export class PFX extends PkiObject implements IPFX {
public static override CLASS_NAME = "PFX";
public version!: number;
public authSafe!: ContentInfo;
public macData?: MacData;
public parsedValue?: PFXParsedValue;
/**
* Initializes a new instance of the {@link PFX} class
* @param parameters Initialization parameters
*/
constructor(parameters: PFXParameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, PFX.defaultValues(VERSION));
this.authSafe = pvutils.getParametersValue(parameters, AUTH_SAFE, PFX.defaultValues(AUTH_SAFE));
if (MAC_DATA in parameters) {
this.macData = pvutils.getParametersValue(parameters, MAC_DATA, PFX.defaultValues(MAC_DATA));
}
if (PARSED_VALUE in parameters) {
this.parsedValue = pvutils.getParametersValue(parameters, PARSED_VALUE, PFX.defaultValues(PARSED_VALUE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof AUTH_SAFE): ContentInfo;
public static override defaultValues(memberName: typeof MAC_DATA): MacData;
public static override defaultValues(memberName: typeof PARSED_VALUE): PFXParsedValue;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return 3;
case AUTH_SAFE:
return (new ContentInfo());
case MAC_DATA:
return (new MacData());
case PARSED_VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VERSION:
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PFX ::= SEQUENCE {
* version INTEGER {v3(3)}(v3,...),
* authSafe ContentInfo,
* macData MacData OPTIONAL
* }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
version?: string;
authSafe?: ContentInfoSchema;
macData?: MacDataSchema;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || VERSION) }),
ContentInfo.schema(names.authSafe || {
names: {
blockName: AUTH_SAFE
}
}),
MacData.schema(names.macData || {
names: {
blockName: MAC_DATA,
optional: true
}
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLERA_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PFX.schema({
names: {
version: VERSION,
authSafe: {
names: {
blockName: AUTH_SAFE
}
},
macData: {
names: {
blockName: MAC_DATA
}
}
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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 });
}
public toSchema(): asn1js.Sequence {
//#region Construct and return new ASN.1 schema for this object
const outputArray = [
new asn1js.Integer({ value: this.version }),
this.authSafe.toSchema()
];
if (this.macData) {
outputArray.push(this.macData.toSchema());
}
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): PFXJson {
const output: PFXJson = {
version: this.version,
authSafe: this.authSafe.toJSON()
};
if (this.macData) {
output.macData = this.macData.toJSON();
}
return output;
}
/**
* Making ContentInfo from PARSED_VALUE object
* @param parameters Parameters, specific to each "integrity mode"
* @param crypto Crypto engine
*/
public async makeInternalValues(parameters: MakeInternalValuesParams = {}, crypto = common.getCrypto(true)) {
//#region Check mandatory parameter
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");
//#endregion
//#region Makes values for each particular integrity mode
switch (this.parsedValue.integrityMode) {
//#region HMAC-based integrity
case 0:
{
//#region Check additional mandatory parameters
if (!("iterations" in parameters))
throw new ParameterError("iterations");
ParameterError.assertEmpty(parameters.pbkdf2HashAlgorithm, "pbkdf2HashAlgorithm");
ParameterError.assertEmpty(parameters.hmacHashAlgorithm, "hmacHashAlgorithm");
ParameterError.assertEmpty(parameters.password, "password");
//#endregion
//#region Initial variables
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 asn1js.OctetString({ valueHex: data })
});
//#endregion
//#region Call current crypto engine for making HMAC-based data stamp
const result = await crypto.stampDataWithPassword({
password: parameters.password,
hashAlgorithm: parameters.hmacHashAlgorithm,
salt: saltBuffer,
iterationCount: parameters.iterations,
contentToStamp: data
});
//#endregion
//#region Make MAC_DATA values
this.macData = new MacData({
mac: new DigestInfo({
digestAlgorithm: new AlgorithmIdentifier({
algorithmId: crypto.getOIDByAlgorithm({ name: parameters.hmacHashAlgorithm }, true, "hmacHashAlgorithm"),
}),
digest: new asn1js.OctetString({ valueHex: result })
}),
macSalt: new asn1js.OctetString({ valueHex: saltBuffer }),
iterations: parameters.iterations
});
//#endregion
//#endregion
}
break;
//#endregion
//#region publicKey-based integrity
case 1:
{
//#region Check additional mandatory parameters
if (!("signingCertificate" in parameters)) {
throw new ParameterError("signingCertificate");
}
ParameterError.assertEmpty(parameters.privateKey, "privateKey");
ParameterError.assertEmpty(parameters.hashAlgorithm, "hashAlgorithm");
//#endregion
//#region Making data to be signed
// NOTE: all internal data for "authenticatedSafe" must be already prepared.
// Thus user must call "makeValues" for all internal "SafeContent" value with appropriate parameters.
// Or user can choose to use values from initial parsing of existing PKCS#12 data.
const toBeSigned = this.parsedValue.authenticatedSafe.toSchema().toBER(false);
//#endregion
//#region Initial variables
const cmsSigned = new SignedData({
version: 1,
encapContentInfo: new EncapsulatedContentInfo({
eContentType: "1.2.840.113549.1.7.1", // "data" content type
eContent: new asn1js.OctetString({ valueHex: toBeSigned })
}),
certificates: [parameters.signingCertificate]
});
//#endregion
//#region Making additional attributes for CMS Signed Data
//#region Create a message digest
const result = await crypto.digest({ name: parameters.hashAlgorithm }, new Uint8Array(toBeSigned));
//#endregion
//#region Combine all signed extensions
//#region Initial variables
const signedAttr: Attribute[] = [];
//#endregion
//#region contentType
signedAttr.push(new Attribute({
type: "1.2.840.113549.1.9.3",
values: [
new asn1js.ObjectIdentifier({ value: "1.2.840.113549.1.7.1" })
]
}));
//#endregion
//#region signingTime
signedAttr.push(new Attribute({
type: "1.2.840.113549.1.9.5",
values: [
new asn1js.UTCTime({ valueDate: new Date() })
]
}));
//#endregion
//#region messageDigest
signedAttr.push(new Attribute({
type: "1.2.840.113549.1.9.4",
values: [
new asn1js.OctetString({ valueHex: result })
]
}));
//#endregion
//#region Making final value for "SignerInfo" type
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
})
}));
//#endregion
//#endregion
//#endregion
//#region Signing CMS Signed Data
await cmsSigned.sign(parameters.privateKey, 0, parameters.hashAlgorithm, undefined, crypto);
//#endregion
//#region Making final CMS_CONTENT_INFO type
this.authSafe = new ContentInfo({
contentType: "1.2.840.113549.1.7.2",
content: cmsSigned.toSchema(true)
});
//#endregion
}
break;
//#endregion
//#region default
default:
throw new Error(`Parameter "integrityMode" has unknown value: ${this.parsedValue.integrityMode}`);
//#endregion
}
//#endregion
}
public async parseInternalValues(parameters: {
checkIntegrity?: boolean;
password?: ArrayBuffer;
}, crypto = common.getCrypto(true)) {
//#region Check input data from "parameters"
ArgumentError.assert(parameters, "parameters", "object");
if (parameters.checkIntegrity === undefined) {
parameters.checkIntegrity = true;
}
//#endregion
//#region Create value for "this.parsedValue.authenticatedSafe" and check integrity
this.parsedValue = {};
switch (this.authSafe.contentType) {
//#region data
case ContentInfo.DATA:
{
//#region Check additional mandatory parameters
ParameterError.assertEmpty(parameters.password, "password");
//#endregion
//#region Integrity based on HMAC
this.parsedValue.integrityMode = 0;
//#endregion
//#region Check that we do have OCTETSTRING as "content"
ArgumentError.assert(this.authSafe.content, "authSafe.content", asn1js.OctetString);
//#endregion
//#region Check we have "constructive encoding" for AuthSafe content
const authSafeContent = this.authSafe.content.getValue();
//#endregion
//#region Set "authenticatedSafe" value
this.parsedValue.authenticatedSafe = AuthenticatedSafe.fromBER(authSafeContent);
//#endregion
//#region Check integrity
if (parameters.checkIntegrity) {
//#region Check that MAC_DATA exists
if (!this.macData) {
throw new Error("Absent \"macData\" value, can not check PKCS#12 data integrity");
}
//#endregion
//#region Initial variables
const hashAlgorithm = crypto.getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId, true, "digestAlgorithm");
//#endregion
//#region Call current crypto engine for verifying HMAC-based data stamp
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),
});
//#endregion
//#region Verify HMAC signature
if (!result) {
throw new Error("Integrity for the PKCS#12 data is broken!");
}
//#endregion
}
//#endregion
}
break;
//#endregion
//#region signedData
case ContentInfo.SIGNED_DATA:
{
//#region Integrity based on signature using public key
this.parsedValue.integrityMode = 1;
//#endregion
//#region Parse CMS Signed Data
const cmsSigned = new SignedData({ schema: this.authSafe.content });
//#endregion
//#region Check that we do have OCTET STRING as "content"
const eContent = cmsSigned.encapContentInfo.eContent;
ParameterError.assert(eContent, "eContent", "cmsSigned.encapContentInfo");
ArgumentError.assert(eContent, "eContent", asn1js.OctetString);
//#endregion
//#region Create correct data block for verification
const data = eContent.getValue();
//#endregion
//#region Set "authenticatedSafe" value
this.parsedValue.authenticatedSafe = AuthenticatedSafe.fromBER(data);
//#endregion
//#region Check integrity
const ok = await cmsSigned.verify({ signer: 0, checkChain: false }, crypto);
if (!ok) {
throw new Error("Integrity for the PKCS#12 data is broken!");
}
//#endregion
}
break;
//#endregion
//#region default
default:
throw new Error(`Incorrect value for "this.authSafe.contentType": ${this.authSafe.contentType}`);
//#endregion
}
//#endregion
}
}

Просмотреть файл

@ -1,248 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EncryptedData, EncryptedDataEncryptParams } from "./EncryptedData";
import { EncryptedContentInfo } from "./EncryptedContentInfo";
import { PrivateKeyInfo } from "./PrivateKeyInfo";
import * as Schema from "./Schema";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { EMPTY_STRING } from "./constants";
import * as common from "./common";
const ENCRYPTION_ALGORITHM = "encryptionAlgorithm";
const ENCRYPTED_DATA = "encryptedData";
const PARSED_VALUE = "parsedValue";
const CLEAR_PROPS = [
ENCRYPTION_ALGORITHM,
ENCRYPTED_DATA,
];
export interface IPKCS8ShroudedKeyBag {
encryptionAlgorithm: AlgorithmIdentifier;
encryptedData: asn1js.OctetString;
parsedValue?: PrivateKeyInfo;
}
export type PKCS8ShroudedKeyBagParameters = PkiObjectParameters & Partial<IPKCS8ShroudedKeyBag>;
export interface PKCS8ShroudedKeyBagJson {
encryptionAlgorithm: AlgorithmIdentifierJson;
encryptedData: asn1js.OctetStringJson;
}
type PKCS8ShroudedKeyBagMakeInternalValuesParams = Omit<EncryptedDataEncryptParams, "contentToEncrypt">;
/**
* Represents the PKCS8ShroudedKeyBag structure described in [RFC7292](https://datatracker.ietf.org/doc/html/rfc7292)
*/
export class PKCS8ShroudedKeyBag extends PkiObject implements IPKCS8ShroudedKeyBag {
public static override CLASS_NAME = "PKCS8ShroudedKeyBag";
public encryptionAlgorithm!: AlgorithmIdentifier;
public encryptedData!: asn1js.OctetString;
public parsedValue?: PrivateKeyInfo;
/**
* Initializes a new instance of the {@link PKCS8ShroudedKeyBag} class
* @param parameters Initialization parameters
*/
constructor(parameters: PKCS8ShroudedKeyBagParameters = {}) {
super();
this.encryptionAlgorithm = pvutils.getParametersValue(parameters, ENCRYPTION_ALGORITHM, PKCS8ShroudedKeyBag.defaultValues(ENCRYPTION_ALGORITHM));
this.encryptedData = pvutils.getParametersValue(parameters, ENCRYPTED_DATA, PKCS8ShroudedKeyBag.defaultValues(ENCRYPTED_DATA));
if (PARSED_VALUE in parameters) {
this.parsedValue = pvutils.getParametersValue(parameters, PARSED_VALUE, PKCS8ShroudedKeyBag.defaultValues(PARSED_VALUE));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ENCRYPTION_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ENCRYPTED_DATA): asn1js.OctetString;
public static override defaultValues(memberName: typeof PARSED_VALUE): PrivateKeyInfo;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ENCRYPTION_ALGORITHM:
return (new AlgorithmIdentifier());
case ENCRYPTED_DATA:
return (new asn1js.OctetString());
case PARSED_VALUE:
return {};
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
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:
return ((memberValue instanceof Object) && (Object.keys(memberValue).length === 0));
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PKCS8ShroudedKeyBag ::= EncryptedPrivateKeyInfo
*
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm AlgorithmIdentifier {{KeyEncryptionAlgorithms}},
* encryptedData EncryptedData
* }
*
* EncryptedData ::= OCTET STRING
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
encryptionAlgorithm?: AlgorithmIdentifierSchema;
encryptedData?: string;
}> = {}): Schema.SchemaType {
/**
* @type {Object}
* @property {string} [blockName]
* @property {string} [encryptionAlgorithm]
* @property {string} [encryptedData]
*/
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
AlgorithmIdentifier.schema(names.encryptionAlgorithm || {
names: {
blockName: ENCRYPTION_ALGORITHM
}
}),
new asn1js.Choice({
value: [
new asn1js.OctetString({ name: (names.encryptedData || ENCRYPTED_DATA) }),
new asn1js.OctetString({
idBlock: {
isConstructed: true
},
name: (names.encryptedData || ENCRYPTED_DATA)
})
]
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PKCS8ShroudedKeyBag.schema({
names: {
encryptionAlgorithm: {
names: {
blockName: ENCRYPTION_ALGORITHM
}
},
encryptedData: ENCRYPTED_DATA
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.encryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.encryptionAlgorithm });
this.encryptedData = asn1.result.encryptedData;
}
public toSchema(): asn1js.Sequence {
return (new asn1js.Sequence({
value: [
this.encryptionAlgorithm.toSchema(),
this.encryptedData
]
}));
}
public toJSON(): PKCS8ShroudedKeyBagJson {
return {
encryptionAlgorithm: this.encryptionAlgorithm.toJSON(),
encryptedData: this.encryptedData.toJSON(),
};
}
protected async parseInternalValues(parameters: {
password: ArrayBuffer;
}, crypto = common.getCrypto(true)) {
//#region Initial variables
const cmsEncrypted = new EncryptedData({
encryptedContentInfo: new EncryptedContentInfo({
contentEncryptionAlgorithm: this.encryptionAlgorithm,
encryptedContent: this.encryptedData
})
});
//#endregion
//#region Decrypt internal data
const decryptedData = await cmsEncrypted.decrypt(parameters, crypto);
//#endregion
//#region Initialize PARSED_VALUE with decrypted PKCS#8 private key
this.parsedValue = PrivateKeyInfo.fromBER(decryptedData);
//#endregion
}
public async makeInternalValues(parameters: PKCS8ShroudedKeyBagMakeInternalValuesParams): Promise<void> {
//#region Check that we do have PARSED_VALUE
if (!this.parsedValue) {
throw new Error("Please initialize \"parsedValue\" first");
}
//#endregion
//#region Initial variables
const cmsEncrypted = new EncryptedData();
//#endregion
//#region Encrypt internal data
const encryptParams: EncryptedDataEncryptParams = {
...parameters,
contentToEncrypt: this.parsedValue.toSchema().toBER(false),
};
await cmsEncrypted.encrypt(encryptParams);
if (!cmsEncrypted.encryptedContentInfo.encryptedContent) {
throw new Error("The filed `encryptedContent` in EncryptedContentInfo is empty");
}
//#endregion
//#region Initialize internal values
this.encryptionAlgorithm = cmsEncrypted.encryptedContentInfo.contentEncryptionAlgorithm;
this.encryptedData = cmsEncrypted.encryptedContentInfo.encryptedContent;
//#endregion
}
}

224
third_party/js/PKI.js/src/PKIStatusInfo.ts поставляемый
Просмотреть файл

@ -1,224 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const STATUS = "status";
const STATUS_STRINGS = "statusStrings";
const FAIL_INFO = "failInfo";
const CLEAR_PROPS = [
STATUS,
STATUS_STRINGS,
FAIL_INFO
];
export interface IPKIStatusInfo {
status: PKIStatus;
statusStrings?: asn1js.Utf8String[];
failInfo?: asn1js.BitString;
}
export interface PKIStatusInfoJson {
status: PKIStatus;
statusStrings?: asn1js.Utf8StringJson[];
failInfo?: asn1js.BitStringJson;
}
export type PKIStatusInfoParameters = PkiObjectParameters & Partial<IPKIStatusInfo>;
export type PKIStatusInfoSchema = Schema.SchemaParameters<{
status?: string;
statusStrings?: string;
failInfo?: string;
}>;
export enum PKIStatus {
granted = 0,
grantedWithMods = 1,
rejection = 2,
waiting = 3,
revocationWarning = 4,
revocationNotification = 5,
}
/**
* Represents the PKIStatusInfo structure described in [RFC3161](https://www.ietf.org/rfc/rfc3161.txt)
*/
export class PKIStatusInfo extends PkiObject implements IPKIStatusInfo {
public static override CLASS_NAME = "PKIStatusInfo";
public status!: PKIStatus;
public statusStrings?: asn1js.Utf8String[];
public failInfo?: asn1js.BitString;
/**
* Initializes a new instance of the {@link PBKDF2Params} class
* @param parameters Initialization parameters
*/
constructor(parameters: PKIStatusInfoParameters = {}) {
super();
this.status = pvutils.getParametersValue(parameters, STATUS, PKIStatusInfo.defaultValues(STATUS));
if (STATUS_STRINGS in parameters) {
this.statusStrings = pvutils.getParametersValue(parameters, STATUS_STRINGS, PKIStatusInfo.defaultValues(STATUS_STRINGS));
}
if (FAIL_INFO in parameters) {
this.failInfo = pvutils.getParametersValue(parameters, FAIL_INFO, PKIStatusInfo.defaultValues(FAIL_INFO));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof STATUS): number;
public static override defaultValues(memberName: typeof STATUS_STRINGS): asn1js.Utf8String[];
public static override defaultValues(memberName: typeof FAIL_INFO): asn1js.BitString;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case STATUS:
return 2;
case STATUS_STRINGS:
return [];
case FAIL_INFO:
return new asn1js.BitString();
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case STATUS:
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PKIStatusInfo ::= SEQUENCE {
* status PKIStatus,
* statusString PKIFreeText OPTIONAL,
* failInfo PKIFailureInfo OPTIONAL }
*```
*/
public static override schema(parameters: PKIStatusInfoSchema = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.status || EMPTY_STRING) }),
new asn1js.Sequence({
optional: true,
value: [
new asn1js.Repeated({
name: (names.statusStrings || EMPTY_STRING),
value: new asn1js.Utf8String()
})
]
}),
new asn1js.BitString({
name: (names.failInfo || EMPTY_STRING),
optional: true
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PKIStatusInfo.schema({
names: {
status: STATUS,
statusStrings: STATUS_STRINGS,
failInfo: FAIL_INFO
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
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;
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Create array of output sequence
const outputArray = [];
outputArray.push(new asn1js.Integer({ value: this.status }));
if (this.statusStrings) {
outputArray.push(new asn1js.Sequence({
optional: true,
value: this.statusStrings
}));
}
if (this.failInfo) {
outputArray.push(this.failInfo);
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): PKIStatusInfoJson {
const res: PKIStatusInfoJson = {
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;
}
}

Просмотреть файл

@ -1,235 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { AlgorithmIdentifier, AlgorithmIdentifierJson, AlgorithmIdentifierSchema } from "./AlgorithmIdentifier";
import { EMPTY_BUFFER, EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const VERSION = "version";
const KEY_DERIVATION_ALGORITHM = "keyDerivationAlgorithm";
const KEY_ENCRYPTION_ALGORITHM = "keyEncryptionAlgorithm";
const ENCRYPTED_KEY = "encryptedKey";
const PASSWORD = "password";
const CLEAR_PROPS = [
VERSION,
KEY_DERIVATION_ALGORITHM,
KEY_ENCRYPTION_ALGORITHM,
ENCRYPTED_KEY
];
export interface IPasswordRecipientInfo {
version: number;
keyDerivationAlgorithm?: AlgorithmIdentifier;
keyEncryptionAlgorithm: AlgorithmIdentifier;
encryptedKey: asn1js.OctetString;
password: ArrayBuffer;
}
export interface PasswordRecipientInfoJson {
version: number;
keyDerivationAlgorithm?: AlgorithmIdentifierJson;
keyEncryptionAlgorithm: AlgorithmIdentifierJson;
encryptedKey: asn1js.OctetStringJson;
}
export type PasswordRecipientinfoParameters = PkiObjectParameters & Partial<IPasswordRecipientInfo>;
/**
* Represents the PasswordRecipientInfo structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
*/
// TODO rename to PasswordRecipientInfo
export class PasswordRecipientinfo extends PkiObject implements IPasswordRecipientInfo {
public static override CLASS_NAME = "PasswordRecipientInfo";
public version!: number;
public keyDerivationAlgorithm?: AlgorithmIdentifier;
public keyEncryptionAlgorithm!: AlgorithmIdentifier;
public encryptedKey!: asn1js.OctetString;
public password!: ArrayBuffer;
/**
* Initializes a new instance of the {@link PasswordRecipientinfo} class
* @param parameters Initialization parameters
*/
constructor(parameters: PasswordRecipientinfoParameters = {}) {
super();
this.version = pvutils.getParametersValue(parameters, VERSION, PasswordRecipientinfo.defaultValues(VERSION));
if (KEY_DERIVATION_ALGORITHM in parameters) {
this.keyDerivationAlgorithm = pvutils.getParametersValue(parameters, KEY_DERIVATION_ALGORITHM, PasswordRecipientinfo.defaultValues(KEY_DERIVATION_ALGORITHM));
}
this.keyEncryptionAlgorithm = pvutils.getParametersValue(parameters, KEY_ENCRYPTION_ALGORITHM, PasswordRecipientinfo.defaultValues(KEY_ENCRYPTION_ALGORITHM));
this.encryptedKey = pvutils.getParametersValue(parameters, ENCRYPTED_KEY, PasswordRecipientinfo.defaultValues(ENCRYPTED_KEY));
this.password = pvutils.getParametersValue(parameters, PASSWORD, PasswordRecipientinfo.defaultValues(PASSWORD));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof VERSION): number;
public static override defaultValues(memberName: typeof KEY_DERIVATION_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof KEY_ENCRYPTION_ALGORITHM): AlgorithmIdentifier;
public static override defaultValues(memberName: typeof ENCRYPTED_KEY): asn1js.OctetString;
public static override defaultValues(memberName: typeof PASSWORD): ArrayBuffer;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case VERSION:
return (-1);
case KEY_DERIVATION_ALGORITHM:
return new AlgorithmIdentifier();
case KEY_ENCRYPTION_ALGORITHM:
return new AlgorithmIdentifier();
case ENCRYPTED_KEY:
return new asn1js.OctetString();
case PASSWORD:
return EMPTY_BUFFER;
default:
return super.defaultValues(memberName);
}
}
/**
* Compare values with default values for all class members
* @param memberName String name for a class member
* @param memberValue Value to compare with default value
*/
public static compareWithDefault(memberName: string, memberValue: any): boolean {
switch (memberName) {
case VERSION:
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);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PasswordRecipientInfo ::= SEQUENCE {
* version CMSVersion, -- Always set to 0
* keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier OPTIONAL,
* keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
* encryptedKey EncryptedKey }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
version?: string;
keyDerivationAlgorithm?: string;
keyEncryptionAlgorithm?: AlgorithmIdentifierSchema;
encryptedKey?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Integer({ name: (names.version || EMPTY_STRING) }),
new asn1js.Constructed({
name: (names.keyDerivationAlgorithm || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: AlgorithmIdentifier.schema().valueBlock.value
}),
AlgorithmIdentifier.schema(names.keyEncryptionAlgorithm || {}),
new asn1js.OctetString({ name: (names.encryptedKey || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PasswordRecipientinfo.schema({
names: {
version: VERSION,
keyDerivationAlgorithm: KEY_DERIVATION_ALGORITHM,
keyEncryptionAlgorithm: {
names: {
blockName: KEY_ENCRYPTION_ALGORITHM
}
},
encryptedKey: ENCRYPTED_KEY
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.version = asn1.result.version.valueBlock.valueDec;
if (KEY_DERIVATION_ALGORITHM in asn1.result) {
this.keyDerivationAlgorithm = new AlgorithmIdentifier({
schema: new asn1js.Sequence({
value: asn1.result.keyDerivationAlgorithm.valueBlock.value
})
});
}
this.keyEncryptionAlgorithm = new AlgorithmIdentifier({ schema: asn1.result.keyEncryptionAlgorithm });
this.encryptedKey = asn1.result.encryptedKey;
}
public toSchema(): asn1js.Sequence {
//#region Create output array for sequence
const outputArray = [];
outputArray.push(new asn1js.Integer({ value: this.version }));
if (this.keyDerivationAlgorithm) {
outputArray.push(new asn1js.Constructed({
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
},
value: this.keyDerivationAlgorithm.toSchema().valueBlock.value
}));
}
outputArray.push(this.keyEncryptionAlgorithm.toSchema());
outputArray.push(this.encryptedKey);
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): PasswordRecipientInfoJson {
const res: PasswordRecipientInfoJson = {
version: this.version,
keyEncryptionAlgorithm: this.keyEncryptionAlgorithm.toJSON(),
encryptedKey: this.encryptedKey.toJSON(),
};
if (this.keyDerivationAlgorithm) {
res.keyDerivationAlgorithm = this.keyDerivationAlgorithm.toJSON();
}
return res;
}
}

100
third_party/js/PKI.js/src/PkiObject.ts поставляемый
Просмотреть файл

@ -1,100 +0,0 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import { AsnError } from "./errors";
import * as Schema from "./Schema";
export interface PkiObjectParameters {
schema?: Schema.SchemaType;
}
interface PkiObjectConstructor<T extends PkiObject = PkiObject> {
new(params: PkiObjectParameters): T;
CLASS_NAME: string;
}
export abstract class PkiObject {
/**
* Name of the class
*/
public static CLASS_NAME = "PkiObject";
/**
* Returns block name
* @returns Returns string block name
*/
public static blockName(): string {
return this.CLASS_NAME;
}
/**
* Creates PKI object from the raw data
* @param raw ASN.1 encoded raw data
* @returns Initialized and filled current class object
*/
public static fromBER<T extends PkiObject>(this: PkiObjectConstructor<T>, raw: BufferSource): T {
const asn1 = asn1js.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`);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static defaultValues(memberName: string): any {
throw new Error(`Invalid member name for ${this.CLASS_NAME} class: ${memberName}`);
}
/**
* Returns value of pre-defined ASN.1 schema for current class
* @param parameters Input parameters for the schema
* @returns ASN.1 schema object
*/
public static schema(parameters: Schema.SchemaParameters = {}): Schema.SchemaType {
throw new Error(`Method '${this.CLASS_NAME}.schema' should be overridden`);
}
public get className(): string {
return (this.constructor as unknown as { CLASS_NAME: string; }).CLASS_NAME;
}
/**
* Converts parsed ASN.1 object into current class
* @param schema ASN.1 schema
*/
public abstract fromSchema(schema: Schema.SchemaType): void;
/**
* Converts current object to ASN.1 object and sets correct values
* @param encodeFlag If param equal to `false` then creates schema via decoding stored value. In other case creates schema via assembling from cached parts
* @returns ASN.1 object
*/
public abstract toSchema(encodeFlag?: boolean): Schema.SchemaType;
/**
* Converts the class to JSON object
* @returns JSON object
*/
public abstract toJSON(): any;
public toString(encoding: "hex" | "base64" | "base64url" = "hex"): string {
let schema: Schema.SchemaType;
try {
schema = this.toSchema();
} catch {
schema = this.toSchema(true);
}
return pvtsutils.Convert.ToString(schema.toBER(), encoding);
}
}

203
third_party/js/PKI.js/src/PolicyConstraints.ts поставляемый
Просмотреть файл

@ -1,203 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const REQUIRE_EXPLICIT_POLICY = "requireExplicitPolicy";
const INHIBIT_POLICY_MAPPING = "inhibitPolicyMapping";
const CLEAR_PROPS = [
REQUIRE_EXPLICIT_POLICY,
INHIBIT_POLICY_MAPPING,
];
export interface IPolicyConstraints {
requireExplicitPolicy?: number;
inhibitPolicyMapping?: number;
}
export interface PolicyConstraintsJson {
requireExplicitPolicy?: number;
inhibitPolicyMapping?: number;
}
export type PolicyConstraintsParameters = PkiObjectParameters & Partial<IPolicyConstraints>;
/**
* Represents the PolicyConstraints structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class PolicyConstraints extends PkiObject implements IPolicyConstraints {
public static override CLASS_NAME = "PolicyConstraints";
public requireExplicitPolicy?: number;
public inhibitPolicyMapping?: number;
/**
* Initializes a new instance of the {@link PolicyConstraints} class
* @param parameters Initialization parameters
*/
constructor(parameters: PolicyConstraintsParameters = {}) {
super();
if (REQUIRE_EXPLICIT_POLICY in parameters) {
this.requireExplicitPolicy = pvutils.getParametersValue(parameters, REQUIRE_EXPLICIT_POLICY, PolicyConstraints.defaultValues(REQUIRE_EXPLICIT_POLICY));
}
if (INHIBIT_POLICY_MAPPING in parameters) {
this.inhibitPolicyMapping = pvutils.getParametersValue(parameters, INHIBIT_POLICY_MAPPING, PolicyConstraints.defaultValues(INHIBIT_POLICY_MAPPING));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof REQUIRE_EXPLICIT_POLICY): number;
public static override defaultValues(memberName: typeof INHIBIT_POLICY_MAPPING): number;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case REQUIRE_EXPLICIT_POLICY:
return 0;
case INHIBIT_POLICY_MAPPING:
return 0;
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PolicyConstraints ::= SEQUENCE {
* requireExplicitPolicy [0] SkipCerts OPTIONAL,
* inhibitPolicyMapping [1] SkipCerts OPTIONAL }
*
* SkipCerts ::= INTEGER (0..MAX)
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
requireExplicitPolicy?: string;
inhibitPolicyMapping?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Primitive({
name: (names.requireExplicitPolicy || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 0 // [0]
}
}), // IMPLICIT integer value
new asn1js.Primitive({
name: (names.inhibitPolicyMapping || EMPTY_STRING),
optional: true,
idBlock: {
tagClass: 3, // CONTEXT-SPECIFIC
tagNumber: 1 // [1]
}
}) // IMPLICIT integer value
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PolicyConstraints.schema({
names: {
requireExplicitPolicy: REQUIRE_EXPLICIT_POLICY,
inhibitPolicyMapping: INHIBIT_POLICY_MAPPING
}
})
);
AsnError.assertSchema(asn1, this.className);
//#region Get internal properties from parsed schema
if (REQUIRE_EXPLICIT_POLICY in asn1.result) {
const field1 = asn1.result.requireExplicitPolicy;
field1.idBlock.tagClass = 1; // UNIVERSAL
field1.idBlock.tagNumber = 2; // INTEGER
const ber1 = field1.toBER(false);
const int1 = asn1js.fromBER(ber1);
AsnError.assert(int1, "Integer");
this.requireExplicitPolicy = (int1.result as asn1js.Integer).valueBlock.valueDec;
}
if (INHIBIT_POLICY_MAPPING in asn1.result) {
const field2 = asn1.result.inhibitPolicyMapping;
field2.idBlock.tagClass = 1; // UNIVERSAL
field2.idBlock.tagNumber = 2; // INTEGER
const ber2 = field2.toBER(false);
const int2 = asn1js.fromBER(ber2);
AsnError.assert(int2, "Integer");
this.inhibitPolicyMapping = (int2.result as asn1js.Integer).valueBlock.valueDec;
}
//#endregion
}
public toSchema(): asn1js.Sequence {
//#region Create correct values for output sequence
const outputArray = [];
if (REQUIRE_EXPLICIT_POLICY in this) {
const int1 = new asn1js.Integer({ value: this.requireExplicitPolicy });
int1.idBlock.tagClass = 3; // CONTEXT-SPECIFIC
int1.idBlock.tagNumber = 0; // [0]
outputArray.push(int1);
}
if (INHIBIT_POLICY_MAPPING in this) {
const int2 = new asn1js.Integer({ value: this.inhibitPolicyMapping });
int2.idBlock.tagClass = 3; // CONTEXT-SPECIFIC
int2.idBlock.tagNumber = 1; // [1]
outputArray.push(int2);
}
//#endregion
//#region Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
//#endregion
}
public toJSON(): PolicyConstraintsJson {
const res: PolicyConstraintsJson = {};
if (REQUIRE_EXPLICIT_POLICY in this) {
res.requireExplicitPolicy = this.requireExplicitPolicy;
}
if (INHIBIT_POLICY_MAPPING in this) {
res.inhibitPolicyMapping = this.inhibitPolicyMapping;
}
return res;
}
}

160
third_party/js/PKI.js/src/PolicyInformation.ts поставляемый
Просмотреть файл

@ -1,160 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { PolicyQualifierInfo, PolicyQualifierInfoJson } from "./PolicyQualifierInfo";
import * as Schema from "./Schema";
export const POLICY_IDENTIFIER = "policyIdentifier";
export const POLICY_QUALIFIERS = "policyQualifiers";
const CLEAR_PROPS = [
POLICY_IDENTIFIER,
POLICY_QUALIFIERS
];
export interface IPolicyInformation {
policyIdentifier: string;
policyQualifiers?: PolicyQualifierInfo[];
}
export type PolicyInformationParameters = PkiObjectParameters & Partial<IPolicyInformation>;
export interface PolicyInformationJson {
policyIdentifier: string;
policyQualifiers?: PolicyQualifierInfoJson[];
}
/**
* Represents the PolicyInformation structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class PolicyInformation extends PkiObject implements IPolicyInformation {
public static override CLASS_NAME = "PolicyInformation";
public policyIdentifier!: string;
public policyQualifiers?: PolicyQualifierInfo[];
/**
* Initializes a new instance of the {@link PolicyInformation} class
* @param parameters Initialization parameters
*/
constructor(parameters: PolicyInformationParameters = {}) {
super();
this.policyIdentifier = pvutils.getParametersValue(parameters, POLICY_IDENTIFIER, PolicyInformation.defaultValues(POLICY_IDENTIFIER));
if (POLICY_QUALIFIERS in parameters) {
this.policyQualifiers = pvutils.getParametersValue(parameters, POLICY_QUALIFIERS, PolicyInformation.defaultValues(POLICY_QUALIFIERS));
}
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof POLICY_IDENTIFIER): string;
public static override defaultValues(memberName: typeof POLICY_QUALIFIERS): PolicyQualifierInfo[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case POLICY_IDENTIFIER:
return EMPTY_STRING;
case POLICY_QUALIFIERS:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PolicyInformation ::= SEQUENCE {
* policyIdentifier CertPolicyId,
* policyQualifiers SEQUENCE SIZE (1..MAX) OF
* PolicyQualifierInfo OPTIONAL }
*
* CertPolicyId ::= OBJECT IDENTIFIER
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{ policyIdentifier?: string; policyQualifiers?: string; }> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.policyIdentifier || EMPTY_STRING) }),
new asn1js.Sequence({
optional: true,
value: [
new asn1js.Repeated({
name: (names.policyQualifiers || EMPTY_STRING),
value: PolicyQualifierInfo.schema()
})
]
})
]
}));
}
/**
* Converts parsed ASN.1 object into current class
* @param schema
*/
fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PolicyInformation.schema({
names: {
policyIdentifier: POLICY_IDENTIFIER,
policyQualifiers: POLICY_QUALIFIERS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
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 }));
}
}
public toSchema(): asn1js.Sequence {
//Create array for output sequence
const outputArray = [];
outputArray.push(new asn1js.ObjectIdentifier({ value: this.policyIdentifier }));
if (this.policyQualifiers) {
outputArray.push(new asn1js.Sequence({
value: Array.from(this.policyQualifiers, o => o.toSchema())
}));
}
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: outputArray
}));
}
public toJSON(): PolicyInformationJson {
const res: PolicyInformationJson = {
policyIdentifier: this.policyIdentifier
};
if (this.policyQualifiers)
res.policyQualifiers = Array.from(this.policyQualifiers, o => o.toJSON());
return res;
}
}

132
third_party/js/PKI.js/src/PolicyMapping.ts поставляемый
Просмотреть файл

@ -1,132 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import * as Schema from "./Schema";
const ISSUER_DOMAIN_POLICY = "issuerDomainPolicy";
const SUBJECT_DOMAIN_POLICY = "subjectDomainPolicy";
const CLEAR_PROPS = [
ISSUER_DOMAIN_POLICY,
SUBJECT_DOMAIN_POLICY
];
export interface IPolicyMapping {
issuerDomainPolicy: string;
subjectDomainPolicy: string;
}
export interface PolicyMappingJson {
issuerDomainPolicy: string;
subjectDomainPolicy: string;
}
export type PolicyMappingParameters = PkiObjectParameters & Partial<IPolicyMapping>;
/**
* Represents the PolicyMapping structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class PolicyMapping extends PkiObject implements IPolicyMapping {
public static override CLASS_NAME = "PolicyMapping";
public issuerDomainPolicy!: string;
public subjectDomainPolicy!: string;
/**
* Initializes a new instance of the {@link PolicyMapping} class
* @param parameters Initialization parameters
*/
constructor(parameters: PolicyMappingParameters = {}) {
super();
this.issuerDomainPolicy = pvutils.getParametersValue(parameters, ISSUER_DOMAIN_POLICY, PolicyMapping.defaultValues(ISSUER_DOMAIN_POLICY));
this.subjectDomainPolicy = pvutils.getParametersValue(parameters, SUBJECT_DOMAIN_POLICY, PolicyMapping.defaultValues(SUBJECT_DOMAIN_POLICY));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: typeof ISSUER_DOMAIN_POLICY): string;
public static override defaultValues(memberName: typeof SUBJECT_DOMAIN_POLICY): string;
public static override defaultValues(memberName: string): any {
switch (memberName) {
case ISSUER_DOMAIN_POLICY:
return EMPTY_STRING;
case SUBJECT_DOMAIN_POLICY:
return EMPTY_STRING;
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PolicyMapping ::= SEQUENCE {
* issuerDomainPolicy CertPolicyId,
* subjectDomainPolicy CertPolicyId }
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
issuerDomainPolicy?: string;
subjectDomainPolicy?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.ObjectIdentifier({ name: (names.issuerDomainPolicy || EMPTY_STRING) }),
new asn1js.ObjectIdentifier({ name: (names.subjectDomainPolicy || EMPTY_STRING) })
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PolicyMapping.schema({
names: {
issuerDomainPolicy: ISSUER_DOMAIN_POLICY,
subjectDomainPolicy: SUBJECT_DOMAIN_POLICY
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.issuerDomainPolicy = asn1.result.issuerDomainPolicy.valueBlock.toString();
this.subjectDomainPolicy = asn1.result.subjectDomainPolicy.valueBlock.toString();
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: [
new asn1js.ObjectIdentifier({ value: this.issuerDomainPolicy }),
new asn1js.ObjectIdentifier({ value: this.subjectDomainPolicy })
]
}));
}
public toJSON(): PolicyMappingJson {
return {
issuerDomainPolicy: this.issuerDomainPolicy,
subjectDomainPolicy: this.subjectDomainPolicy
};
}
}

117
third_party/js/PKI.js/src/PolicyMappings.ts поставляемый
Просмотреть файл

@ -1,117 +0,0 @@
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { EMPTY_STRING } from "./constants";
import { AsnError } from "./errors";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { PolicyMapping, PolicyMappingJson } from "./PolicyMapping";
import * as Schema from "./Schema";
const MAPPINGS = "mappings";
const CLEAR_PROPS = [
MAPPINGS,
];
export interface IPolicyMappings {
mappings: PolicyMapping[];
}
export interface PolicyMappingsJson {
mappings: PolicyMappingJson[];
}
export type PolicyMappingsParameters = PkiObjectParameters & Partial<IPolicyMappings>;
/**
* Represents the PolicyMappings structure described in [RFC5280](https://datatracker.ietf.org/doc/html/rfc5280)
*/
export class PolicyMappings extends PkiObject implements IPolicyMappings {
public static override CLASS_NAME = "PolicyMappings";
public mappings!: PolicyMapping[];
/**
* Initializes a new instance of the {@link PolicyMappings} class
* @param parameters Initialization parameters
*/
constructor(parameters: PolicyMappingsParameters = {}) {
super();
this.mappings = pvutils.getParametersValue(parameters, MAPPINGS, PolicyMappings.defaultValues(MAPPINGS));
if (parameters.schema) {
this.fromSchema(parameters.schema);
}
}
/**
* Returns default values for all class members
* @param memberName String name for a class member
* @returns Default value
*/
public static override defaultValues(memberName: string): PolicyMapping[];
public static override defaultValues(memberName: string): any {
switch (memberName) {
case MAPPINGS:
return [];
default:
return super.defaultValues(memberName);
}
}
/**
* @inheritdoc
* @asn ASN.1 schema
* ```asn
* PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF PolicyMapping
*```
*/
public static override schema(parameters: Schema.SchemaParameters<{
mappings?: string;
}> = {}): Schema.SchemaType {
const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});
return (new asn1js.Sequence({
name: (names.blockName || EMPTY_STRING),
value: [
new asn1js.Repeated({
name: (names.mappings || EMPTY_STRING),
value: PolicyMapping.schema()
})
]
}));
}
public fromSchema(schema: Schema.SchemaType): void {
// Clear input data first
pvutils.clearProps(schema, CLEAR_PROPS);
// Check the schema is valid
const asn1 = asn1js.compareSchema(schema,
schema,
PolicyMappings.schema({
names: {
mappings: MAPPINGS
}
})
);
AsnError.assertSchema(asn1, this.className);
// Get internal properties from parsed schema
this.mappings = Array.from(asn1.result.mappings, element => new PolicyMapping({ schema: element }));
}
public toSchema(): asn1js.Sequence {
// Construct and return new ASN.1 schema for this object
return (new asn1js.Sequence({
value: Array.from(this.mappings, o => o.toSchema())
}));
}
public toJSON(): PolicyMappingsJson {
return {
mappings: Array.from(this.mappings, o => o.toJSON())
};
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше