« Binary Patching with bsdiff in C# | Main | Git Bash in Console2 »

13 April 2011

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:

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 GuidUtility.Create which implements the RFC 4122 rules. Using it is simple (once you’ve decided on the namespace ID to use):

    Guid guid = GuidUtility.Create(GuidUtility.DnsNamespace, "code.logos.com");

Posted by Bradley Grainger at April 13, 2011 06:31 PM