-1

This question already has an answer here:

I am using the below method to generate multiple unique random codes of 14 digits:

var randNum = Math.floor(Math.random() * timestamp * 100);
var number = randNum.toString().substr(0, 14);

Is this method secure for generating multiple unique codes? What are the odds to get a duplicate codes? Is there any other algorithm to generate random number with less time complexity in node js?

marked as duplicate by Alexander O'Mara, forest, Steffen Ullrich, Serge Ballesta, Tobi Nary Feb 22 '18 at 8:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

As the comments point out, you are probably doing something for which you should use a cryptographically secure (pseudo-)random number generator. The standard one for Node is crypto.randomBytes.

However, that doesn't actually answer your question. As it turns out, the actual answer involves somewhat complicated math but is known; see the Birthday Problem or Birthday Attack (for the scenario of somebody trying to cause a duplicate).

As a rough approximation, though, you can think of the chance of any duplicate as being about what the chance of a specific duplicate would be if there were half as many digits (half the bits entropy). That is, with 14 digits, you have 10^14 possible values, which is very close to 2^46.5. As such, you can say there at 46.5 bits of entropy in your random codes. There's only a 1/(2^46.5) chance of any single code matching any specific other single one.

However, when you generate a bunch of codes, the chances of a collision (duplicate) go way up, much faster than you think. By the time you've generated about 10,000,000 codes (10^7, or very close to 2^23.25), you will, on average, have about one duplicate (it's all statistics, of course, you might have no dupes, or one, or two, or twenty... but one would be the most likely number). This might seem like a large number, but if you're using this code for anything serious, it's way too small. You should be using much, much larger numbers. For unique IDs, 128 bits (roughly 3.4*10^38 possible values) is the standard size number to use. Don't try to generate that in base 10, of course; that's silly. It's only 16 completely random bytes, though.

Not the answer you're looking for? Browse other questions tagged or ask your own question.