Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way in Java to turn String into UUID

Tags:

java

uuid

How to generate a valid UUID from a String? The String alone is not what I'm looking for. Rather, I'm looking for something like a hash function converting any String to a valid UUID.

like image 839
Guy Kobrinsky Avatar asked Sep 03 '14 05:09

Guy Kobrinsky


People also ask

Can we convert string to UUID in Java?

The fromString() method of UUID class in Java is used for the creation of UUID from the standard string representation of the same. Parameters: The method takes one parameter UUID_name which is the string representation of the UUID. Return Value: The method returns the actual UUID created from the specified string.

Can I convert string to UUID?

The fromString(String name) method is used to create a UUID from the string standard representation as described in the toString() method.

What is UUID randomUUID () in Java?

The randomUUID() method is used to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator.


2 Answers

Try this out:

String superSecretId = "f000aa01-0451-4000-b000-000000000000";
UUID.fromString(superSecretId);

I am using this in my project and it works. Make sure you import the right stuff.

like image 178
Raj Avatar answered Oct 23 '22 17:10

Raj


In the Java core library, there's java.util.UUID.nameUUIDFromBytes(byte[]).

I wouldn't recommend it because it's UUID 3 which is based on MD5, a very broken hash function. You'd be better off finding an implementation of UUID 5, which is based on SHA-1 (better although also sort of broken).

like image 45
Chris Martin Avatar answered Oct 23 '22 16:10

Chris Martin