As part of a web application I need an auth-code to pass as a URL parameter. I开发者_开发技巧 am currently using (in Rails) : Digest::SHA1.hexdigest((object_id + rand(255)).to_s)
Which provides long strings like : http://myapp.com/objects/1?auth_code=833fe7bdc789dff996f5de46075dcb409b4bb4f0
However it is too long and I think I might be able to "compress" this chain using more legal characters in an URL like the whole uppercase and lowercase alphabet in addition to numbers.
Do you have a code snipplet which does just that ?
your_auth_code = Digest::SHA1.hexdigest((object_id + rand(255)).to_s)
your_shortened_code = your_auth_code.to_i(16).to_s(36)
Converts your auth_code from base 16 (hexadecimal) to base 36 which uses [0-9a-z] Personally I'd just cut the code in two if you feel it's too long.
Courtesy of a coworker of mine:
CHARS = [*'a'..'z'] + [*'A'..'Z'] + [*0..9]
def create_token
self.token = (0..9).map { CHARS[rand(CHARS.size)] }*''
end
There's also one that uses a bunch ascii characters from range 32+, but it isn't suitable for your use case (urls) due to illegal characters, but you might want to use for password salts, etc. This one courtesy of James Buck:
Array.new(32) { 32 + rand(95) }.pack("C*")
With those two snippets you can probably customize it for your needs.
What gpaul is getting at is that hash functions are still hash functions even if they're truncated, there's just a higher chance of collision though with only 10 bits it's still quite a low rate of collision. If you look at bit.ly for instance their hashes are completely miniscule but as you noted they're using base-32 instead of base-16, it doesn't really matter that much.
What's important is for you to ask what's at risk if people collide, because even with full SHA1 there's still the chance (cryptographically impossible). If there's really not a huge danger I think you could go down to 5-10 characters.
But the question still remains of why it matters. In your emails presumably you're sending a link which people just click on correct? There may be a better option entirely if you can tell us why the url is too long.
That is correct : my app has Users which click a link on an email containing an auth code. When the user clicks the link, he ends up on the webapp but he is not redirected. The auth code will stay in the URL bar. Each one of my users has an auth code. What's at stake if collision occur is that two users cannot be distinguished between each other.
Thanks to your very valuable input I was able to figure out what to type in google to get info on that topic : "base 62".
So I found the base62 gem : http://github.com/jtzemp/base62
And now, my formula is :
Digest::SHA1.hexdigest((object_id + rand(255)).to_s).to_i(16).base62_encode.slice(0..10)
which gives me an auth_code like : Fw1eDr701PY
Its a good compromise. If my app conquers the world, I can still add a DB lookup to avoid duplicates but for now I will stick to it.
精彩评论