diff --git a/packages/crypto/src/pbkdf2.ts b/packages/crypto/src/pbkdf2.ts index 110b16e265..889e652056 100644 --- a/packages/crypto/src/pbkdf2.ts +++ b/packages/crypto/src/pbkdf2.ts @@ -10,10 +10,14 @@ import { sha512 as nobleSha512 } from "@noble/hashes/sha512"; * `undefined` in that case. */ export async function getCryptoModule(): Promise { + const g: any = globalThis; + if (g.crypto) { + return g.crypto; + } try { - const crypto = await import("crypto"); + const crypto = await require("crypto"); // We get `Object{default: Object{}}` as a fallback when using - // `crypto: false` in Webpack 5, which we interprete as unavailable. + // `crypto: false` in Webpack 5, which we interpret as unavailable. if (typeof crypto === "object" && Object.keys(crypto).length <= 1) { return undefined; } @@ -24,15 +28,12 @@ export async function getCryptoModule(): Promise { } export async function getSubtle(): Promise { - const g: any = globalThis; - let subtle = g.crypto && g.crypto.subtle; - if (!subtle) { - const crypto = await getCryptoModule(); - if (crypto && crypto.webcrypto && crypto.webcrypto.subtle) { - subtle = crypto.webcrypto.subtle; - } + const crypto = await getCryptoModule(); + if (crypto && crypto.subtle) { + return crypto.subtle; + } else if (crypto.webcrypto && crypto.webcrypto.subtle) { + return crypto.webcrypto.subtle; } - return subtle; } export async function pbkdf2Sha512Subtle( @@ -108,12 +109,11 @@ export async function pbkdf2Sha512( const subtle = await getSubtle(); if (subtle) { return pbkdf2Sha512Subtle(subtle, secret, salt, iterations, keylen); + } + const crypto = await getCryptoModule(); + if (crypto) { + return pbkdf2Sha512Crypto(crypto, secret, salt, iterations, keylen); } else { - const crypto = await getCryptoModule(); - if (crypto) { - return pbkdf2Sha512Crypto(crypto, secret, salt, iterations, keylen); - } else { - return pbkdf2Sha512Noble(secret, salt, iterations, keylen); - } + return pbkdf2Sha512Noble(secret, salt, iterations, keylen); } }