Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Created August 3, 2023 00:05
Show Gist options
  • Save xiaomi7732/eb097ebcbe7ffe5c568ccbcf3b334c25 to your computer and use it in GitHub Desktop.
Save xiaomi7732/eb097ebcbe7ffe5c568ccbcf3b334c25 to your computer and use it in GitHub Desktop.
Hash a string to a guid

Hash a string to a guid

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.

Goal

This is the API I want:

Guid CreateGuid(string value);

Implementation

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment