String to Guid with MD5 hashes for .NET and SQL Server

If you need to convert a string value to Guid you can use MD5 hashes. They are always having a length of 128 bits and therefore can be converted to a Guid.

Why you may want to do this?

In my project I’m having a big database containing some very long text values. I needed a way to quickly compare and query them. In Sql Server indexed columns does have a maximun length and in my case the limit was exceeded. Storing the hashes of big text values in the database is a good option for that. You can add an index to the Guid and query quickly.


This example converts a string to Guid in C#

        /// <summary>
        /// Convert string to Guid
        /// </summary>
        /// <param name="value">the string value</param>
        /// <returns>the Guid value</returns>
        public static Guid ConvertToMd5HashGUID(string value)
            // convert null to empty string - null can not be hashed
            if (value == null)
                value = string.Empty;

            // get the byte representation
            var bytes = Encoding.Default.GetBytes(value);

            // create the md5 hash
            MD5 md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(bytes);

            // convert the hash to a Guid
            return new Guid(data);



One thought on “String to Guid with MD5 hashes for .NET and SQL Server

  1. […] Các bạn có thể tham khảo thêm link gốc tại đây. […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: