关于回答“把base64后的字符串转换成小写字母加数字,要可逆”问题的代码实现

//加密

function base64Encode($char) {

    $asciivalue = ord($char);



    //判断是否为数字

    if ($asciivalue >= 48 && $asciivalue <= 57) {

        return '99' . $char;

    }



    //判断是否为小写字母

    if ($asciivalue >= 97 && $asciivalue <= 122) {

        return '88' . $char;

    }



    $result = '';

    //判断ascii值是否为三位数,若是则直接返回,若不是则补全三位

    switch (strlen($asciivalue)) {

        case 1:

            $result = '77' . strval($asciivalue);

            break;

        case 2:

            $result = '6' . strval($asciivalue);

            break;

        case 3:

            $result = strval($asciivalue);

            break;

        default:

            break;

    }

    return $result;

}



//解密

function base64Decode($strtemp) {

    $judge = substr($strtemp, 0, 2);



    $result = '';

    //判断字符串类型

    switch ($judge) {

        case '99':

        case '88':

            $result = substr($strtemp, 2, 1);

            break;

        case '77':

            $result = chr(intval(substr($strtemp, 2, 1)));

            break;

        default:

            if (substr($judge, 0, 1) == '6') {

                $result = chr(intval(substr($strtemp, 1, 2)));

            } else {

                $result = chr(intval(substr($strtemp, 2, 1)));

            }

            break;

    }

    return $result;

}



header("Content-type: text/html; charset=utf-8");

$str = '好好学习PHP,adfassfas!';

echo 'base64加密前:' . $str . '<br/>';

$strencode = base64_encode($str);

echo 'base64加密后:' . $strencode . '<br/>';



$strencodetemp = '';

for ($i = 0; $i < strlen($strencode); $i++) {

    $strencodetemp.=base64Encode(substr($strencode, $i, 1));

}



echo '对base64加密后的字符串再进行加密后:<br/>' . $strencodetemp . '<br/>';



$strdecodetemp = '';

for ($i = 0; $i < strlen($strencodetemp); $i+=3) {

    $strdecodetemp.=base64Decode(substr($strencodetemp, $i, 3));

}



echo '对自定义加密后的字符串再进行解密后:<br/>' . $strdecodetemp . '<br/>';



echo '最后再进行base64解密后:<br/>' . base64_decode($strdecodetemp) . '<br/>';

运行结果如下:

base64加密前:好好学习PHP,adfassfas!
base64加密后:5aW95aW95a2m5LmgUEhQLGFkZmFzc2ZhcyE=
对base64加密后的字符串再进行加密后:
99588a68799999588a68799999588a99288m99567688m88g68566988h68167667167088k69088m67088z88c99269088h88c88y669661
对自定义加密后的字符串再进行解密后:
5aW95aW95a2m5LmgUEhQLGFkZmFzc2ZhcyE=
最后再进行base64解密后:
好好学习PHP,adfassfas!

你可能感兴趣的:(base64)