4

We would like to generate a Guid based on some random string. The goal would be that the Guid is always the same for a given string.

Just to be clear, my string is not formated as a guid, it could be "Toto" as "asdfblkajsdflknasldknalkvkndlskfj".

I know that this would generate some Guid that is as unique as my input string, but it's not the question here.

J4N
  • 19,480
  • 39
  • 187
  • 340

1 Answers1

9

Since both a Guid and a MD5 hash are 128 bits integers, you could use the MD5 of a given string as the Guid. It will reproduce the same value consistently:

using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hashBytes = md5.ComputeHash(inputBytes);

    Guid g = new Guid(hashBytes);
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • This works practically. However, not that you violate the policy of a Guid, so theoretically it does not make sense to use a Guid here at all - I would just go for a simple String of the new hash. Of course you can then format it as you like and make it look like a Guid - even if it isn't theoretically. – Larce Apr 03 '18 at 11:00
  • Anyway I wouldn't use MD5 anymore. If input distribution is as good as original Guid distribution MD5 algorithm may increase the likelihood of collisions. – arekzyla Apr 03 '18 at 11:24
  • A valid argument to not do what OP asks @arekzyla. – Patrick Hofman Apr 03 '18 at 11:25