Skip to content

Instantly share code, notes, and snippets.

@egil
Last active January 17, 2021 17:17
Show Gist options
  • Save egil/6f049001206e3fe649da2c85fbffd6da to your computer and use it in GitHub Desktop.
Save egil/6f049001206e3fe649da2c85fbffd6da to your computer and use it in GitHub Desktop.
This can be used to hash key/value pairs, that should be used as a ID in e.g. a database like CosmosDB. This will produce the same length key, no matter how many key/value pairs are supplied.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
public static class IdFactory
{
public static string CreateId(IEnumerable<(string key, string value)> kvps)
{
using var crypt = new SHA256Managed();
var tagBytes = TagsToBytes(kvps);
var hashedTags = crypt.ComputeHash(tagBytes);
return ConvertToString(hashedTags);
}
private static string ConvertToString(byte[] hashedTags)
{
var builder = new StringBuilder();
foreach (var @byte in hashedTags)
{
builder.Append(@byte.ToString("x2", CultureInfo.InvariantCulture));
}
return builder.ToString();
}
private static byte[] TagsToBytes(IEnumerable<(string key, string value)> kvps)
{
var builder = new StringBuilder();
foreach (var tag in kvps.OrderBy(tag => tag.key))
{
builder.Append(tag.Key);
builder.Append(tag.Value);
}
return Encoding.UTF8.GetBytes(builder.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment