In building a Java based system that needs unique identifiers on the URL, is UUID.randomUUID()
or SecureRandom
a better choice?
More specifically, a call to POST /items
will return a 201 Created
with a Location to the newly created /items/{id}
where {id}
is a random string and the URL is intended to be used by anonymous HTTP requests for a limited time window.
This code returns a 22 character string (e.g. B-KEPLFdWNZ4JTUnnEq3Og
) with 128 bits of randomness.
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[16];
random.nextBytes(bytes);
Encoder encoder = Base64.getUrlEncoder().withoutPadding();
String token = encoder.encodeToString(bytes);
System.out.println(token);
UUID.randomUUID() is a "Static factory to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator." This code returns a 36 character string (e.g. f0803ce7-8e3d-421a-8126-e5a0bd0a865f
) with 122 bits of randomness.
UUID randomUUID = UUID.randomUUID();
System.out.println(randomUUID);
These identifiers will also be persisted in a relational database as a fixed length CHAR
type.