Socket
Socket
Sign inDemoInstall

webcrypto-core

Package Overview
Dependencies
Maintainers
2
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

webcrypto-core - npm Package Compare versions

Comparing version 1.2.1 to 1.3.0

build/types/crypto_key_pair.d.ts

1

build/types/aes/base.d.ts
import { ProviderCrypto } from "../provider";
import { CryptoKey } from "../crypto_key";
export declare abstract class AesProvider extends ProviderCrypto {

@@ -3,0 +4,0 @@ checkGenerateKeyParams(algorithm: AesKeyGenParams): void;

16

build/types/asn1/ec_signature.d.ts

@@ -0,9 +1,17 @@

import { BufferSource } from "pvtsutils";
export declare class EcDsaSignature {
/**
* Create EcDsaSignature from X9.62 signature
* @param value X9.62 signature
* @returns EcDsaSignature
*/
static fromWebCryptoSignature(value: BufferSource): EcDsaSignature;
r: ArrayBuffer;
s: ArrayBuffer;
toWebCryptoSignature(pointSize?: number): ArrayBufferLike;
private getPointSize;
private addPadding;
private removePadding;
/**
* Converts ECDSA signature into X9.62 signature format
* @param pointSize EC point size in bits
* @returns ECDSA signature in X9.62 signature format
*/
toWebCryptoSignature(pointSize?: number): ArrayBuffer;
}

@@ -0,4 +1,152 @@

/**
* ```
* secp256r1 OBJECT IDENTIFIER ::= {
* iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
* prime(1) 7 }
* ```
*/
export declare const idSecp256r1 = "1.2.840.10045.3.1.7";
/**
* ```
* ellipticCurve OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) certicom(132) curve(0) }
* ```
*/
export declare const idEllipticCurve = "1.3.132.0";
/**
* ```
* secp384r1 OBJECT IDENTIFIER ::= { ellipticCurve 34 }
* ```
*/
export declare const idSecp384r1: string;
/**
* ```
* secp521r1 OBJECT IDENTIFIER ::= { ellipticCurve 35 }
* ```
*/
export declare const idSecp521r1: string;
/**
* ```
* secp256k1 OBJECT IDENTIFIER ::= { ellipticCurve 10 }
* ```
*/
export declare const idSecp256k1: string;
/**
* ```
* ecStdCurvesAndGeneration OBJECT IDENTIFIER ::= {
* iso(1) identified-organization(3) teletrust(36) algorithm(3)
* signature-algorithm(3) ecSign(2) ecStdCurvesAndGeneration(8)
* }
* ellipticCurve OBJECT IDENTIFIER ::= { ecStdCurvesAndGeneration 1 }
* versionOne OBJECT IDENTIFIER ::= { ellipticCurve 1 }
* ```
*/
export declare const idVersionOne = "1.3.36.3.3.2.8.1.1";
/**
* ```
* brainpoolP160r1 OBJECT IDENTIFIER ::= { versionOne 1 }
* ```
*/
export declare const idBrainpoolP160r1: string;
/**
* ```
* brainpoolP160t1 OBJECT IDENTIFIER ::= { versionOne 2 }
* ```
*/
export declare const idBrainpoolP160t1: string;
/**
* ```
* brainpoolP192r1 OBJECT IDENTIFIER ::= { versionOne 3 }
* ```
*/
export declare const idBrainpoolP192r1: string;
/**
* ```
* brainpoolP192t1 OBJECT IDENTIFIER ::= { versionOne 4 }
* ```
*/
export declare const idBrainpoolP192t1: string;
/**
* ```
* brainpoolP224r1 OBJECT IDENTIFIER ::= { versionOne 5 }
* ```
*/
export declare const idBrainpoolP224r1: string;
/**
* ```
* brainpoolP224t1 OBJECT IDENTIFIER ::= { versionOne 6 }
* ```
*/
export declare const idBrainpoolP224t1: string;
/**
* ```
* brainpoolP256r1 OBJECT IDENTIFIER ::= { versionOne 7 }
* ```
*/
export declare const idBrainpoolP256r1: string;
/**
* ```
* brainpoolP256t1 OBJECT IDENTIFIER ::= { versionOne 8 }
* ```
*/
export declare const idBrainpoolP256t1: string;
/**
* ```
* brainpoolP320r1 OBJECT IDENTIFIER ::= { versionOne 9 }
* ```
*/
export declare const idBrainpoolP320r1: string;
/**
* ```
* brainpoolP320t1 OBJECT IDENTIFIER ::= { versionOne 10 }
* ```
*/
export declare const idBrainpoolP320t1: string;
/**
* ```
* brainpoolP384r1 OBJECT IDENTIFIER ::= { versionOne 11 }
* ```
*/
export declare const idBrainpoolP384r1: string;
/**
* ```
* brainpoolP384t1 OBJECT IDENTIFIER ::= { versionOne 12 }
* ```
*/
export declare const idBrainpoolP384t1: string;
/**
* ```
* brainpoolP512r1 OBJECT IDENTIFIER ::= { versionOne 13 }
* ```
*/
export declare const idBrainpoolP512r1: string;
/**
* ```
* brainpoolP512t1 OBJECT IDENTIFIER ::= { versionOne 14 }
* ```
*/
export declare const idBrainpoolP512t1: string;
/**
* ```
* id-X25519 OBJECT IDENTIFIER ::= { 1 3 101 110 }
* ```
*/
export declare const idX25519 = "1.3.101.110";
/**
* ```
* id-X448 OBJECT IDENTIFIER ::= { 1 3 101 111 }
* ```
*/
export declare const idX448 = "1.3.101.111";
/**
* ```
* id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
* ```
*/
export declare const idEd25519 = "1.3.101.112";
/**
* ```
* id-Ed448 OBJECT IDENTIFIER ::= { 1 3 101 113 }
* ```
*/
export declare const idEd448 = "1.3.101.113";

@@ -13,3 +13,3 @@ import { SubtleCrypto } from "./subtle";

*/
abstract getRandomValues<T extends ArrayBufferView>(array: T): T;
abstract getRandomValues<T extends ArrayBufferView | null>(array: T): T;
}

@@ -1,2 +0,2 @@

import { KeyAlgorithm } from "../key";
import { KeyAlgorithm, CryptoKey } from "../crypto_key";
import { ProviderCrypto } from "../provider";

@@ -3,0 +3,0 @@ import { KeyUsages } from "../types";

@@ -0,1 +1,3 @@

import { CryptoKey } from "../crypto_key";
import { CryptoKeyPair } from "../crypto_key_pair";
import { ProviderCrypto } from "../provider";

@@ -2,0 +4,0 @@ export declare abstract class EllipticProvider extends ProviderCrypto {

@@ -1,2 +0,2 @@

import { CryptoKey } from "../key";
import { CryptoKey } from "../crypto_key";
import { ProviderKeyUsages } from "../types";

@@ -3,0 +3,0 @@ import { EllipticProvider } from "./base";

@@ -6,1 +6,3 @@ export * from "./base";

export * from "./eddsa";
export * from "./curves";
export * from "./utils";

@@ -0,1 +1,2 @@

import { CryptoKey } from "../crypto_key";
import { ProviderCrypto } from "../provider";

@@ -2,0 +3,0 @@ import { KeyUsages } from "../types";

@@ -0,1 +1,2 @@

import { CryptoKey } from "../crypto_key";
import { ProviderCrypto } from "../provider";

@@ -2,0 +3,0 @@ import { KeyUsages } from "../types";

@@ -13,3 +13,3 @@ export * from "./errors";

export * from "./subtle";
export * from "./key";
export * from "./crypto_key";
export * from "./utils";

@@ -20,1 +20,2 @@ export { BufferSourceConverter } from "pvtsutils";

export * as json from "./json";
export * from "./crypto_key_pair";

@@ -0,1 +1,2 @@

import { CryptoKey } from "../crypto_key";
import { ProviderCrypto } from "../provider";

@@ -2,0 +3,0 @@ import { KeyUsages } from "../types";

@@ -0,1 +1,3 @@

import { CryptoKey } from "./crypto_key";
import { CryptoKeyPair } from "./crypto_key_pair";
import { KeyUsages, ProviderKeyUsages } from "./types";

@@ -17,2 +19,4 @@ export interface IProviderCheckOptions {

onDigest(algorithm: Algorithm, data: ArrayBuffer): Promise<ArrayBuffer>;
generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair>;
generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
generateKey(algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<CryptoKeyPair | CryptoKey>;

@@ -19,0 +23,0 @@ checkGenerateKey(algorithm: Algorithm, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): void;

@@ -0,1 +1,3 @@

import { CryptoKey } from "../crypto_key";
import { CryptoKeyPair } from "../crypto_key_pair";
import { ProviderCrypto } from "../provider";

@@ -2,0 +4,0 @@ export declare abstract class RsaProvider extends ProviderCrypto {

import { ProviderCrypto } from "./provider";
import { ProviderStorage } from "./storage";
import { HashedAlgorithm } from "./types";
import { CryptoKey } from './key';
import { CryptoKey } from './crypto_key';
import { CryptoKeyPair } from './crypto_key_pair';
export declare class SubtleCrypto {

@@ -9,3 +10,5 @@ static isHashedAlgorithm(data: any): data is HashedAlgorithm;

digest(algorithm: AlgorithmIdentifier, data: BufferSource, ...args: any[]): Promise<ArrayBuffer>;
generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<CryptoKeyPair | globalThis.CryptoKey>;
generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<CryptoKeyPair>;
generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<CryptoKey>;
generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: Iterable<KeyUsage>, ...args: any[]): Promise<CryptoKeyPair | CryptoKey>;
sign(algorithm: AlgorithmIdentifier, key: CryptoKey, data: BufferSource, ...args: any[]): Promise<ArrayBuffer>;

@@ -16,9 +19,9 @@ verify(algorithm: AlgorithmIdentifier, key: CryptoKey, signature: BufferSource, data: BufferSource, ...args: any[]): Promise<boolean>;

deriveBits(algorithm: AlgorithmIdentifier, baseKey: CryptoKey, length: number, ...args: any[]): Promise<ArrayBuffer>;
deriveKey(algorithm: AlgorithmIdentifier, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<globalThis.CryptoKey>;
deriveKey(algorithm: AlgorithmIdentifier, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<CryptoKey>;
exportKey(format: "raw" | "spki" | "pkcs8", key: CryptoKey, ...args: any[]): Promise<ArrayBuffer>;
exportKey(format: "jwk", key: CryptoKey, ...args: any[]): Promise<JsonWebKey>;
exportKey(format: KeyFormat, key: CryptoKey, ...args: any[]): Promise<JsonWebKey | ArrayBuffer>;
importKey(format: KeyFormat, keyData: JsonWebKey | BufferSource, algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<globalThis.CryptoKey>;
importKey(format: KeyFormat, keyData: JsonWebKey | BufferSource, algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<CryptoKey>;
wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier, ...args: any[]): Promise<ArrayBuffer>;
unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<globalThis.CryptoKey>;
unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier, unwrappedKeyAlgorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[], ...args: any[]): Promise<CryptoKey>;
protected checkRequiredArguments(args: any[], size: number, methodName: string): void;

@@ -25,0 +28,0 @@ protected prepareAlgorithm(algorithm: AlgorithmIdentifier): Algorithm | HashedAlgorithm;

@@ -7,4 +7,4 @@ /**

export { BufferSourceConverter } from 'pvtsutils';
import { AsnProp, AsnPropTypes, AsnType, AsnTypeTypes, AsnIntegerConverter, AsnSerializer, AsnConvert } from '@peculiar/asn1-schema';
import { __decorate } from 'tslib';
import { AsnProp, AsnPropTypes, AsnType, AsnTypeTypes, AsnIntegerConverter, AsnSerializer } from '@peculiar/asn1-schema';
import { JsonProp, JsonPropTypes } from '@peculiar/json-schema';

@@ -443,3 +443,3 @@ import * as asn1 from 'asn1js';

if (algorithm.length !== this.keySizeBits) {
throw new OperationError(`algorith.length: Must be ${this.keySizeBits}`);
throw new OperationError(`algorithm.length: Must be ${this.keySizeBits}`);
}

@@ -626,312 +626,2 @@ }

class HmacProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HMAC";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["sign", "verify"];
}
getDefaultLength(algName) {
switch (algName.toUpperCase()) {
case "SHA-1":
case "SHA-256":
case "SHA-384":
case "SHA-512":
return 512;
default:
throw new Error(`Unknown algorithm name '${algName}'`);
}
}
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
if ("length" in algorithm) {
if (typeof algorithm.length !== "number") {
throw new TypeError("length: Is not a Number");
}
if (algorithm.length < 1) {
throw new RangeError("length: Number is out of range");
}
}
}
checkImportParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
}
}
class Pbkdf2Provider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "PBKDF2";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveBits", "deriveKey"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!(algorithm.salt instanceof ArrayBuffer || ArrayBuffer.isView(algorithm.salt))) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "iterations");
if (typeof algorithm.iterations !== "number") {
throw new TypeError("iterations: Is not a Number");
}
if (algorithm.iterations < 1) {
throw new TypeError("iterations: Is less than 1");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class HkdfProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HKDF";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveKey", "deriveBits"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!BufferSourceConverter.isBufferSource(algorithm.salt)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "info");
if (!BufferSourceConverter.isBufferSource(algorithm.info)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class Crypto {
get [Symbol.toStringTag]() {
return "Crypto";
}
}
class ProviderStorage {
constructor() {
this.items = {};
}
get(algorithmName) {
return this.items[algorithmName.toLowerCase()] || null;
}
set(provider) {
this.items[provider.name.toLowerCase()] = provider;
}
removeAt(algorithmName) {
const provider = this.get(algorithmName.toLowerCase());
if (provider) {
delete this.items[algorithmName];
}
return provider;
}
has(name) {
return !!this.get(name);
}
get length() {
return Object.keys(this.items).length;
}
get algorithms() {
const algorithms = [];
for (const key in this.items) {
const provider = this.items[key];
algorithms.push(provider.name);
}
return algorithms.sort();
}
}
class SubtleCrypto {
constructor() {
this.providers = new ProviderStorage();
}
static isHashedAlgorithm(data) {
return data
&& typeof data === "object"
&& "name" in data
&& "hash" in data
? true
: false;
}
get [Symbol.toStringTag]() {
return "SubtleCrypto";
}
async digest(...args) {
this.checkRequiredArguments(args, 2, "digest");
const [algorithm, data, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.digest(preparedAlgorithm, preparedData, ...params);
return result;
}
async generateKey(...args) {
this.checkRequiredArguments(args, 3, "generateKey");
const [algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.generateKey({ ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
return result;
}
async sign(...args) {
this.checkRequiredArguments(args, 3, "sign");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.sign({ ...preparedAlgorithm, name: provider.name }, key, preparedData, ...params);
return result;
}
async verify(...args) {
this.checkRequiredArguments(args, 4, "verify");
const [algorithm, key, signature, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const preparedSignature = BufferSourceConverter.toArrayBuffer(signature);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.verify({ ...preparedAlgorithm, name: provider.name }, key, preparedSignature, preparedData, ...params);
return result;
}
async encrypt(...args) {
this.checkRequiredArguments(args, 3, "encrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.encrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async decrypt(...args) {
this.checkRequiredArguments(args, 3, "decrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async deriveBits(...args) {
this.checkRequiredArguments(args, 3, "deriveBits");
const [algorithm, baseKey, length, ...params] = args;
this.checkCryptoKey(baseKey);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, length, { keyUsage: true }, ...params);
return result;
}
async deriveKey(...args) {
this.checkRequiredArguments(args, 5, "deriveKey");
const [algorithm, baseKey, derivedKeyType, extractable, keyUsages, ...params] = args;
const preparedDerivedKeyType = this.prepareAlgorithm(derivedKeyType);
const importProvider = this.getProvider(preparedDerivedKeyType.name);
importProvider.checkDerivedKeyParams(preparedDerivedKeyType);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
provider.checkCryptoKey(baseKey, "deriveKey");
const derivedBits = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, derivedKeyType.length || 512, { keyUsage: false }, ...params);
return this.importKey("raw", derivedBits, derivedKeyType, extractable, keyUsages, ...params);
}
async exportKey(...args) {
this.checkRequiredArguments(args, 2, "exportKey");
const [format, key, ...params] = args;
this.checkCryptoKey(key);
const provider = this.getProvider(key.algorithm.name);
const result = await provider.exportKey(format, key, ...params);
return result;
}
async importKey(...args) {
this.checkRequiredArguments(args, 5, "importKey");
const [format, keyData, algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
if (["pkcs8", "spki", "raw"].indexOf(format) !== -1) {
const preparedData = BufferSourceConverter.toArrayBuffer(keyData);
return provider.importKey(format, preparedData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
else {
if (!keyData.kty) {
throw new TypeError("keyData: Is not JSON");
}
}
return provider.importKey(format, keyData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
async wrapKey(format, key, wrappingKey, wrapAlgorithm, ...args) {
let keyData = await this.exportKey(format, key, ...args);
if (format === "jwk") {
const json = JSON.stringify(keyData);
keyData = Convert.FromUtf8String(json);
}
const preparedAlgorithm = this.prepareAlgorithm(wrapAlgorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(keyData);
const provider = this.getProvider(preparedAlgorithm.name);
return provider.encrypt({ ...preparedAlgorithm, name: provider.name }, wrappingKey, preparedData, { keyUsage: false }, ...args);
}
async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages, ...args) {
const preparedAlgorithm = this.prepareAlgorithm(unwrapAlgorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(wrappedKey);
const provider = this.getProvider(preparedAlgorithm.name);
let keyData = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, unwrappingKey, preparedData, { keyUsage: false }, ...args);
if (format === "jwk") {
try {
keyData = JSON.parse(Convert.ToUtf8String(keyData));
}
catch (e) {
const error = new TypeError("wrappedKey: Is not a JSON");
error.internal = e;
throw error;
}
}
return this.importKey(format, keyData, unwrappedKeyAlgorithm, extractable, keyUsages, ...args);
}
checkRequiredArguments(args, size, methodName) {
if (args.length < size) {
throw new TypeError(`Failed to execute '${methodName}' on 'SubtleCrypto': ${size} arguments required, but only ${args.length} present`);
}
}
prepareAlgorithm(algorithm) {
if (typeof algorithm === "string") {
return {
name: algorithm,
};
}
if (SubtleCrypto.isHashedAlgorithm(algorithm)) {
const preparedAlgorithm = { ...algorithm };
preparedAlgorithm.hash = this.prepareAlgorithm(algorithm.hash);
return preparedAlgorithm;
}
return { ...algorithm };
}
getProvider(name) {
const provider = this.providers.get(name);
if (!provider) {
throw new AlgorithmError("Unrecognized name");
}
return provider;
}
checkCryptoKey(key) {
if (!(key instanceof CryptoKey)) {
throw new TypeError(`Key is not of type 'CryptoKey'`);
}
}
}
let ObjectIdentifier = class ObjectIdentifier {

@@ -1202,2 +892,74 @@ constructor(value) {

class EcUtils {
static decodePoint(data, pointSize) {
const view = BufferSourceConverter.toUint8Array(data);
if ((view.length === 0) || (view[0] !== 4)) {
throw new Error("Only uncompressed point format supported");
}
const n = (view.length - 1) / 2;
if (n !== (Math.ceil(pointSize / 8))) {
throw new Error("Point does not match field size");
}
const xb = view.slice(1, n + 1);
const yb = view.slice(n + 1, n + 1 + n);
return { x: xb, y: yb };
}
static encodePoint(point, pointSize) {
const size = Math.ceil(pointSize / 8);
if (point.x.byteLength !== size || point.y.byteLength !== size) {
throw new Error("X,Y coordinates don't match point size criteria");
}
const x = BufferSourceConverter.toUint8Array(point.x);
const y = BufferSourceConverter.toUint8Array(point.y);
const res = new Uint8Array(size * 2 + 1);
res[0] = 4;
res.set(x, 1);
res.set(y, size + 1);
return res;
}
static getSize(pointSize) {
return Math.ceil(pointSize / 8);
}
static encodeSignature(signature, pointSize) {
const size = this.getSize(pointSize);
const r = BufferSourceConverter.toUint8Array(signature.r);
const s = BufferSourceConverter.toUint8Array(signature.s);
const res = new Uint8Array(size * 2);
res.set(this.padStart(r, size));
res.set(this.padStart(s, size), size);
return res;
}
static decodeSignature(data, pointSize) {
const size = this.getSize(pointSize);
const view = BufferSourceConverter.toUint8Array(data);
if (view.length !== (size * 2)) {
throw new Error("Incorrect size of the signature");
}
const r = view.slice(0, size);
const s = view.slice(size);
return {
r: this.trimStart(r),
s: this.trimStart(s),
};
}
static trimStart(data) {
let i = 0;
while ((i < data.length - 1) && (data[i] === 0)) {
i++;
}
if (i === 0) {
return data;
}
return data.slice(i, data.length);
}
static padStart(data, size) {
if (size === data.length) {
return data;
}
const res = new Uint8Array(size);
res.set(data, size - data.length);
return res;
}
}
class EcDsaSignature {

@@ -1209,49 +971,14 @@ constructor() {

static fromWebCryptoSignature(value) {
const wcSignature = BufferSourceConverter.toUint8Array(value);
const pointSize = wcSignature.byteLength / 2;
const ecSignature = new this();
ecSignature.r = ecSignature.removePadding(wcSignature.slice(0, pointSize));
ecSignature.s = ecSignature.removePadding(wcSignature.slice(pointSize, pointSize * 2));
const pointSize = value.byteLength / 2;
const point = EcUtils.decodeSignature(value, pointSize * 8);
const ecSignature = new EcDsaSignature();
ecSignature.r = BufferSourceConverter.toArrayBuffer(point.r);
ecSignature.s = BufferSourceConverter.toArrayBuffer(point.s);
return ecSignature;
}
toWebCryptoSignature(pointSize) {
pointSize = this.getPointSize();
const r = this.addPadding(pointSize, BufferSourceConverter.toUint8Array(this.r));
const s = this.addPadding(pointSize, BufferSourceConverter.toUint8Array(this.s));
const wcSignature = new Uint8Array(r.byteLength + s.byteLength);
wcSignature.set(r, 0);
wcSignature.set(s, r.length);
return wcSignature.buffer;
pointSize !== null && pointSize !== void 0 ? pointSize : (pointSize = Math.max(this.r.byteLength, this.s.byteLength) * 8);
const signature = EcUtils.encodeSignature(this, pointSize);
return signature.buffer;
}
getPointSize() {
const size = Math.max(this.r.byteLength, this.s.byteLength);
switch (size) {
case 31:
case 32:
return 32;
case 47:
case 48:
return 48;
case 65:
case 66:
return 66;
}
throw new Error("Unsupported EC point size");
}
addPadding(pointSize, bytes) {
const res = new Uint8Array(pointSize);
const uint8Array = BufferSourceConverter.toUint8Array(bytes);
res.set(uint8Array, pointSize - uint8Array.length);
return res;
}
removePadding(bytes) {
const uint8Array = BufferSourceConverter.toUint8Array(bytes);
for (let i = 0; i < uint8Array.length; i++) {
if (!uint8Array[i]) {
continue;
}
return uint8Array.slice(i);
}
return new Uint8Array(0);
}
}

@@ -1275,2 +1002,22 @@ __decorate([

const idSecp256r1 = "1.2.840.10045.3.1.7";
const idEllipticCurve = "1.3.132.0";
const idSecp384r1 = `${idEllipticCurve}.34`;
const idSecp521r1 = `${idEllipticCurve}.35`;
const idSecp256k1 = `${idEllipticCurve}.10`;
const idVersionOne = "1.3.36.3.3.2.8.1.1";
const idBrainpoolP160r1 = `${idVersionOne}.1`;
const idBrainpoolP160t1 = `${idVersionOne}.2`;
const idBrainpoolP192r1 = `${idVersionOne}.3`;
const idBrainpoolP192t1 = `${idVersionOne}.4`;
const idBrainpoolP224r1 = `${idVersionOne}.5`;
const idBrainpoolP224t1 = `${idVersionOne}.6`;
const idBrainpoolP256r1 = `${idVersionOne}.7`;
const idBrainpoolP256t1 = `${idVersionOne}.8`;
const idBrainpoolP320r1 = `${idVersionOne}.9`;
const idBrainpoolP320t1 = `${idVersionOne}.10`;
const idBrainpoolP384r1 = `${idVersionOne}.11`;
const idBrainpoolP384t1 = `${idVersionOne}.12`;
const idBrainpoolP512r1 = `${idVersionOne}.13`;
const idBrainpoolP512t1 = `${idVersionOne}.14`;
const idX25519 = "1.3.101.110";

@@ -1294,2 +1041,22 @@ const idX448 = "1.3.101.111";

get CurvePrivateKey () { return CurvePrivateKey; },
idSecp256r1: idSecp256r1,
idEllipticCurve: idEllipticCurve,
idSecp384r1: idSecp384r1,
idSecp521r1: idSecp521r1,
idSecp256k1: idSecp256k1,
idVersionOne: idVersionOne,
idBrainpoolP160r1: idBrainpoolP160r1,
idBrainpoolP160t1: idBrainpoolP160t1,
idBrainpoolP192r1: idBrainpoolP192r1,
idBrainpoolP192t1: idBrainpoolP192t1,
idBrainpoolP224r1: idBrainpoolP224r1,
idBrainpoolP224t1: idBrainpoolP224t1,
idBrainpoolP256r1: idBrainpoolP256r1,
idBrainpoolP256t1: idBrainpoolP256t1,
idBrainpoolP320r1: idBrainpoolP320r1,
idBrainpoolP320t1: idBrainpoolP320t1,
idBrainpoolP384r1: idBrainpoolP384r1,
idBrainpoolP384t1: idBrainpoolP384t1,
idBrainpoolP512r1: idBrainpoolP512r1,
idBrainpoolP512t1: idBrainpoolP512t1,
idX25519: idX25519,

@@ -1301,2 +1068,362 @@ idX448: idX448,

class EcCurves {
constructor() { }
static register(item) {
const oid = new ObjectIdentifier();
oid.value = item.id;
const raw = AsnConvert.serialize(oid);
this.items.push({
...item,
raw,
});
this.names.push(item.name);
}
static find(nameOrId) {
nameOrId = nameOrId.toUpperCase();
for (const item of this.items) {
if (item.name.toUpperCase() === nameOrId || item.id.toUpperCase() === nameOrId) {
return item;
}
}
return null;
}
static get(nameOrId) {
const res = this.find(nameOrId);
if (!res) {
throw new Error(`Unsupported EC named curve '${nameOrId}'`);
}
return res;
}
}
EcCurves.items = [];
EcCurves.names = [];
EcCurves.register({ name: "P-256", id: idSecp256r1, size: 256 });
EcCurves.register({ name: "P-384", id: idSecp384r1, size: 384 });
EcCurves.register({ name: "P-521", id: idSecp521r1, size: 521 });
EcCurves.register({ name: "K-256", id: idSecp256k1, size: 256 });
EcCurves.register({ name: "brainpoolP160r1", id: idBrainpoolP160r1, size: 160 });
EcCurves.register({ name: "brainpoolP160t1", id: idBrainpoolP160t1, size: 160 });
EcCurves.register({ name: "brainpoolP192r1", id: idBrainpoolP192r1, size: 192 });
EcCurves.register({ name: "brainpoolP192t1", id: idBrainpoolP192t1, size: 192 });
EcCurves.register({ name: "brainpoolP224r1", id: idBrainpoolP224r1, size: 224 });
EcCurves.register({ name: "brainpoolP224t1", id: idBrainpoolP224t1, size: 224 });
EcCurves.register({ name: "brainpoolP256r1", id: idBrainpoolP256r1, size: 256 });
EcCurves.register({ name: "brainpoolP256t1", id: idBrainpoolP256t1, size: 256 });
EcCurves.register({ name: "brainpoolP320r1", id: idBrainpoolP320r1, size: 320 });
EcCurves.register({ name: "brainpoolP320t1", id: idBrainpoolP320t1, size: 320 });
EcCurves.register({ name: "brainpoolP384r1", id: idBrainpoolP384r1, size: 384 });
EcCurves.register({ name: "brainpoolP384t1", id: idBrainpoolP384t1, size: 384 });
EcCurves.register({ name: "brainpoolP512r1", id: idBrainpoolP512r1, size: 512 });
EcCurves.register({ name: "brainpoolP512t1", id: idBrainpoolP512t1, size: 512 });
class HmacProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HMAC";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["sign", "verify"];
}
getDefaultLength(algName) {
switch (algName.toUpperCase()) {
case "SHA-1":
case "SHA-256":
case "SHA-384":
case "SHA-512":
return 512;
default:
throw new Error(`Unknown algorithm name '${algName}'`);
}
}
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
if ("length" in algorithm) {
if (typeof algorithm.length !== "number") {
throw new TypeError("length: Is not a Number");
}
if (algorithm.length < 1) {
throw new RangeError("length: Number is out of range");
}
}
}
checkImportParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
}
}
class Pbkdf2Provider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "PBKDF2";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveBits", "deriveKey"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!(algorithm.salt instanceof ArrayBuffer || ArrayBuffer.isView(algorithm.salt))) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "iterations");
if (typeof algorithm.iterations !== "number") {
throw new TypeError("iterations: Is not a Number");
}
if (algorithm.iterations < 1) {
throw new TypeError("iterations: Is less than 1");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class HkdfProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HKDF";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveKey", "deriveBits"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!BufferSourceConverter.isBufferSource(algorithm.salt)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "info");
if (!BufferSourceConverter.isBufferSource(algorithm.info)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class Crypto {
get [Symbol.toStringTag]() {
return "Crypto";
}
}
class ProviderStorage {
constructor() {
this.items = {};
}
get(algorithmName) {
return this.items[algorithmName.toLowerCase()] || null;
}
set(provider) {
this.items[provider.name.toLowerCase()] = provider;
}
removeAt(algorithmName) {
const provider = this.get(algorithmName.toLowerCase());
if (provider) {
delete this.items[algorithmName];
}
return provider;
}
has(name) {
return !!this.get(name);
}
get length() {
return Object.keys(this.items).length;
}
get algorithms() {
const algorithms = [];
for (const key in this.items) {
const provider = this.items[key];
algorithms.push(provider.name);
}
return algorithms.sort();
}
}
class SubtleCrypto {
constructor() {
this.providers = new ProviderStorage();
}
static isHashedAlgorithm(data) {
return data
&& typeof data === "object"
&& "name" in data
&& "hash" in data
? true
: false;
}
get [Symbol.toStringTag]() {
return "SubtleCrypto";
}
async digest(...args) {
this.checkRequiredArguments(args, 2, "digest");
const [algorithm, data, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.digest(preparedAlgorithm, preparedData, ...params);
return result;
}
async generateKey(...args) {
this.checkRequiredArguments(args, 3, "generateKey");
const [algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.generateKey({ ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
return result;
}
async sign(...args) {
this.checkRequiredArguments(args, 3, "sign");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.sign({ ...preparedAlgorithm, name: provider.name }, key, preparedData, ...params);
return result;
}
async verify(...args) {
this.checkRequiredArguments(args, 4, "verify");
const [algorithm, key, signature, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const preparedSignature = BufferSourceConverter.toArrayBuffer(signature);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.verify({ ...preparedAlgorithm, name: provider.name }, key, preparedSignature, preparedData, ...params);
return result;
}
async encrypt(...args) {
this.checkRequiredArguments(args, 3, "encrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.encrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async decrypt(...args) {
this.checkRequiredArguments(args, 3, "decrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async deriveBits(...args) {
this.checkRequiredArguments(args, 3, "deriveBits");
const [algorithm, baseKey, length, ...params] = args;
this.checkCryptoKey(baseKey);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, length, { keyUsage: true }, ...params);
return result;
}
async deriveKey(...args) {
this.checkRequiredArguments(args, 5, "deriveKey");
const [algorithm, baseKey, derivedKeyType, extractable, keyUsages, ...params] = args;
const preparedDerivedKeyType = this.prepareAlgorithm(derivedKeyType);
const importProvider = this.getProvider(preparedDerivedKeyType.name);
importProvider.checkDerivedKeyParams(preparedDerivedKeyType);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
provider.checkCryptoKey(baseKey, "deriveKey");
const derivedBits = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, derivedKeyType.length || 512, { keyUsage: false }, ...params);
return this.importKey("raw", derivedBits, derivedKeyType, extractable, keyUsages, ...params);
}
async exportKey(...args) {
this.checkRequiredArguments(args, 2, "exportKey");
const [format, key, ...params] = args;
this.checkCryptoKey(key);
const provider = this.getProvider(key.algorithm.name);
const result = await provider.exportKey(format, key, ...params);
return result;
}
async importKey(...args) {
this.checkRequiredArguments(args, 5, "importKey");
const [format, keyData, algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
if (["pkcs8", "spki", "raw"].indexOf(format) !== -1) {
const preparedData = BufferSourceConverter.toArrayBuffer(keyData);
return provider.importKey(format, preparedData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
else {
if (!keyData.kty) {
throw new TypeError("keyData: Is not JSON");
}
}
return provider.importKey(format, keyData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
async wrapKey(format, key, wrappingKey, wrapAlgorithm, ...args) {
let keyData = await this.exportKey(format, key, ...args);
if (format === "jwk") {
const json = JSON.stringify(keyData);
keyData = Convert.FromUtf8String(json);
}
const preparedAlgorithm = this.prepareAlgorithm(wrapAlgorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(keyData);
const provider = this.getProvider(preparedAlgorithm.name);
return provider.encrypt({ ...preparedAlgorithm, name: provider.name }, wrappingKey, preparedData, { keyUsage: false }, ...args);
}
async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages, ...args) {
const preparedAlgorithm = this.prepareAlgorithm(unwrapAlgorithm);
const preparedData = BufferSourceConverter.toArrayBuffer(wrappedKey);
const provider = this.getProvider(preparedAlgorithm.name);
let keyData = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, unwrappingKey, preparedData, { keyUsage: false }, ...args);
if (format === "jwk") {
try {
keyData = JSON.parse(Convert.ToUtf8String(keyData));
}
catch (e) {
const error = new TypeError("wrappedKey: Is not a JSON");
error.internal = e;
throw error;
}
}
return this.importKey(format, keyData, unwrappedKeyAlgorithm, extractable, keyUsages, ...args);
}
checkRequiredArguments(args, size, methodName) {
if (args.length < size) {
throw new TypeError(`Failed to execute '${methodName}' on 'SubtleCrypto': ${size} arguments required, but only ${args.length} present`);
}
}
prepareAlgorithm(algorithm) {
if (typeof algorithm === "string") {
return {
name: algorithm,
};
}
if (SubtleCrypto.isHashedAlgorithm(algorithm)) {
const preparedAlgorithm = { ...algorithm };
preparedAlgorithm.hash = this.prepareAlgorithm(algorithm.hash);
return preparedAlgorithm;
}
return { ...algorithm };
}
getProvider(name) {
const provider = this.providers.get(name);
if (!provider) {
throw new AlgorithmError("Unrecognized name");
}
return provider;
}
checkCryptoKey(key) {
if (!(key instanceof CryptoKey)) {
throw new TypeError(`Key is not of type 'CryptoKey'`);
}
}
}
var index = /*#__PURE__*/Object.freeze({

@@ -1307,2 +1434,2 @@ __proto__: null,

export { AesCbcProvider, AesCmacProvider, AesCtrProvider, AesEcbProvider, AesGcmProvider, AesKwProvider, AesProvider, AlgorithmError, Crypto, CryptoError, CryptoKey, DesProvider, EcdhEsProvider, EcdhProvider, EcdsaProvider, EdDsaProvider, EllipticProvider, HkdfProvider, HmacProvider, OperationError, Pbkdf2Provider, PemConverter, ProviderCrypto, ProviderStorage, RequiredPropertyError, RsaOaepProvider, RsaProvider, RsaPssProvider, RsaSsaProvider, SubtleCrypto, UnsupportedOperationError, index$1 as asn1, isJWK, index as json };
export { AesCbcProvider, AesCmacProvider, AesCtrProvider, AesEcbProvider, AesGcmProvider, AesKwProvider, AesProvider, AlgorithmError, Crypto, CryptoError, CryptoKey, DesProvider, EcCurves, EcUtils, EcdhEsProvider, EcdhProvider, EcdsaProvider, EdDsaProvider, EllipticProvider, HkdfProvider, HmacProvider, OperationError, Pbkdf2Provider, PemConverter, ProviderCrypto, ProviderStorage, RequiredPropertyError, RsaOaepProvider, RsaProvider, RsaPssProvider, RsaSsaProvider, SubtleCrypto, UnsupportedOperationError, index$1 as asn1, isJWK, index as json };

@@ -10,4 +10,4 @@ /**

var pvtsutils = require('pvtsutils');
var asn1Schema = require('@peculiar/asn1-schema');
var tslib = require('tslib');
var asn1Schema = require('@peculiar/asn1-schema');
var jsonSchema = require('@peculiar/json-schema');

@@ -25,5 +25,3 @@ var asn1 = require('asn1js');

enumerable: true,
get: function () {
return e[k];
}
get: function () { return e[k]; }
});

@@ -33,3 +31,3 @@ }

}
n['default'] = e;
n["default"] = e;
return Object.freeze(n);

@@ -470,3 +468,3 @@ }

if (algorithm.length !== this.keySizeBits) {
throw new OperationError(`algorith.length: Must be ${this.keySizeBits}`);
throw new OperationError(`algorithm.length: Must be ${this.keySizeBits}`);
}

@@ -653,312 +651,2 @@ }

class HmacProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HMAC";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["sign", "verify"];
}
getDefaultLength(algName) {
switch (algName.toUpperCase()) {
case "SHA-1":
case "SHA-256":
case "SHA-384":
case "SHA-512":
return 512;
default:
throw new Error(`Unknown algorithm name '${algName}'`);
}
}
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
if ("length" in algorithm) {
if (typeof algorithm.length !== "number") {
throw new TypeError("length: Is not a Number");
}
if (algorithm.length < 1) {
throw new RangeError("length: Number is out of range");
}
}
}
checkImportParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
}
}
class Pbkdf2Provider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "PBKDF2";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveBits", "deriveKey"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!(algorithm.salt instanceof ArrayBuffer || ArrayBuffer.isView(algorithm.salt))) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "iterations");
if (typeof algorithm.iterations !== "number") {
throw new TypeError("iterations: Is not a Number");
}
if (algorithm.iterations < 1) {
throw new TypeError("iterations: Is less than 1");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class HkdfProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HKDF";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveKey", "deriveBits"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!pvtsutils.BufferSourceConverter.isBufferSource(algorithm.salt)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "info");
if (!pvtsutils.BufferSourceConverter.isBufferSource(algorithm.info)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class Crypto {
get [Symbol.toStringTag]() {
return "Crypto";
}
}
class ProviderStorage {
constructor() {
this.items = {};
}
get(algorithmName) {
return this.items[algorithmName.toLowerCase()] || null;
}
set(provider) {
this.items[provider.name.toLowerCase()] = provider;
}
removeAt(algorithmName) {
const provider = this.get(algorithmName.toLowerCase());
if (provider) {
delete this.items[algorithmName];
}
return provider;
}
has(name) {
return !!this.get(name);
}
get length() {
return Object.keys(this.items).length;
}
get algorithms() {
const algorithms = [];
for (const key in this.items) {
const provider = this.items[key];
algorithms.push(provider.name);
}
return algorithms.sort();
}
}
class SubtleCrypto {
constructor() {
this.providers = new ProviderStorage();
}
static isHashedAlgorithm(data) {
return data
&& typeof data === "object"
&& "name" in data
&& "hash" in data
? true
: false;
}
get [Symbol.toStringTag]() {
return "SubtleCrypto";
}
async digest(...args) {
this.checkRequiredArguments(args, 2, "digest");
const [algorithm, data, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.digest(preparedAlgorithm, preparedData, ...params);
return result;
}
async generateKey(...args) {
this.checkRequiredArguments(args, 3, "generateKey");
const [algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.generateKey({ ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
return result;
}
async sign(...args) {
this.checkRequiredArguments(args, 3, "sign");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.sign({ ...preparedAlgorithm, name: provider.name }, key, preparedData, ...params);
return result;
}
async verify(...args) {
this.checkRequiredArguments(args, 4, "verify");
const [algorithm, key, signature, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const preparedSignature = pvtsutils.BufferSourceConverter.toArrayBuffer(signature);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.verify({ ...preparedAlgorithm, name: provider.name }, key, preparedSignature, preparedData, ...params);
return result;
}
async encrypt(...args) {
this.checkRequiredArguments(args, 3, "encrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.encrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async decrypt(...args) {
this.checkRequiredArguments(args, 3, "decrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async deriveBits(...args) {
this.checkRequiredArguments(args, 3, "deriveBits");
const [algorithm, baseKey, length, ...params] = args;
this.checkCryptoKey(baseKey);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, length, { keyUsage: true }, ...params);
return result;
}
async deriveKey(...args) {
this.checkRequiredArguments(args, 5, "deriveKey");
const [algorithm, baseKey, derivedKeyType, extractable, keyUsages, ...params] = args;
const preparedDerivedKeyType = this.prepareAlgorithm(derivedKeyType);
const importProvider = this.getProvider(preparedDerivedKeyType.name);
importProvider.checkDerivedKeyParams(preparedDerivedKeyType);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
provider.checkCryptoKey(baseKey, "deriveKey");
const derivedBits = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, derivedKeyType.length || 512, { keyUsage: false }, ...params);
return this.importKey("raw", derivedBits, derivedKeyType, extractable, keyUsages, ...params);
}
async exportKey(...args) {
this.checkRequiredArguments(args, 2, "exportKey");
const [format, key, ...params] = args;
this.checkCryptoKey(key);
const provider = this.getProvider(key.algorithm.name);
const result = await provider.exportKey(format, key, ...params);
return result;
}
async importKey(...args) {
this.checkRequiredArguments(args, 5, "importKey");
const [format, keyData, algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
if (["pkcs8", "spki", "raw"].indexOf(format) !== -1) {
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(keyData);
return provider.importKey(format, preparedData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
else {
if (!keyData.kty) {
throw new TypeError("keyData: Is not JSON");
}
}
return provider.importKey(format, keyData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
async wrapKey(format, key, wrappingKey, wrapAlgorithm, ...args) {
let keyData = await this.exportKey(format, key, ...args);
if (format === "jwk") {
const json = JSON.stringify(keyData);
keyData = pvtsutils.Convert.FromUtf8String(json);
}
const preparedAlgorithm = this.prepareAlgorithm(wrapAlgorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(keyData);
const provider = this.getProvider(preparedAlgorithm.name);
return provider.encrypt({ ...preparedAlgorithm, name: provider.name }, wrappingKey, preparedData, { keyUsage: false }, ...args);
}
async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages, ...args) {
const preparedAlgorithm = this.prepareAlgorithm(unwrapAlgorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(wrappedKey);
const provider = this.getProvider(preparedAlgorithm.name);
let keyData = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, unwrappingKey, preparedData, { keyUsage: false }, ...args);
if (format === "jwk") {
try {
keyData = JSON.parse(pvtsutils.Convert.ToUtf8String(keyData));
}
catch (e) {
const error = new TypeError("wrappedKey: Is not a JSON");
error.internal = e;
throw error;
}
}
return this.importKey(format, keyData, unwrappedKeyAlgorithm, extractable, keyUsages, ...args);
}
checkRequiredArguments(args, size, methodName) {
if (args.length < size) {
throw new TypeError(`Failed to execute '${methodName}' on 'SubtleCrypto': ${size} arguments required, but only ${args.length} present`);
}
}
prepareAlgorithm(algorithm) {
if (typeof algorithm === "string") {
return {
name: algorithm,
};
}
if (SubtleCrypto.isHashedAlgorithm(algorithm)) {
const preparedAlgorithm = { ...algorithm };
preparedAlgorithm.hash = this.prepareAlgorithm(algorithm.hash);
return preparedAlgorithm;
}
return { ...algorithm };
}
getProvider(name) {
const provider = this.providers.get(name);
if (!provider) {
throw new AlgorithmError("Unrecognized name");
}
return provider;
}
checkCryptoKey(key) {
if (!(key instanceof CryptoKey)) {
throw new TypeError(`Key is not of type 'CryptoKey'`);
}
}
}
let ObjectIdentifier = class ObjectIdentifier {

@@ -1229,2 +917,74 @@ constructor(value) {

class EcUtils {
static decodePoint(data, pointSize) {
const view = pvtsutils.BufferSourceConverter.toUint8Array(data);
if ((view.length === 0) || (view[0] !== 4)) {
throw new Error("Only uncompressed point format supported");
}
const n = (view.length - 1) / 2;
if (n !== (Math.ceil(pointSize / 8))) {
throw new Error("Point does not match field size");
}
const xb = view.slice(1, n + 1);
const yb = view.slice(n + 1, n + 1 + n);
return { x: xb, y: yb };
}
static encodePoint(point, pointSize) {
const size = Math.ceil(pointSize / 8);
if (point.x.byteLength !== size || point.y.byteLength !== size) {
throw new Error("X,Y coordinates don't match point size criteria");
}
const x = pvtsutils.BufferSourceConverter.toUint8Array(point.x);
const y = pvtsutils.BufferSourceConverter.toUint8Array(point.y);
const res = new Uint8Array(size * 2 + 1);
res[0] = 4;
res.set(x, 1);
res.set(y, size + 1);
return res;
}
static getSize(pointSize) {
return Math.ceil(pointSize / 8);
}
static encodeSignature(signature, pointSize) {
const size = this.getSize(pointSize);
const r = pvtsutils.BufferSourceConverter.toUint8Array(signature.r);
const s = pvtsutils.BufferSourceConverter.toUint8Array(signature.s);
const res = new Uint8Array(size * 2);
res.set(this.padStart(r, size));
res.set(this.padStart(s, size), size);
return res;
}
static decodeSignature(data, pointSize) {
const size = this.getSize(pointSize);
const view = pvtsutils.BufferSourceConverter.toUint8Array(data);
if (view.length !== (size * 2)) {
throw new Error("Incorrect size of the signature");
}
const r = view.slice(0, size);
const s = view.slice(size);
return {
r: this.trimStart(r),
s: this.trimStart(s),
};
}
static trimStart(data) {
let i = 0;
while ((i < data.length - 1) && (data[i] === 0)) {
i++;
}
if (i === 0) {
return data;
}
return data.slice(i, data.length);
}
static padStart(data, size) {
if (size === data.length) {
return data;
}
const res = new Uint8Array(size);
res.set(data, size - data.length);
return res;
}
}
class EcDsaSignature {

@@ -1236,49 +996,14 @@ constructor() {

static fromWebCryptoSignature(value) {
const wcSignature = pvtsutils.BufferSourceConverter.toUint8Array(value);
const pointSize = wcSignature.byteLength / 2;
const ecSignature = new this();
ecSignature.r = ecSignature.removePadding(wcSignature.slice(0, pointSize));
ecSignature.s = ecSignature.removePadding(wcSignature.slice(pointSize, pointSize * 2));
const pointSize = value.byteLength / 2;
const point = EcUtils.decodeSignature(value, pointSize * 8);
const ecSignature = new EcDsaSignature();
ecSignature.r = pvtsutils.BufferSourceConverter.toArrayBuffer(point.r);
ecSignature.s = pvtsutils.BufferSourceConverter.toArrayBuffer(point.s);
return ecSignature;
}
toWebCryptoSignature(pointSize) {
pointSize = this.getPointSize();
const r = this.addPadding(pointSize, pvtsutils.BufferSourceConverter.toUint8Array(this.r));
const s = this.addPadding(pointSize, pvtsutils.BufferSourceConverter.toUint8Array(this.s));
const wcSignature = new Uint8Array(r.byteLength + s.byteLength);
wcSignature.set(r, 0);
wcSignature.set(s, r.length);
return wcSignature.buffer;
pointSize !== null && pointSize !== void 0 ? pointSize : (pointSize = Math.max(this.r.byteLength, this.s.byteLength) * 8);
const signature = EcUtils.encodeSignature(this, pointSize);
return signature.buffer;
}
getPointSize() {
const size = Math.max(this.r.byteLength, this.s.byteLength);
switch (size) {
case 31:
case 32:
return 32;
case 47:
case 48:
return 48;
case 65:
case 66:
return 66;
}
throw new Error("Unsupported EC point size");
}
addPadding(pointSize, bytes) {
const res = new Uint8Array(pointSize);
const uint8Array = pvtsutils.BufferSourceConverter.toUint8Array(bytes);
res.set(uint8Array, pointSize - uint8Array.length);
return res;
}
removePadding(bytes) {
const uint8Array = pvtsutils.BufferSourceConverter.toUint8Array(bytes);
for (let i = 0; i < uint8Array.length; i++) {
if (!uint8Array[i]) {
continue;
}
return uint8Array.slice(i);
}
return new Uint8Array(0);
}
}

@@ -1302,2 +1027,22 @@ tslib.__decorate([

const idSecp256r1 = "1.2.840.10045.3.1.7";
const idEllipticCurve = "1.3.132.0";
const idSecp384r1 = `${idEllipticCurve}.34`;
const idSecp521r1 = `${idEllipticCurve}.35`;
const idSecp256k1 = `${idEllipticCurve}.10`;
const idVersionOne = "1.3.36.3.3.2.8.1.1";
const idBrainpoolP160r1 = `${idVersionOne}.1`;
const idBrainpoolP160t1 = `${idVersionOne}.2`;
const idBrainpoolP192r1 = `${idVersionOne}.3`;
const idBrainpoolP192t1 = `${idVersionOne}.4`;
const idBrainpoolP224r1 = `${idVersionOne}.5`;
const idBrainpoolP224t1 = `${idVersionOne}.6`;
const idBrainpoolP256r1 = `${idVersionOne}.7`;
const idBrainpoolP256t1 = `${idVersionOne}.8`;
const idBrainpoolP320r1 = `${idVersionOne}.9`;
const idBrainpoolP320t1 = `${idVersionOne}.10`;
const idBrainpoolP384r1 = `${idVersionOne}.11`;
const idBrainpoolP384t1 = `${idVersionOne}.12`;
const idBrainpoolP512r1 = `${idVersionOne}.13`;
const idBrainpoolP512t1 = `${idVersionOne}.14`;
const idX25519 = "1.3.101.110";

@@ -1321,2 +1066,22 @@ const idX448 = "1.3.101.111";

get CurvePrivateKey () { return CurvePrivateKey; },
idSecp256r1: idSecp256r1,
idEllipticCurve: idEllipticCurve,
idSecp384r1: idSecp384r1,
idSecp521r1: idSecp521r1,
idSecp256k1: idSecp256k1,
idVersionOne: idVersionOne,
idBrainpoolP160r1: idBrainpoolP160r1,
idBrainpoolP160t1: idBrainpoolP160t1,
idBrainpoolP192r1: idBrainpoolP192r1,
idBrainpoolP192t1: idBrainpoolP192t1,
idBrainpoolP224r1: idBrainpoolP224r1,
idBrainpoolP224t1: idBrainpoolP224t1,
idBrainpoolP256r1: idBrainpoolP256r1,
idBrainpoolP256t1: idBrainpoolP256t1,
idBrainpoolP320r1: idBrainpoolP320r1,
idBrainpoolP320t1: idBrainpoolP320t1,
idBrainpoolP384r1: idBrainpoolP384r1,
idBrainpoolP384t1: idBrainpoolP384t1,
idBrainpoolP512r1: idBrainpoolP512r1,
idBrainpoolP512t1: idBrainpoolP512t1,
idX25519: idX25519,

@@ -1328,2 +1093,362 @@ idX448: idX448,

class EcCurves {
constructor() { }
static register(item) {
const oid = new ObjectIdentifier();
oid.value = item.id;
const raw = asn1Schema.AsnConvert.serialize(oid);
this.items.push({
...item,
raw,
});
this.names.push(item.name);
}
static find(nameOrId) {
nameOrId = nameOrId.toUpperCase();
for (const item of this.items) {
if (item.name.toUpperCase() === nameOrId || item.id.toUpperCase() === nameOrId) {
return item;
}
}
return null;
}
static get(nameOrId) {
const res = this.find(nameOrId);
if (!res) {
throw new Error(`Unsupported EC named curve '${nameOrId}'`);
}
return res;
}
}
EcCurves.items = [];
EcCurves.names = [];
EcCurves.register({ name: "P-256", id: idSecp256r1, size: 256 });
EcCurves.register({ name: "P-384", id: idSecp384r1, size: 384 });
EcCurves.register({ name: "P-521", id: idSecp521r1, size: 521 });
EcCurves.register({ name: "K-256", id: idSecp256k1, size: 256 });
EcCurves.register({ name: "brainpoolP160r1", id: idBrainpoolP160r1, size: 160 });
EcCurves.register({ name: "brainpoolP160t1", id: idBrainpoolP160t1, size: 160 });
EcCurves.register({ name: "brainpoolP192r1", id: idBrainpoolP192r1, size: 192 });
EcCurves.register({ name: "brainpoolP192t1", id: idBrainpoolP192t1, size: 192 });
EcCurves.register({ name: "brainpoolP224r1", id: idBrainpoolP224r1, size: 224 });
EcCurves.register({ name: "brainpoolP224t1", id: idBrainpoolP224t1, size: 224 });
EcCurves.register({ name: "brainpoolP256r1", id: idBrainpoolP256r1, size: 256 });
EcCurves.register({ name: "brainpoolP256t1", id: idBrainpoolP256t1, size: 256 });
EcCurves.register({ name: "brainpoolP320r1", id: idBrainpoolP320r1, size: 320 });
EcCurves.register({ name: "brainpoolP320t1", id: idBrainpoolP320t1, size: 320 });
EcCurves.register({ name: "brainpoolP384r1", id: idBrainpoolP384r1, size: 384 });
EcCurves.register({ name: "brainpoolP384t1", id: idBrainpoolP384t1, size: 384 });
EcCurves.register({ name: "brainpoolP512r1", id: idBrainpoolP512r1, size: 512 });
EcCurves.register({ name: "brainpoolP512t1", id: idBrainpoolP512t1, size: 512 });
class HmacProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HMAC";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["sign", "verify"];
}
getDefaultLength(algName) {
switch (algName.toUpperCase()) {
case "SHA-1":
case "SHA-256":
case "SHA-384":
case "SHA-512":
return 512;
default:
throw new Error(`Unknown algorithm name '${algName}'`);
}
}
checkGenerateKeyParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
if ("length" in algorithm) {
if (typeof algorithm.length !== "number") {
throw new TypeError("length: Is not a Number");
}
if (algorithm.length < 1) {
throw new RangeError("length: Number is out of range");
}
}
}
checkImportParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
}
}
class Pbkdf2Provider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "PBKDF2";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveBits", "deriveKey"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!(algorithm.salt instanceof ArrayBuffer || ArrayBuffer.isView(algorithm.salt))) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "iterations");
if (typeof algorithm.iterations !== "number") {
throw new TypeError("iterations: Is not a Number");
}
if (algorithm.iterations < 1) {
throw new TypeError("iterations: Is less than 1");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class HkdfProvider extends ProviderCrypto {
constructor() {
super(...arguments);
this.name = "HKDF";
this.hashAlgorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
this.usages = ["deriveKey", "deriveBits"];
}
checkAlgorithmParams(algorithm) {
this.checkRequiredProperty(algorithm, "hash");
this.checkHashAlgorithm(algorithm.hash, this.hashAlgorithms);
this.checkRequiredProperty(algorithm, "salt");
if (!pvtsutils.BufferSourceConverter.isBufferSource(algorithm.salt)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
this.checkRequiredProperty(algorithm, "info");
if (!pvtsutils.BufferSourceConverter.isBufferSource(algorithm.info)) {
throw new TypeError("salt: Is not of type '(ArrayBuffer or ArrayBufferView)'");
}
}
checkImportKey(format, keyData, algorithm, extractable, keyUsages, ...args) {
super.checkImportKey(format, keyData, algorithm, extractable, keyUsages);
if (extractable) {
throw new SyntaxError("extractable: Must be 'false'");
}
}
}
class Crypto {
get [Symbol.toStringTag]() {
return "Crypto";
}
}
class ProviderStorage {
constructor() {
this.items = {};
}
get(algorithmName) {
return this.items[algorithmName.toLowerCase()] || null;
}
set(provider) {
this.items[provider.name.toLowerCase()] = provider;
}
removeAt(algorithmName) {
const provider = this.get(algorithmName.toLowerCase());
if (provider) {
delete this.items[algorithmName];
}
return provider;
}
has(name) {
return !!this.get(name);
}
get length() {
return Object.keys(this.items).length;
}
get algorithms() {
const algorithms = [];
for (const key in this.items) {
const provider = this.items[key];
algorithms.push(provider.name);
}
return algorithms.sort();
}
}
class SubtleCrypto {
constructor() {
this.providers = new ProviderStorage();
}
static isHashedAlgorithm(data) {
return data
&& typeof data === "object"
&& "name" in data
&& "hash" in data
? true
: false;
}
get [Symbol.toStringTag]() {
return "SubtleCrypto";
}
async digest(...args) {
this.checkRequiredArguments(args, 2, "digest");
const [algorithm, data, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.digest(preparedAlgorithm, preparedData, ...params);
return result;
}
async generateKey(...args) {
this.checkRequiredArguments(args, 3, "generateKey");
const [algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.generateKey({ ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
return result;
}
async sign(...args) {
this.checkRequiredArguments(args, 3, "sign");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.sign({ ...preparedAlgorithm, name: provider.name }, key, preparedData, ...params);
return result;
}
async verify(...args) {
this.checkRequiredArguments(args, 4, "verify");
const [algorithm, key, signature, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const preparedSignature = pvtsutils.BufferSourceConverter.toArrayBuffer(signature);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.verify({ ...preparedAlgorithm, name: provider.name }, key, preparedSignature, preparedData, ...params);
return result;
}
async encrypt(...args) {
this.checkRequiredArguments(args, 3, "encrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.encrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async decrypt(...args) {
this.checkRequiredArguments(args, 3, "decrypt");
const [algorithm, key, data, ...params] = args;
this.checkCryptoKey(key);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(data);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, key, preparedData, { keyUsage: true }, ...params);
return result;
}
async deriveBits(...args) {
this.checkRequiredArguments(args, 3, "deriveBits");
const [algorithm, baseKey, length, ...params] = args;
this.checkCryptoKey(baseKey);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
const result = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, length, { keyUsage: true }, ...params);
return result;
}
async deriveKey(...args) {
this.checkRequiredArguments(args, 5, "deriveKey");
const [algorithm, baseKey, derivedKeyType, extractable, keyUsages, ...params] = args;
const preparedDerivedKeyType = this.prepareAlgorithm(derivedKeyType);
const importProvider = this.getProvider(preparedDerivedKeyType.name);
importProvider.checkDerivedKeyParams(preparedDerivedKeyType);
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
provider.checkCryptoKey(baseKey, "deriveKey");
const derivedBits = await provider.deriveBits({ ...preparedAlgorithm, name: provider.name }, baseKey, derivedKeyType.length || 512, { keyUsage: false }, ...params);
return this.importKey("raw", derivedBits, derivedKeyType, extractable, keyUsages, ...params);
}
async exportKey(...args) {
this.checkRequiredArguments(args, 2, "exportKey");
const [format, key, ...params] = args;
this.checkCryptoKey(key);
const provider = this.getProvider(key.algorithm.name);
const result = await provider.exportKey(format, key, ...params);
return result;
}
async importKey(...args) {
this.checkRequiredArguments(args, 5, "importKey");
const [format, keyData, algorithm, extractable, keyUsages, ...params] = args;
const preparedAlgorithm = this.prepareAlgorithm(algorithm);
const provider = this.getProvider(preparedAlgorithm.name);
if (["pkcs8", "spki", "raw"].indexOf(format) !== -1) {
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(keyData);
return provider.importKey(format, preparedData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
else {
if (!keyData.kty) {
throw new TypeError("keyData: Is not JSON");
}
}
return provider.importKey(format, keyData, { ...preparedAlgorithm, name: provider.name }, extractable, keyUsages, ...params);
}
async wrapKey(format, key, wrappingKey, wrapAlgorithm, ...args) {
let keyData = await this.exportKey(format, key, ...args);
if (format === "jwk") {
const json = JSON.stringify(keyData);
keyData = pvtsutils.Convert.FromUtf8String(json);
}
const preparedAlgorithm = this.prepareAlgorithm(wrapAlgorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(keyData);
const provider = this.getProvider(preparedAlgorithm.name);
return provider.encrypt({ ...preparedAlgorithm, name: provider.name }, wrappingKey, preparedData, { keyUsage: false }, ...args);
}
async unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages, ...args) {
const preparedAlgorithm = this.prepareAlgorithm(unwrapAlgorithm);
const preparedData = pvtsutils.BufferSourceConverter.toArrayBuffer(wrappedKey);
const provider = this.getProvider(preparedAlgorithm.name);
let keyData = await provider.decrypt({ ...preparedAlgorithm, name: provider.name }, unwrappingKey, preparedData, { keyUsage: false }, ...args);
if (format === "jwk") {
try {
keyData = JSON.parse(pvtsutils.Convert.ToUtf8String(keyData));
}
catch (e) {
const error = new TypeError("wrappedKey: Is not a JSON");
error.internal = e;
throw error;
}
}
return this.importKey(format, keyData, unwrappedKeyAlgorithm, extractable, keyUsages, ...args);
}
checkRequiredArguments(args, size, methodName) {
if (args.length < size) {
throw new TypeError(`Failed to execute '${methodName}' on 'SubtleCrypto': ${size} arguments required, but only ${args.length} present`);
}
}
prepareAlgorithm(algorithm) {
if (typeof algorithm === "string") {
return {
name: algorithm,
};
}
if (SubtleCrypto.isHashedAlgorithm(algorithm)) {
const preparedAlgorithm = { ...algorithm };
preparedAlgorithm.hash = this.prepareAlgorithm(algorithm.hash);
return preparedAlgorithm;
}
return { ...algorithm };
}
getProvider(name) {
const provider = this.providers.get(name);
if (!provider) {
throw new AlgorithmError("Unrecognized name");
}
return provider;
}
checkCryptoKey(key) {
if (!(key instanceof CryptoKey)) {
throw new TypeError(`Key is not of type 'CryptoKey'`);
}
}
}
var index = /*#__PURE__*/Object.freeze({

@@ -1336,5 +1461,3 @@ __proto__: null,

enumerable: true,
get: function () {
return pvtsutils.BufferSourceConverter;
}
get: function () { return pvtsutils.BufferSourceConverter; }
});

@@ -1353,2 +1476,4 @@ exports.AesCbcProvider = AesCbcProvider;

exports.DesProvider = DesProvider;
exports.EcCurves = EcCurves;
exports.EcUtils = EcUtils;
exports.EcdhEsProvider = EcdhEsProvider;

@@ -1355,0 +1480,0 @@ exports.EcdhProvider = EcdhProvider;

{
"name": "webcrypto-core",
"version": "1.2.1",
"version": "1.3.0",
"description": "Common layer to be used by crypto libraries based on WebCrypto API for input validation.",

@@ -58,13 +58,12 @@ "main": "build/webcrypto-core.js",

"@types/mocha": "^9.0.0",
"@types/node": "^14.17.12",
"@types/node": "^16.11.4",
"coveralls": "^3.1.1",
"mocha": "^9.1.1",
"mocha": "^9.1.3",
"nyc": "^15.1.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rollup": "^2.56.3",
"rollup": "^2.58.1",
"rollup-plugin-typescript2": "^0.30.0",
"ts-node": "^10.2.1",
"ts-node": "^10.4.0",
"tslint": "^6.1.3",
"typescript": "^4.4.2"
"typescript": "^4.4.4"
},

@@ -71,0 +70,0 @@ "author": "PeculiarVentures",

@@ -53,3 +53,3 @@ [![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/PeculiarVentures/webcrypto-core/master/LICENSE)

class Crypto {
class Crypto extends core.Crypto {

@@ -56,0 +56,0 @@ constructor() {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc