Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a unique 8 digit number using crypto in node js?

I want to generate a unique number everytime. I have used crypto module for that.

const alphanu = crypto.randomBytes(16).toString('hex')

This will generate alphanumeric string of length 32. I want to generate a number of length 8.

I tried randomInt as well.

const num = crypto.randomInt(10000000,99999999)

Will it always generate a unique number?

How do I achieve what I want?

like image 530
Renee Avatar asked Sep 15 '25 22:09

Renee


1 Answers

Your "unique" requirement will be harder to achieve than you think. If you meant "non-deterministic", then just use crypto.randomInt() as you did in your question:

crypto.randomInt(10**7, 10**8-1) // 8 digit, no leading zeroes
crypto.randomInt(0, 10**8-1).toString().padStart(8, "0") // 8 digits, allows leading zeroes

Technically speaking, this is psuedorandom, not random. However, for most use cases, you won't be able to tell the difference.

Now if you need unique, then here's two fairly easy approaches you could use:

  1. Store every number you've already used in a database, or
  2. Start at 0 and increment by one each time and add leading zeroes if necessary (or start at 10^7 if you don't want leading zeroes). With this, all you need to do is store the last number used. However, with this approach, the result is deterministic, which might be a security drawback depending on your use case.
like image 162
Michael M. Avatar answered Sep 18 '25 14:09

Michael M.