Sometimes, you may encounter a situation where you require a GUID-formatted key but only have a loose string at hand. In such cases, this simple solution can prove to be quite effective.
This is the API I want:
Guid CreateGuid(string value);
And here's the implemneation
public async Task<Guid> GetGuidAsync(string value, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException($"'{nameof(value)}' cannot be null or empty.", nameof(value));
}
using Stream input = new MemoryStream(Encoding.UTF8.GetBytes(value));
using SHA256 mySHA256 = SHA256.Create();
byte[] hashed = await mySHA256.ComputeHashAsync(input, cancellationToken).ConfigureAwait(false);
// Truncate 32 bits to 16 bits.
byte[] hashed16 = hashed.Take(16).ToArray();
return new Guid(hashed16);
}
See more details: https://github.com/xiaomi7732/HashStringToGuid/