26
26
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
27
*/
28
28
29
+ // The Node.js crypto module is used as a fallback for the Web Crypto API. When
30
+ // building for the browser, inclusion of the crypto module should be disabled,
31
+ // which the package hints at in its package.json for bundlers that support it.
32
+ import nodeCrypto from "crypto" ;
33
+
29
34
/**
30
35
* The random implementation to use as a fallback.
31
36
* @type {?function(number):!Array.<number> }
@@ -41,18 +46,16 @@ var randomFallback = null;
41
46
* @throws {Error } If no random implementation is available
42
47
* @inner
43
48
*/
44
- function random ( len ) {
45
- // Web Crypto API
49
+ function randomBytes ( len ) {
50
+ // Web Crypto API. Globally available in the browser and in Node.js >=23.
46
51
try {
47
52
return crypto . getRandomValues ( new Uint8Array ( len ) ) ;
48
53
} catch { }
49
- // Node.js crypto
50
- if ( typeof require === "function" ) {
51
- try {
52
- return require ( "crypto" ) . randomBytes ( len ) ;
53
- } catch { }
54
- }
55
- // Fallback
54
+ // Node.js crypto module for non-browser environments.
55
+ try {
56
+ return nodeCrypto . randomBytes ( len ) ;
57
+ } catch { }
58
+ // Custom fallback specified with `setRandomFallback`.
56
59
if ( ! randomFallback ) {
57
60
throw Error (
58
61
"Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative" ,
@@ -97,7 +100,7 @@ export function genSaltSync(rounds, seed_length) {
97
100
if ( rounds < 10 ) salt . push ( "0" ) ;
98
101
salt . push ( rounds . toString ( ) ) ;
99
102
salt . push ( "$" ) ;
100
- salt . push ( base64_encode ( random ( BCRYPT_SALT_LEN ) , BCRYPT_SALT_LEN ) ) ; // May throw
103
+ salt . push ( base64_encode ( randomBytes ( BCRYPT_SALT_LEN ) , BCRYPT_SALT_LEN ) ) ; // May throw
101
104
return salt . join ( "" ) ;
102
105
}
103
106
0 commit comments