views:

335

answers:

5

Is there a way to take any number, from say, 1 to 40000 and generate an 8 character hash?

I was thinking of using base_convert but couldn't figure out a way to force it to be an 8 character hash.

Any help would be appreciated! Thanks.

+7  A: 

Why don't you just run md5 and take the first 8 characters?

Because you are wanting a hash, it doesn't matter whether portions are discarded, but rather that the same input will produce the same hash.

$hash = substr(md5($num), 0, 8);
George Edison
Thanks to whoever fixed that. I must be asleep.
George Edison
Is there any chance of a collision in my number range?
doc
Better instinct tells me no... but you might want to run a test. Since 40,000 is not a huge number, you could easily test that.
George Edison
Thanks, I'm testing this now with a random hash associated with a session.
doc
A: 

there are many ways ...

one example

$x = ?
$s = '';
for ($i=0;$i<8;++$i)
{
    $s .= chr( $x%26 + ord('a') );
    $x /= 26;
}
steelbytes
isn't this just effectively changing the base of the number?
nickf
sure. but the request was pretty vague - it just asked for an 8char hash.
steelbytes
Sorry about how vaguely I asked the question :( I'm trying to generate an 8 character hash from any integer but don't just want to pad the remaining length of the hash with something. Any ideas?
doc
A: 
$hash = substr(hash("sha256",$num), 0, 8);
ghostdog74
How does this differ from mine? `md5` is pretty strong. Why `sha256`?
George Edison
@GeorgeEdison: md5 is pretty weak. It just takes hours to create collisions.
neo
+1  A: 
>>> math.exp(math.log(40000)/8)
3.7606030930863934

Therefore you need 4 digit-symbols to produce a 8-character hash from 40000:

sprintf("%08s", base_convert($n, 10, 4))
Ignacio Vazquez-Abrams
A: 

So you want to convert a 6 digit number into a 8 digit string reproducibly?

sprintf("%08d", $number);

Certainly a hash is not reversible - but without a salt / IV it might be a bit easy to hack. A better solution might be:

substr(sha1($number . $some_secret),0,8);

C.

symcbean