patterncsharpMinor
Short hash generator
Viewed 0 times
generatorhashshort
Problem
I am working on some code that will generate a link with a relativly unique 10 character hash. I am not worried to much about colisions as long as they are rare enough that I could have a couple thousand links out standing since I soft delete after they are used and a colision between an open item and a closed item is not an issue. I would also like the method to be deterministic, the same input generates the same output so worst case I can recalculate the hash if needed. Here is the code I have and it works but am wondering if there is a better way.
string input = //Some input text that includes the datetime the hash was created;
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
//make sure the hash is only alpha numeric to prevent charecters that may break the url
return string.Concat(Convert.ToBase64String(hash).ToCharArray().Where(x => char.IsLetterOrDigit(x)).Take(10));
}Solution
This seems fine.
This should give you a key-space of
If you have only a few thousand links then you're more likely to win the lottery jackpot than get a collision.
This should give you a key-space of
64^10.If you have only a few thousand links then you're more likely to win the lottery jackpot than get a collision.
Context
StackExchange Code Review Q#102251, answer score: 2
Revisions (0)
No revisions yet.