How can I generate a GUID for a string?

Quite old this thread but this is how we solved this problem:

Since Guid’s from the .NET framework are arbitrary 16bytes, or respectively 128bits, you can calculate a Guid from arbitrary strings by applying any hash function to the string that generates a 16 byte hash and subsequently pass the result into the Guid constructor.

We decided to use the MD5 hash function and an example code could look like this:

string input = "asdfasdf";
using (MD5 md5 = MD5.Create())
{
    byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
    Guid result = new Guid(hash);
}

Please note that this Guid generation has a few flaws by itself as it depends on the quality of the hash function! If your hash function generates equal hashes for lots of string you use, it’s going to impact the behaviour of your software.

Here is a list of the most popular hash functions that produce a digest of 128bit:

  • RIPEMD (probability of collision: 2^18)
  • MD4 (probability of collision: for sure)
  • MD5 (probability of collision: 2^20.96)

Please note that one can use also other hash functions that produce larger digests and simply truncate those. Therefore it may be smart to use a newer hash function. To list some:

  • SHA-1
  • SHA-2
  • SHA-3

Today (Aug 2013) the 160bit SHA1 hash can be considered being a good choice.

Leave a Comment

tech