Generating a deterministic GUID

Although a new GUID is typically created in order to provide a unique ID, there are occasions when it’s useful for two different systems to generate the same GUID independently. RFC 4122 provides an algorithm for deterministic creation of a GUID based on a namespace ID (itself a GUID) and a name within that namespace. These name- based GUIDs will never collide with GUIDs from other sources (e.g., Guid.NewGuid), and have a very (very) small chance of colliding with other name-based GUIDs. As per section 4.3:

  • The UUIDs generated at different times from the same name in the same namespace MUST be equal.
  • The UUIDs generated from two different names in the same namespace should be different (with very high probability).
  • The UUIDs generated from the same name in two different namespaces should be different with (very high probability).
  • If two UUIDs that were generated from names are equal, then they were generated from the same name in the same namespace (with very high probability).

Because the .NET Framework doesn’t provide a way to create these GUIDs, it’s tempting to create a custom solution (e.g., using a MD5 hash as a GUID, because it has the same number of bytes), but because that doesn’t follow the rules of GUID creation, it’s not guaranteed to be unique with respect to other GUIDs.

The algorithm for generating these GUIDs is fairly straightforward; the most complicated part may be converting the GUID to network byte order as specified in the RFC. (It’s complicated enough that the RFC authors got it wrong; the example given in Appendix B is incorrect.)

There are libraries to do this for Python and C++; I didn’t find one for .NET, so I wrote a function which implements the RFC 4122 rules. Update: This function is now available via the NGuid package.

Using it is simple (once you’ve decided on the namespace ID to use):

var guid = GuidHelpers.CreateFromName(GuidHelpers.DnsNamespace, "faithlife.codes");

Posted by Bradley Grainger on April 13, 2011