Generate GUID from any string using C#

Some times you need to generate GUID from a string which is not valid for GUID constructor .

so what we will do is to get a valid input from string that the GUID constructor will accept it.

It is recommended to be sure that the string that you will generate a GUID from it some how unique.

The Idea is simple is to hash the string to 16 byte Array which the GUID constructor will accept it.

Note: feel free to use more reliable hashing techniques.

The code will talk :

using System;
using System.Text;
using System.Security.Cryptography;


namespace StringToGUID
{
    class Program
    {
        static void Main(string[] args)
        {
            string token = "BSNAItOawkSl07t77RKnMjYwYyG4bCt0g8DVDBv5m0";
            Console.WriteLine(StringToGUID(token).ToString());
            token = "BSNePf57YwhzeE9QfOyepPfIPao4UD5UohG_fI-#eda7d";
            Console.WriteLine(StringToGUID(token).ToString());
            Console.ReadLine();
        }

        static Guid StringToGUID(string value)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value));
            return new Guid(data);
        }


    }
}

And The Output:

5e5d4d29-e8b2-edb1-d5f8-a3717796cde0

114a9922-7557-7811-112f-267a1a751e9b

2 Comments

Comments have been disabled for this content.