You can use the builtin crypto.randomUUID()
to generate UUIDv4 (version 4).
That's a 36 characters long string (288-bit) that encode a 128 bits UUID.
Of those 128 bits, only 122 bits are random, 4 bits are used to encode the UUID version (always version 4 for randomUUID()
), and 2 other bits are fixed, so you lose 6 bits of randomness in total.
const crypto = require('crypto')
crypto.randomUUID()
'5a388e8e-09eb-4778-a242-ea663f3c7e5e'
The first 4
in -4478-
indicates that it's a UUID version 4, that's 4 bits that are not random.
The first two bits of -a242-
are fixed to 10
by the RFC spec, so those are not random either.
In total you have 122-bits of randomness in if you use UUIDv4 as a nonce.
You could generate a 128-bits totally random nonce with crypto.randomBytes(16)
and encode it in either base64url (22 characters), base64 (24 characters), or hex (32 characters), all of those are shorter that UUIDv4 which is 36 characters.
UUIDv4 is longer (less compact) and has less random bits, but it's easier to read when you are troubleshooting and are easily recognizable as a random value.
crypto.randomUUID() # 36 characters
'5a388e8e-09eb-4778-a242-ea663f3c7e5e'
var nonce128bitvalue = crypto.randomBytes(16) # 16 * 8 = 128 bits
nonce128bitvalue.toString('base64url') # 22 characters long
'q-UBP7J_AqOn1BWTBq1Tfw'
nonce128bitvalue.toString('base64') # 24 characters long
'q+UBP7J/AqOn1BWTBq1Tfw=='
nonce128bitvalue.toString('hex') # 36 characters long
'abe5013fb27f02a3a7d4159306ad537f'
As stated in the crypto.randomUUID()
documentation:
Generates a random RFC 4122 version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator.