UNPKG

@nfen/webcrypto-ts

Version:
62 lines 2.73 kB
/** * Wrapper for node/browser webcrypto * @module */ class CryptoLoader { static async load() { // @ts-ignore return typeof crypto !== "undefined" // Should match node which includes crypto and window.crypto ? Promise.resolve(crypto) : await (await import("node:crypto")).webcrypto; } } /** * Crypto loader which loads native webcrypto depending on environment */ export const _crypto = CryptoLoader.load(); export async function encrypt(algorithm, key, data) { return await (await _crypto).subtle.encrypt(algorithm, key, data); } export async function decrypt(algorithm, key, data) { return await (await _crypto).subtle.decrypt(algorithm, key, data); } export async function sign(algorithm, key, data) { return await (await _crypto).subtle.sign(algorithm, key, data); } export async function verify(algorithm, key, signature, data) { return await (await _crypto).subtle.verify(algorithm, key, signature, data); } export async function deriveKey(algorithm, key, derivedKeyType, extractable, keyUsages) { return (await (await _crypto).subtle.deriveKey(algorithm, key, derivedKeyType, extractable, keyUsages)); } export async function deriveBits(algorithm, baseKey, length) { if (length % 8 !== 0) { throw new RangeError("Length must be a multiple of 8"); } return await (await _crypto).subtle.deriveBits(algorithm, baseKey, length); } export async function wrapKey(format, key, wrappingKey, wrapAlgorithm) { return await (await _crypto).subtle.wrapKey(format, key, wrappingKey, wrapAlgorithm); } export async function unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) { return await (await _crypto).subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages); } export async function exportKey(format, key) { if (format === "jwk") { return await (await _crypto).subtle.exportKey(format, key); } return await (await _crypto).subtle.exportKey(format, key); } export async function importKey(format, key, algorithm, extractable, keyUsages) { if (format === "jwk") { return (await (await _crypto).subtle.importKey(format, key, algorithm, extractable, keyUsages)); } return (await (await _crypto).subtle.importKey(format, key, algorithm, extractable, keyUsages)); } export async function generateKey(algorithm, extractable, keyUsages) { return (await (await _crypto).subtle.generateKey(algorithm, extractable, keyUsages)); } export async function digest(algorithm, data) { return (await (await _crypto).subtle.digest(algorithm, data)); } //# sourceMappingURL=webcrypto.js.map