31

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.

Michal
  • 31
  • 6
Guy Kobrinsky
  • 311
  • 1
  • 3
  • 4
  • 1
    Well 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
  • 4
    What'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
  • 1
    This 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 Answers2

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
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