Skip to content

Instantly share code, notes, and snippets.

@dmitribodiu
Forked from jen20/MessageIdentity.cs
Created April 29, 2020 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitribodiu/51b421591c22a2d4f81def8dfaaf0514 to your computer and use it in GitHub Desktop.
Save dmitribodiu/51b421591c22a2d4f81def8dfaaf0514 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment