@peculiar/webcrypto
Version:
A WebCrypto Polyfill for NodeJS
72 lines (71 loc) • 2.64 kB
JavaScript
/**
* Copyright (c) 2019-2026, Peculiar Ventures
* SPDX-License-Identifier: MIT
*/
import { getCryptoKey, setCryptoKey } from "../storage.js";
import { ShaCrypto } from "../sha/crypto.js";
import { HmacCryptoKey } from "./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";
// src/mechs/hmac/hmac.ts
var HmacProvider = class extends core.HmacProvider {
async onGenerateKey(algorithm, extractable, keyUsages) {
const length = (algorithm.length || this.getDefaultLength(algorithm.hash.name)) >> 3 << 3;
const key = new HmacCryptoKey();
key.algorithm = {
...algorithm,
length,
name: this.name
};
key.extractable = extractable;
key.usages = keyUsages;
key.data = crypto.randomBytes(length >> 3);
return setCryptoKey(key);
}
async onSign(algorithm, key, data) {
const cryptoAlg = ShaCrypto.getAlgorithmName(key.algorithm.hash);
const hmac = crypto.createHmac(cryptoAlg, getCryptoKey(key).data).update(Buffer.from(toUint8Array(data))).digest();
return toArrayBuffer(hmac);
}
async onVerify(algorithm, key, signature, data) {
const cryptoAlg = ShaCrypto.getAlgorithmName(key.algorithm.hash);
return crypto.createHmac(cryptoAlg, getCryptoKey(key).data).update(Buffer.from(toUint8Array(data))).digest().compare(Buffer.from(toUint8Array(signature))) === 0;
}
async onImportKey(format, keyData, algorithm, extractable, keyUsages) {
let key;
switch (format.toLowerCase()) {
case "jwk":
key = JsonParser.fromJSON(keyData, { targetSchema: HmacCryptoKey });
break;
case "raw":
assertBufferSource(keyData);
key = new HmacCryptoKey();
key.data = Buffer.from(toUint8Array(keyData));
break;
default: throw new core.OperationError("format: Must be 'jwk' or 'raw'");
}
key.algorithm = {
hash: { name: algorithm.hash.name },
name: this.name,
length: key.data.length << 3
};
key.extractable = extractable;
key.usages = keyUsages;
return setCryptoKey(key);
}
async onExportKey(format, key) {
switch (format.toLowerCase()) {
case "jwk": return JsonSerializer.toJSON(getCryptoKey(key));
case "raw": return toArrayBuffer(getCryptoKey(key).data);
default: throw new core.OperationError("format: Must be 'jwk' or 'raw'");
}
}
checkCryptoKey(key, keyUsage) {
super.checkCryptoKey(key, keyUsage);
if (!(getCryptoKey(key) instanceof HmacCryptoKey)) throw new TypeError("key: Is not HMAC CryptoKey");
}
};
export { HmacProvider };