skip to Main Content

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


  1. 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.
    Login or Signup to reply.
  2. 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.

    const alphanu = Date.now().toString(36) + Math.random().toString(36).substring(13);
    
    console.log(alphanu); 
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search