A PHP class to generate an alphanumeric hash of specified length from an integer.
composer require dmhendricks/hash-int
- PHP 5.6 or higher
- BC Math:
apt install php7.x-bcmath
$num = 456;
/**
* Create a 7-character hash from integer
*/
$hash = \CloudVerve\HashInt::hash( $num, 7 );
// Unhash the string
$unhashed = \CloudVerve\HashInt::unhash( $hash );
echo 'Hashed: ' . $hash . '<br />';
echo 'Unhashed: ' . $unhashed;
Hashed: p3Wq1aC
Unhashed: 456
Original Author Notes
Paraphrased (source):
I wanted a short, unique, alphanumeric hash with a sequence that is difficult to deduce. I could create it with md5 and trim the first n chars, but storing a truncated checksum in a unique field means that the frequency of collisions will increase geometrically as the number of unique keys for a base 62-encoded integer approaches 62^n. I'd rather do it right than create a time bomb.
Hashes are base 62 encoded base 10 integers. 1=1, 10=a, 36=Z, 61=z, 62=10, 72=1a, etc.
1 character = 62 permutations, 2 characters = 3844 permutations, etc.
41 = next highest prime from golden mean of 62.
2377 = next highest prime from golden mean of 3844.
I chose to use primes to ensure hash uniqueness. Any prime greater than one half 62^n will do, but if you use a prime near 62^n or 62^n/2 or 2*62^n/3 etc, you will detect a linearity in the sequence at certain points in the ring.
I chose primes near the golden ratio to maximize the appearance of randomness. Given a small set of hashes (even with the associated id) it would be difficult for anyone to guess the next hash.
This is a thin rotation and base re-encoding obfuscation algorithm, not an encryption algorithm. Don't use this to encrypt sensitive information - use it to obfuscate integer IDs or create short reference keys (as an example, for short URLs).
- Prime Numbers Generator and Checker
- Ernesto Preste for adding bcmath support
- Padraig Kennedy for adding hash reversibility