php: number only hash?

An MD5 or SHA1 hash in PHP returns a hexadecimal number, so all you need to do is convert bases. PHP has a function that can do this for you:

$bignum = hexdec( md5("test") );

or

$bignum = hexdec( sha1("test") );

PHP Manual for hexdec

Since you want a limited size number, you could then use modular division to put it in a range you want.

$smallnum = $bignum % [put your upper bound here]

EDIT

As noted by Artefacto in the comments, using this approach will result in a number beyond the maximum size of an Integer in PHP, and the result after modular division will always be 0. However, taking a substring of the hash that contains the first 16 characters doesn’t have this problem. Revised version for calculating the initial large number:

$bignum = hexdec( substr(sha1("test"), 0, 15) );

Leave a Comment