Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create short hash in PHP

Tags:

php

hash

This has been asked numerous times here on SO. But I haven't found a solution for my problem.

I want to create a short hash (let's say max 8 chars) for an invitation system. I cannot use base[X] encoding because that would be too easy to guess. I cannot just trim extra characters of e.g. an MD5 hash, because I think the problem of collisions will come up at some time then.

Is there a solution for this?

like image 565
PeeHaa Avatar asked Dec 04 '11 16:12

PeeHaa


2 Answers

If you want to be assured of never having a collision, your best bet is to maintain a database of valid hashes and compare against that database when generating new hashes.

If you think you will have a high volume, you may want to pre-generate the hashes so that you have a "haystack" of them ready to use. Some people do this with random numbers because hardware random number generators can only produce numbers at a certain rate.

like image 178
user984869 Avatar answered Oct 03 '22 03:10

user984869


The shortest useful hash algorithm would be md5. Md5 generates 16 bytes=128 bit hash. if you use base 64 encoding, that is, 6 useful bits per byte/char.

You should be able to reduce the md5 to 22 characters (leaving the trailing padding introduced by b64).

This has an added advantage of using the same for legal filenames. You will have to substitute the default / and + characters with any other symbol which does not clash with file naming convention of your os.

Base64 (by replacing / and +) ensures your hash does not mess up the url with special characters.

like image 38
geekay Avatar answered Oct 03 '22 02:10

geekay