effective solution: base32 encoding in php

Freddy picture Freddy · May 7, 2013 · Viewed 19.7k times · Source

I am looking for a base32 function/class for php. the different classes and function that i found are all very ineffective. I ran a benchmark and came to the following result:

10000 decodings:

base32: 2.3273 seconds

base64: 0.0062 seconds

The base32 class which I have used is:

http://www.php.net/manual/en/function.base-convert.php#102232

Is there any way which is simpler?

The reason why I want to use base32 is that it is not case sensitive and as a result I have no problems any more regarding url parameters which on some system (e.g. email systems) are always converted to lowercase letters.

If you have a better alternative for lowercase encoding, I would also love to hear them.

Answer

Andre D picture Andre D · May 21, 2013

For Base32 in PHP, you can try my implementation here:

https://github.com/ademarre/binary-to-text-php

Copied from the Base32 example in the README file:

// RFC 4648 base32 alphabet; case-insensitive
$base32 = new Base2n(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', FALSE, TRUE, TRUE);
$encoded = $base32->encode('encode this');
// MVXGG33EMUQHI2DJOM======

It's not slow, and it may or may not be faster than the class you benchmarked, but it will not be as fast as a built-in PHP function like base64_encode(). If that is very important to you, and you don't really care about Base32 encoding, then you should just use hexadecimal. You can encode hexadecimal with native PHP functions, and it is case-insensitive.

$encoded = bin2hex('encode this'); // 656e636f64652074686973
$decoded = pack('H*', $encoded);   // encode this

// Alternatively, as of PHP 5.4...
$decoded = hex2bin($encoded);      // encode this

The downside to hexadecimal is that there is more data inflation compared to Base32. Hexadecimal inflates the data 100%, while Base32 inflates the data about 60%.