Skip to content

Instantly share code, notes, and snippets.

@jen20
Created August 19, 2014 17:39
Show Gist options
  • Save jen20/33d28a6ed7415f1aaa58 to your computer and use it in GitHub Desktop.
Save jen20/33d28a6ed7415f1aaa58 to your computer and use it in GitHub Desktop.
Generator for deterministic GUIDs
public class MessageIdentity
{
public Guid NameSpace;
private readonly byte[] _namespaceBytes;
public MessageIdentity(Guid guidNameSpace)
{
NameSpace = guidNameSpace;
_namespaceBytes = guidNameSpace.ToByteArray();
SwapByteOrder(_namespaceBytes);
}
public Guid Create(byte[] input)
{
byte[] hash;
using (var algorithm = SHA1.Create())
{
algorithm.TransformBlock(_namespaceBytes, 0, _namespaceBytes.Length, null, 0);
algorithm.TransformFinalBlock(input, 0, input.Length);
hash = algorithm.Hash;
}
var newGuid = new byte[16];
Array.Copy(hash, 0, newGuid, 0, 16);
newGuid[6] = (byte)((newGuid[6] & 0x0F) | (5 << 4));
newGuid[8] = (byte)((newGuid[8] & 0x3F) | 0x80);
SwapByteOrder(newGuid);
return new Guid(newGuid);
}
private static void SwapByteOrder(byte[] guid)
{
SwapBytes(guid, 0, 3);
SwapBytes(guid, 1, 2);
SwapBytes(guid, 4, 5);
SwapBytes(guid, 6, 7);
}
private static void SwapBytes(byte[] guid, int left, int right)
{
var temp = guid[left];
guid[left] = guid[right];
guid[right] = temp;
}
}
@jen20
Copy link
Author

jen20 commented Aug 19, 2014

I need to find the original source for the algorithm to credit it.

@kstrauss
Copy link

i believe it's similar to rfc4122 section 4.3
http://www.ietf.org/rfc/rfc4122.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment