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?
3
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: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:
To make a random and unique number, you’re going to have to mix
.random()
and a time stamp together.Here’s a simple UID generator I’ve been using for a while now, I’ve modified the
.substring()
so that it returns 8 characters.For guaranteed unique numbers you are right to use encryption. Because encryption is one-to-one then unique inputs guarantee unique outputs. Just encrypt 0, 1, 2, 3, … with the same key (and IV if used) and you will get unique numbers out.
You want 8 digit numbers, so the output range is 0 .. 99,999,999. That is a 27 bit number. You could use a 32 bit encryption (which gives 10 digits) with cycle walking to get numbers within range. If the cycle walking takes too long, then you could either accept a 10 digit output or write a simple 28-bit Feistel cipher with four or six rounds. That will not be cryptographically secure, but will give you enough pseudo-randomness with guaranteed uniqueness.