Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a consistant GUID or unique identifier from a string

Tags:

c#

Say I have a string, something like '70c3bdc5ceeac673'. Is it possible in C# to create a GUID like structure (DB Column is only accepting uniqueidentifier) based on this string? The goal would be that the same Guid or unique sting is created everytime I pass that value in. I guess essentially like a Hmac SHA1 hash with a key.

like image 555
Stavros_S Avatar asked Jan 05 '23 21:01

Stavros_S


1 Answers

Creating Guid from SHA256 hash seem like an easy option:

var guid = new Guid(
   System.Security.Cryptography.SHA256.Create()
      .ComputeHash(Encoding.UTF8.GetBytes("70c3bdc5ceeac673")).Take(16).ToArray());

Code discards half of hash result, but it does not change the fact that the same string is always transformed to the same Guid.

Alternatively depending on your requirements just converting string to byte array and padding with 0/removing extra may be enough.

like image 173
Alexei Levenkov Avatar answered Jan 25 '23 12:01

Alexei Levenkov