Id transformation with Optimus
Recently I wrote a blog post and gave a talk at php.gent about id obfuscation and how it can help hide your application internals from malicious users. While doing some research about other obfuscation techniques, I stumbled upon an implementation based on Donald Knuth's integer hash. This unbelievable small and fast algorithm will generate random-like integers with the ability to convert them back to the original value. This technique was so cool that I decided to create a PHP package for it called Optimus.
Go ahead and install it using composer:
composer require jenssegers/optimus
Using the package is fairly simple, but there is some math involved before you can start using it. Luckily, I managed to make this as easy as possible with an included command line script.
First you need to pick a prime number. You can calculate this yourself or pick one from this list. For the decoding process, the algorithm needs the "inverse prime", so that (PRIME * INVERSE) & MAXID == 1
. To calculate this number you can use the included optimus
tool:
> php vendor/bin/optimus spark 1580030173
Prime: 1580030173
Inverse: 59260789
Random: 1163945558
With these numbers you can fire up your own Optimus instance:
use Jenssegers\Optimus\Optimus;
new Optimus(1580030173, 59260789, 1163945558);
Make sure that you use the same numbers throughout your entire application. I would suggest registering a shared instance on your IoC container of choice like this:
$app['Jenssegers\Optimus\Optimus'] = function () {
return new Optimus(1580030173, 59260789, 1163945558);
};
To start encoding and decoding id's, you can use the encode
and decode
methods:
$encoded = $optimus->encode(20);
Which will result in 1535832388
. To decode it back to its original value simple do:
$original = $optimus->decode(1535832388);
I hope you find this technique as interesting as I do. It's amazing how fast it can encode and decode values. I did a quick benchmark and compared it to Hashids, and Optimus turned out to be over 125 times faster! What are you waiting for, test drive your Optimus today!