const { randomBytes } = await import('node:crypto')
const buf = randomBytes(256)
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`)

crypto.randomBytes() is a cryptographically secure random number generator based on openssl. Depending on the operating system of the user, randomBytes will use /dev/urandom (Unix) or CryptoGenRandom (Windows).

While still pseudo-random sources, the important thing is that they are not guessable by an attacker. In other words, after using crypto.randomBytes() to generate a secret key for AES-256 encryption, no one will be able to guess the key.

Should I always use crypto.randomBytes()? No. There are dangers if you implement your random number generator on top of a low-level API like random bytes. Because it returns bytes and not numbers, it’s up to you to convert the bytes into numbers. If you make a mistake, it can result in a vulnerability in your system.

In short, use crypto.randomBytes() whenever you need raw bytes. If you need a number within a range, for example, a random number between 0 and 9, then use a non-biased function that uses crypto.randomBytes() as the source of entropy: node-random-number-csprng

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee


Reference:

  1. crypto.randomBytes(size[, callback])