Skip to content

Instantly share code, notes, and snippets.

@dnauck
Created June 19, 2015 10:01
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 dnauck/6190ac506b05691cc29d to your computer and use it in GitHub Desktop.
Save dnauck/6190ac506b05691cc29d to your computer and use it in GitHub Desktop.
Creates and returns a deterministic GUID from the input string
using System;
using System.Text;
namespace Test
{
public static class StringExtensions
{
/// <summary>
/// Creates and returns a deterministic <see cref="Guid"/> from the input string.
/// This extension method could be used to build a <see cref="Guid"/> from a natural
/// or external key of any entity.
/// </summary>
/// <param name="value">The input string.</param>
/// <returns>A deterministic <see cref="Guid"/>.</returns>
public static Guid ToDeterministicGuid(this string value)
{
if (string.IsNullOrWhiteSpace(value))
return Guid.Empty;
var md5Digest = new Org.BouncyCastle.Crypto.Digests.MD5Digest();
var md5ResultBuffer = new byte[md5Digest.GetDigestSize()];
var input = Encoding.UTF8.GetBytes(value);
md5Digest.BlockUpdate(input, 0, input.Length);
md5Digest.DoFinal(md5ResultBuffer, 0);
return new Guid(md5ResultBuffer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment