Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Guid based on a string [duplicate]

Tags:

c#

.net

guid

We would like to generate a Guid based on some random string. The goal would be that the Guid is always the same for a given string.

Just to be clear, my string is not formated as a guid, it could be "Toto" as "asdfblkajsdflknasldknalkvkndlskfj".

I know that this would generate some Guid that is as unique as my input string, but it's not the question here.

like image 782
J4N Avatar asked Jan 28 '23 09:01

J4N


1 Answers

Since both a Guid and a MD5 hash are 128 bits integers, you could use the MD5 of a given string as the Guid. It will reproduce the same value consistently:

using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hashBytes = md5.ComputeHash(inputBytes);

    Guid g = new Guid(hashBytes);
}
like image 51
Patrick Hofman Avatar answered Feb 03 '23 13:02

Patrick Hofman