Last active
January 17, 2021 17:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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