UNPKG

@peculiar/webcrypto

Version:
76 lines (75 loc) • 2.81 kB
/** * Copyright (c) 2019-2026, Peculiar Ventures * SPDX-License-Identifier: MIT */ import { getCryptoKey, setCryptoKey } from "../storage.js"; import { RsaPrivateKey } from "./private_key.js"; import { RsaPublicKey } from "./public_key.js"; import { RsaCrypto } from "./crypto.js"; import * as core from "webcrypto-core"; import crypto from "node:crypto"; import { convert, toArrayBuffer, toUint8Array } from "@peculiar/utils"; // src/mechs/rsa/rsa_es.ts var RsaEsProvider = class extends core.ProviderCrypto { name = "RSAES-PKCS1-v1_5"; usages = { publicKey: ["encrypt", "wrapKey"], privateKey: ["decrypt", "unwrapKey"] }; async onGenerateKey(algorithm, extractable, keyUsages) { const keys = await RsaCrypto.generateKey({ ...algorithm, name: this.name }, extractable, keyUsages); return { privateKey: setCryptoKey(keys.privateKey), publicKey: setCryptoKey(keys.publicKey) }; } checkGenerateKeyParams(algorithm) { this.checkRequiredProperty(algorithm, "publicExponent"); if (!(algorithm.publicExponent && algorithm.publicExponent instanceof Uint8Array)) throw new TypeError("publicExponent: Missing or not a Uint8Array"); const publicExponent = convert.encode("base64", algorithm.publicExponent); if (!(publicExponent === "Aw==" || publicExponent === "AQAB")) throw new TypeError("publicExponent: Must be [3] or [1,0,1]"); this.checkRequiredProperty(algorithm, "modulusLength"); switch (algorithm.modulusLength) { case 1024: case 2048: case 4096: break; default: throw new TypeError("modulusLength: Must be 1024, 2048, or 4096"); } } async onEncrypt(algorithm, key, data) { const options = this.toCryptoOptions(key); const enc = crypto.publicEncrypt(options, toUint8Array(data)); return toArrayBuffer(enc); } async onDecrypt(algorithm, key, data) { const options = this.toCryptoOptions(key); const dec = crypto.privateDecrypt(options, toUint8Array(data)); return toArrayBuffer(dec); } async onExportKey(format, key) { return RsaCrypto.exportKey(format, getCryptoKey(key)); } async onImportKey(format, keyData, algorithm, extractable, keyUsages) { const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); return setCryptoKey(key); } checkCryptoKey(key, keyUsage) { super.checkCryptoKey(key, keyUsage); const internalKey = getCryptoKey(key); if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) throw new TypeError("key: Is not RSA CryptoKey"); } toCryptoOptions(key) { const type = key.type.toUpperCase(); return { key: `-----BEGIN ${type} KEY-----\n${getCryptoKey(key).data.toString("base64")}\n-----END ${type} KEY-----`, padding: crypto.constants.RSA_PKCS1_PADDING }; } }; export { RsaEsProvider };