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


I'm fairly sure you've confused System.Guid with wanting a hash (say, SHA-256) of a given string.

Note that, when selecting a cryptographically-secure hashing algorithm, MD5, SHA0 and SHA1 are all generally considered dead. SHA2 and up are still usable.


What you are looking for is probably generating version 3 or version 5 UUIDs, which are name based UUIDs. (version 5 is the recommended). I don't think that the .NET framework has build in support for it. See http://en.wikipedia.org/wiki/Universally_Unique_Identifier

I did a few google searches to see if I could find something in the Win32 API, but nothing came up. However, I am sure that the .NET framework has some implementation hidden somewhere, because as far as I know, when generating a COM object in .NET, and you don't supply an explicit GUID, then the .NET framework generates a name based UUID to create a well-defined ClassID and InterfaceID, i.e. UUIDs that don't change every time you recompile (like VB6). But this is probably hidden, so I guess you need to implement the algorithm yourself. Luckily, .NET provides both an MD5 and SHA1 algorithm so I don't think implementing a version3 and version5 UUID should be too difficult.