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.
Asked
Active
Viewed 6.0k times
31
-
1Well what are your requirements around uniqueness etc? You *could* just call `hashCode` to get an `int`, and then build a UUID based on that... but you'd obviously get a lot more collisions than necessary. – Jon Skeet Sep 03 '14 at 05:56
-
4What's in the string that has any relevance to a UUID at all? You may as well just generate a new UUID and keep a mapping table somewhere. Or possibly [`UUID.nameUUIDFromBytes(string.getBytes())`](http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html#nameUUIDFromBytes(byte[])). – user207421 Sep 03 '14 at 06:01
-
1This looks like an XY Problem. – Raedwald Sep 03 '14 at 06:58
-
There is a good answer on this here: https://stackoverflow.com/a/40230410/1174024 – Nicholas DiPiazza Sep 17 '19 at 03:14
2 Answers
25
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.

Raj
- 3,637
- 8
- 29
- 52
-
4This method only converts from a string representation of UUID to UUID. Does not work for any string. https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html#toString-- – user0904 Jun 12 '19 at 13:43
-
6
-
2
15
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).

Chris Martin
- 30,334
- 10
- 78
- 137
-
-
1@Abhijeet I wouldn't know. You may want to ask that as a separate question. – Chris Martin Feb 01 '17 at 05:24
-
2MD5 is broken for security purposes, but for hashing is good, has [low collision rate](https://stackoverflow.com/questions/201705/how-many-random-elements-before-md5-produces-collisions) – cdalxndr Feb 11 '21 at 13:38