@peculiar/webcrypto
Version:
A WebCrypto Polyfill for NodeJS
195 lines (194 loc) • 7.7 kB
JavaScript
/**
* Copyright (c) 2019-2026, Peculiar Ventures
* SPDX-License-Identifier: MIT
*/
import { RsaPrivateKey } from "./private_key.js";
import { RsaPublicKey } from "./public_key.js";
import * as core from "webcrypto-core";
import { Buffer } from "node:buffer";
import crypto from "node:crypto";
import { JsonParser, JsonSerializer } from "@peculiar/json-schema";
import { assertBufferSource, toArrayBuffer, toUint8Array } from "@peculiar/utils";
import { AsnParser, AsnSerializer } from "@peculiar/asn1-schema";
// src/mechs/rsa/crypto.ts
var RsaCrypto = class {
static publicKeyUsages = [
"verify",
"encrypt",
"wrapKey"
];
static privateKeyUsages = [
"sign",
"decrypt",
"unwrapKey"
];
static async generateKey(algorithm, extractable, keyUsages) {
const privateKey = new RsaPrivateKey();
privateKey.algorithm = algorithm;
privateKey.extractable = extractable;
privateKey.usages = keyUsages.filter((usage) => this.privateKeyUsages.indexOf(usage) !== -1);
const publicKey = new RsaPublicKey();
publicKey.algorithm = algorithm;
publicKey.extractable = true;
publicKey.usages = keyUsages.filter((usage) => this.publicKeyUsages.indexOf(usage) !== -1);
const publicExponent = Buffer.concat([Buffer.alloc(4 - algorithm.publicExponent.byteLength, 0), Buffer.from(algorithm.publicExponent)]).readInt32BE(0);
const keys = crypto.generateKeyPairSync("rsa", {
modulusLength: algorithm.modulusLength,
publicExponent,
publicKeyEncoding: {
format: "der",
type: "spki"
},
privateKeyEncoding: {
format: "der",
type: "pkcs8"
}
});
privateKey.data = keys.privateKey;
publicKey.data = keys.publicKey;
return {
privateKey,
publicKey
};
}
static async exportKey(format, key) {
switch (format.toLowerCase()) {
case "jwk": return JsonSerializer.toJSON(key);
case "pkcs8":
case "spki": return toArrayBuffer(key.data);
default: throw new core.OperationError("format: Must be 'jwk', 'pkcs8' or 'spki'");
}
}
static async importKey(format, keyData, algorithm, extractable, keyUsages) {
switch (format.toLowerCase()) {
case "jwk": if (keyData.d) {
const asnKey = JsonParser.fromJSON(keyData, { targetSchema: core.asn1.RsaPrivateKey });
return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages);
} else {
const asnKey = JsonParser.fromJSON(keyData, { targetSchema: core.asn1.RsaPublicKey });
return this.importPublicKey(asnKey, algorithm, extractable, keyUsages);
}
case "spki": {
assertBufferSource(keyData);
const keyInfo = AsnParser.parse(toUint8Array(keyData), core.asn1.PublicKeyInfo);
const asnKey = AsnParser.parse(keyInfo.publicKey, core.asn1.RsaPublicKey);
return this.importPublicKey(asnKey, algorithm, extractable, keyUsages);
}
case "pkcs8": {
assertBufferSource(keyData);
const keyInfo = AsnParser.parse(toUint8Array(keyData), core.asn1.PrivateKeyInfo);
const asnKey = AsnParser.parse(keyInfo.privateKey, core.asn1.RsaPrivateKey);
return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages);
}
default: throw new core.OperationError("format: Must be 'jwk', 'pkcs8' or 'spki'");
}
}
static async sign(algorithm, key, data) {
switch (algorithm.name.toUpperCase()) {
case "RSA-PSS":
case "RSASSA-PKCS1-V1_5": return this.signRsa(algorithm, key, data);
default: throw new core.OperationError("algorithm: Is not recognized");
}
}
static async verify(algorithm, key, signature, data) {
switch (algorithm.name.toUpperCase()) {
case "RSA-PSS":
case "RSASSA-PKCS1-V1_5": return this.verifySSA(algorithm, key, data, signature);
default: throw new core.OperationError("algorithm: Is not recognized");
}
}
static async encrypt(algorithm, key, data) {
switch (algorithm.name.toUpperCase()) {
case "RSA-OAEP": return this.encryptOAEP(algorithm, key, data);
default: throw new core.OperationError("algorithm: Is not recognized");
}
}
static async decrypt(algorithm, key, data) {
switch (algorithm.name.toUpperCase()) {
case "RSA-OAEP": return this.decryptOAEP(algorithm, key, data);
default: throw new core.OperationError("algorithm: Is not recognized");
}
}
static importPrivateKey(asnKey, algorithm, extractable, keyUsages) {
const keyInfo = new core.asn1.PrivateKeyInfo();
keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1";
keyInfo.privateKeyAlgorithm.parameters = null;
keyInfo.privateKey = AsnSerializer.serialize(asnKey);
const key = new RsaPrivateKey();
key.data = Buffer.from(AsnSerializer.serialize(keyInfo));
key.algorithm = Object.assign({}, algorithm);
key.algorithm.publicExponent = new Uint8Array(asnKey.publicExponent);
key.algorithm.modulusLength = asnKey.modulus.byteLength << 3;
key.extractable = extractable;
key.usages = keyUsages;
return key;
}
static importPublicKey(asnKey, algorithm, extractable, keyUsages) {
const keyInfo = new core.asn1.PublicKeyInfo();
keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1";
keyInfo.publicKeyAlgorithm.parameters = null;
keyInfo.publicKey = AsnSerializer.serialize(asnKey);
const key = new RsaPublicKey();
key.data = Buffer.from(AsnSerializer.serialize(keyInfo));
key.algorithm = Object.assign({}, algorithm);
key.algorithm.publicExponent = new Uint8Array(asnKey.publicExponent);
key.algorithm.modulusLength = asnKey.modulus.byteLength << 3;
key.extractable = extractable;
key.usages = keyUsages;
return key;
}
static getCryptoAlgorithm(alg) {
switch (alg.hash.name.toUpperCase()) {
case "SHA-1": return "RSA-SHA1";
case "SHA-256": return "RSA-SHA256";
case "SHA-384": return "RSA-SHA384";
case "SHA-512": return "RSA-SHA512";
case "SHA3-256": return "RSA-SHA3-256";
case "SHA3-384": return "RSA-SHA3-384";
case "SHA3-512": return "RSA-SHA3-512";
default: throw new core.OperationError("algorithm.hash: Is not recognized");
}
}
static signRsa(algorithm, key, data) {
const cryptoAlg = this.getCryptoAlgorithm(key.algorithm);
const signer = crypto.createSign(cryptoAlg);
signer.update(Buffer.from(data));
if (!key.pem) key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`;
const options = { key: key.pem };
if (algorithm.name.toUpperCase() === "RSA-PSS") {
options.padding = crypto.constants.RSA_PKCS1_PSS_PADDING;
options.saltLength = algorithm.saltLength;
}
const signature = signer.sign(options);
return toArrayBuffer(signature);
}
static verifySSA(algorithm, key, data, signature) {
const cryptoAlg = this.getCryptoAlgorithm(key.algorithm);
const signer = crypto.createVerify(cryptoAlg);
signer.update(Buffer.from(data));
if (!key.pem) key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`;
const options = { key: key.pem };
if (algorithm.name.toUpperCase() === "RSA-PSS") {
options.padding = crypto.constants.RSA_PKCS1_PSS_PADDING;
options.saltLength = algorithm.saltLength;
}
return signer.verify(options, signature);
}
static encryptOAEP(algorithm, key, data) {
const options = {
key: `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
};
if (algorithm.label) {}
return toArrayBuffer(crypto.publicEncrypt(options, data));
}
static decryptOAEP(algorithm, key, data) {
const options = {
key: `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
};
if (algorithm.label) {}
return toArrayBuffer(crypto.privateDecrypt(options, data));
}
};
export { RsaCrypto };