Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can cryptographically strong UUIDs be generated in Javascript?

What is the state of today's web browsers (Chrome, IE, Safari & Firefox) and their ability to create cryptographically strong UUIDs? In researching this question I have been unable to find anything definitive. I have come across info on stackoverflow and elsewhere that points to issues with Math.random but I would like to know what the current state of all this is.

UPDATE

As icktoofay pointed out, crypto.getRandomValues is the way to do this. Unfortunately, support across browsers is limited. Is there a proven way to work around this? Are there any javascript libraries that tackle this problem?

like image 923
user1843640 Avatar asked Jan 19 '14 03:01

user1843640


People also ask

How are UUIDs generated?

Different versions of UUID follow the RFC 4122 specification. UUIDs are generated using an algorithm based on a timestamp and other factors such as the network address. Free tools to generate UUIDs include UUIDTools or Online UUID Generator.

How UUID v4 is generated?

Version 4 (random) A version 4 UUID is randomly generated. As in other UUIDs, 4 bits are used to indicate version 4, and 2 or 3 bits to indicate the variant (102 or 1102 for variants 1 and 2 respectively).

What is UUID in JS?

A Universally Unique Identifier (UUID) is a label used to uniquely identify a resource among all other resources of that type. Computer systems generate UUIDs locally using very large random numbers.

Are UUID always unique?

UUIDs are handy for giving entities their own special names, for example, in a database. There are several ways to generate them, including methods based on time, MAC addresses, hashes, and random numbers, but they make the same promise: no two are identical. Each one is unique across space and time.


2 Answers

In browsers that have it, you can use crypto.getRandomValues to get cryptographically-secure pseudorandom values. For example:

var array = new Uint8Array(16);
crypto.getRandomValues(array);

You can then manipulate those bytes into a valid UUID.

like image 54
icktoofay Avatar answered Sep 23 '22 03:09

icktoofay


Although this doesn't directly answer the original question, it might help someone looking for a library to help with UUID creation. For my current needs I have decided to use the node-uuid library. From the feature list:

  • Generate RFC4122 version 1 or version 4 UUIDs
  • Cryptographically strong random # generation on supporting platforms

Looking at the source it seems to accomplish this by using crypto.getRandomValues which is what @icktoofay suggested.

like image 43
user1843640 Avatar answered Sep 22 '22 03:09

user1843640