编程语言
首页 > 编程语言> > php – 将base64转换为base62(无特殊字符)

php – 将base64转换为base62(无特殊字符)

作者:互联网

我想在一个URL中传递一个河豚加密的字符串,并希望像base64一样编码,但没有任何特殊字符,像base62这样的东西会很棒(0-9a-zA-Z).所以我要做的是使用base64_encode转换河豚加密字符串,并将base64转换为base62.

我知道如何使base64 url​​-safe的解决方案,但我真的不希望字符串中有任何特殊字符. convert_base()仅适用于最多36的基数,数学扩展可以转换为基数62.

有没有人知道如何使用PHP将base64字符串转换为base62?

解决方法:

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

所有学分都归Marcus Bointon所有.

标签:php,base64,converter,base62
来源: https://codeday.me/bug/20190831/1777334.html