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));
}
-
\$\begingroup\$ If it is a link, why are you limiting it to 10 characters? \$\endgroup\$spyr03– spyr032015年08月29日 19:59:22 +00:00Commented Aug 29, 2015 at 19:59
-
\$\begingroup\$ To get a relatively unique 10 character string, it is way easier to generate a GUID and use the first 10 characters. They are also guaranteed legal in an URL. Regarding uniqueness, the first 6 or 7 are usually unique (commonly used within git to refer to a commit), so using 10 characters should be quite safe. \$\endgroup\$holroy– holroy2015年08月29日 22:10:30 +00:00Commented Aug 29, 2015 at 22:10
-
\$\begingroup\$ @spyr03 I want to keep the URL short like a tiny URL. Other than that no specific reason \$\endgroup\$RubberChickenLeader– RubberChickenLeader2015年08月29日 23:19:01 +00:00Commented Aug 29, 2015 at 23:19
-
\$\begingroup\$ @holroy I edited the question but I wanted to have a deterministic method not just a substring on a GUID. \$\endgroup\$RubberChickenLeader– RubberChickenLeader2015年08月29日 23:20:59 +00:00Commented Aug 29, 2015 at 23:20
1 Answer 1
This seems fine.
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.