DEV Community

Discussion on: Making random ID with Javascript

miketalbot profile image
Mike Talbot • Edited on

If length is long enough then this is likely to produce non-conflicting ids for many cases on a single system, the problem is that they are not cryptographically secure. Conflicts become more likely when it is used on multiple systems.

The reason that they aren't secure is that Math.random() is predictable and not "really random". In fact, producing one ID with this method, of reasonable length, would probably give enough information to work out what the next ID was going to be.

This is a problem if you used such an ID as the key to a database record and then exposed that ID in a URL, because a hacker would be able to work out many other IDs and potentially access data they shouldn't.

To create really secure IDs then some "entropy" should be added - this is something that you could derive from the system or the environment. Like the movement of the users mouse, the number of packets received on the server. Something that is not computer generated if possible. You should also make the random part of the calculation come from a cryptographically secure method. There are many with different characteristics, for instance the mersenne twister is considered good, there are many way of getting that algorithm including this.

miketalbot profile image
Mike Talbot

Personally I use nanoid which is ideal for many circumstances, has variable length and is faster that uuid

meatboy profile image
Meat Boy

Exactly. Problem with generating some "random and unique" string may sounds trivial, but it's not. As addition to what you have wrote, the problem is tried to be solved by ietf and uuid implementations: