Created
August 24, 2020 16:38
-
-
Save ChrisMcKee/a8892a905f9f54d712c4442758883e96 to your computer and use it in GitHub Desktop.
Sizeable seed based ID
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.Linq; | |
using System.Security.Cryptography; | |
using System.Text; | |
namespace HashTime | |
{ | |
class Program | |
{ | |
private static readonly Dictionary<string, string> SeedBox = new Dictionary<string, string>(); | |
private static readonly Random Rnd = new Random(); | |
static string GetNum(int length) => string.Join(string.Empty, Enumerable.Range(0, length).Select(number => Rnd.Next(0, 9).ToString())); | |
static void Main(string[] args) | |
{ | |
var did = Guid.NewGuid().ToString(); | |
int i = 3_000_000; | |
while (i-- > 0) | |
{ | |
TestShortCode(GetNum(6) + "_" + GetNum(9) + "test" + "test" + did); | |
} | |
Console.WriteLine("boop"); | |
} | |
/// <summary> | |
/// Produces a fixed length upper case string based on the reduced byte output of the hash | |
/// </summary> | |
/// <param name="input"></param> | |
/// <param name="maxLength"></param> | |
/// <returns></returns> | |
private static string SHA1HexHash(string input, int maxLength = 40) | |
{ | |
using (SHA1 sha1 = SHA1.Create()) | |
{ | |
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)).AsSpan().Slice(start: 0, length: maxLength); | |
var sb = new StringBuilder(maxLength); | |
for (var index = 0; index < maxLength; index++) | |
{ | |
sb.Append(hash[index].ToString("X2")); | |
} | |
return sb.ToString(); | |
} | |
} | |
/// <summary> | |
/// Produces a mix case hash based on a slice of the Base64 Encoded hash | |
/// </summary> | |
/// <param name="input"></param> | |
/// <param name="maxLength"></param> | |
/// <returns></returns> | |
private static string SHA1B65Hash(string input, int maxLength = 40) | |
{ | |
using (SHA1 sha1 = SHA1.Create()) | |
{ | |
return Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(input))).Substring(0,maxLength); | |
} | |
} | |
public static void TestShortCode(string seed) | |
{ | |
var muhSeed = SHA1B65Hash(seed, 9); | |
//var muhSeed = SHA1HexHash(seed, 9); | |
try | |
{ | |
if (SeedBox.ContainsKey(muhSeed)) | |
{ | |
var matchedSeed = SeedBox.GetValueOrDefault(muhSeed); | |
if (seed != matchedSeed) | |
{ | |
Console.WriteLine("Collision on " + seed + " existed for " + matchedSeed); | |
} | |
} | |
else | |
{ | |
SeedBox.Add(muhSeed, seed); | |
} | |
} | |
catch | |
{ | |
Console.WriteLine("Error handling MuhSeed"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment