Throw if WebCrypto API is not available

It was already required, this simply makes errors more clear.
This commit is contained in:
larabr 2024-02-06 15:41:40 +01:00
parent 3320eaccb2
commit 280828dae6
2 changed files with 12 additions and 7 deletions

View File

@ -7,14 +7,12 @@ import enums from '../enums';
import util from '../util';
const webCrypto = util.getWebCrypto();
const nodeCrypto = util.getNodeCrypto();
export default async function computeHKDF(hashAlgo, inputKey, salt, info, outLen) {
const hash = enums.read(enums.webHash, hashAlgo);
if (!hash) throw new Error('Hash algo not supported with HKDF');
const crypto = webCrypto || nodeCrypto.webcrypto.subtle;
const importedKey = await crypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);
const bits = await crypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);
const importedKey = await webCrypto.importKey('raw', inputKey, 'HKDF', false, ['deriveBits']);
const bits = await webCrypto.deriveBits({ name: 'HKDF', hash, salt, info }, importedKey, outLen * 8);
return new Uint8Array(bits);
}

View File

@ -420,11 +420,18 @@ const util = {
},
/**
* Get native Web Cryptography api, only the current version of the spec.
* @returns {Object} The SubtleCrypto api or 'undefined'.
* Get native Web Cryptography API.
* @returns {Object} The SubtleCrypto API
* @throws if the API is not available
*/
getWebCrypto: function() {
return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
const globalWebCrypto = typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle;
// Fallback for Node 16, which does not expose WebCrypto as a global
const webCrypto = globalWebCrypto || this.getNodeCrypto()?.webcrypto.subtle;
if (!webCrypto) {
throw new Error('The WebCrypto API is not available');
}
return webCrypto;
},
/**