6
\$\begingroup\$

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));
}
asked Aug 29, 2015 at 18:01
\$\endgroup\$
4
  • \$\begingroup\$ If it is a link, why are you limiting it to 10 characters? \$\endgroup\$ Commented 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\$ Commented 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\$ Commented 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\$ Commented Aug 29, 2015 at 23:20

1 Answer 1

2
\$\begingroup\$

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.

answered Aug 30, 2015 at 18:35
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.