Search code examples
phpbase64convertersbase62

convert base64 to base62 (without special characters)


I want to pass a blowfish encrypted string in a URL, and want to encode it like base64, but without any special character, something like base62 would be great (0-9a-zA-Z). So what I'm trying to do is converting the blowfish encrypted string using base64_encode, and convert base64 to base62.

I know about solutions how to make base64 url-safe, but I really don't want any special character in the string. convert_base() only works with base up to 36, the math extensions can convert up to base 62.

Has anybody a nice idea how to convert a base64 string to base62 using PHP?


Solution

  • function base62encode($data) {
        $outstring = '';
        $l = strlen($data);
        for ($i = 0; $i < $l; $i += 8) {
            $chunk = substr($data, $i, 8);
            $outlen = ceil((strlen($chunk) * 8)/6); //8bit/char in, 6bits/char out, round up
            $x = bin2hex($chunk);  //gmp won't convert from binary, so go via hex
            $w = gmp_strval(gmp_init(ltrim($x, '0'), 16), 62); //gmp doesn't like leading 0s
            $pad = str_pad($w, $outlen, '0', STR_PAD_LEFT);
            $outstring .= $pad;
        }
        return $outstring;
    }
    
    function base62decode($data) {
        $outstring = '';
        $l = strlen($data);
        for ($i = 0; $i < $l; $i += 11) {
            $chunk = substr($data, $i, 11);
            $outlen = floor((strlen($chunk) * 6)/8); //6bit/char in, 8bits/char out, round down
            $y = gmp_strval(gmp_init(ltrim($chunk, '0'), 62), 16); //gmp doesn't like leading 0s
            $pad = str_pad($y, $outlen * 2, '0', STR_PAD_LEFT); //double output length as as we're going via hex (4bits/char)
            $outstring .= pack('H*', $pad); //same as hex2bin
        }
        return $outstring;
    }
    
    $str62 = base62_encode(base64_decode($str64)) // $str64 = our string base64 encoded
    

    All credits go to Marcus Bointon.