Close this search box.

Generating Deterministic GUIDs

Thursday, June 26, 2008 2:38 PM


Recently I had a need to generate deterministic GUIDs for a string, so a given string would always result in the same unique id.

In the unlikely event you also have a need for it (mine related to UDDI Service Provider names), there’s a very simple way to do it using an MD5 hash as an intermediate step:

private Guid GetDeterministicGuid(string input)

  // use MD5 hash to get a 16-byte hash of the string:

  MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();

  byte[] inputBytes = Encoding.Default.GetBytes(input);

  byte[] hashBytes = provider.ComputeHash(inputBytes);

  // generate a guid from the hash:

  Guid hashGuid = new Guid(hashBytes);

  return hashGuid;

The input string can be of any length, and the hash will always be the same for a given input. MD5 generates a 128-bit hash, in the form of a 16 element byte array which can be parsed directly by System.Guid.

This article is part of the GWB Archives. Original Author: Elton Stoneman

Related Posts