Skip to content

Instantly share code, notes, and snippets.

@jen20
Created August 19, 2014 17:39
Show Gist options
  • Select an option

  • Save jen20/33d28a6ed7415f1aaa58 to your computer and use it in GitHub Desktop.

Select an option

Save jen20/33d28a6ed7415f1aaa58 to your computer and use it in GitHub Desktop.

Revisions

  1. jen20 created this gist Aug 19, 2014.
    47 changes: 47 additions & 0 deletions MessageIdentity.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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;
    }
    }