* Generates cryptographically secure random bytes. * @function * @param {number} len Bytes length * @returns {!Array. } Random bytes * @throws {Error} If no random implementation is available * @inner
(len)
| 47 | * @inner |
| 48 | */ |
| 49 | function randomBytes(len) { |
| 50 | // Web Crypto API. Globally available in the browser and in Node.js >=23. |
| 51 | try { |
| 52 | return crypto.getRandomValues(new Uint8Array(len)); |
| 53 | } catch {} |
| 54 | // Node.js crypto module for non-browser environments. |
| 55 | try { |
| 56 | return nodeCrypto.randomBytes(len); |
| 57 | } catch {} |
| 58 | // Custom fallback specified with `setRandomFallback`. |
| 59 | if (!randomFallback) { |
| 60 | throw Error( |
| 61 | "Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative", |
| 62 | ); |
| 63 | } |
| 64 | return randomFallback(len); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto |