-
-
Save dmitribodiu/51b421591c22a2d4f81def8dfaaf0514 to your computer and use it in GitHub Desktop.
Generator for deterministic GUIDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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