php 数据加密的三种方法,可逆

   //加密 入参加密方式
    public function encrypt($data){
      $id =json_encode($data);
      $str =base64_encode($id);
      $str = urlencode(base64_encode(openssl_encrypt($str, 'aes-256-cbc', \config('aes_passwd'), OPENSSL_RAW_DATA, \config('aes_iv'))));
      return $str;
    }
    //解密 入参加密方式
    public function decrypt($str){
     $str = openssl_decrypt(base64_decode($str), 'aes-256-cbc', \config('aes_passwd'), OPENSSL_RAW_DATA, \config('aes_iv'));
     $str = base64_decode($str);
     $str =json_decode(trim($str),true);
     return $str;
    }
    //返回数据加密和解密 $operation E加密 D解密
    public function encrypts($string, $operation, $key = 'fo_34r3=rKjjg') {
        $key = md5($key);
        $key_length = strlen($key);
        $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
        $string_length = strlen($string);
        $rndkey = $box = array();
        $result = '';
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($key[$i % $key_length]);
            $box[$i] = $i;
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'D') {
            if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
                return substr($result, 8);
            } else {
                return'';
            }
        } else {
            return str_replace('=', '', base64_encode($result));
        }}
    //加密函数
    function lockcode($code) {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        $num = $code;
        $code = '';
        while ( $num > 0) {
            $mod = $num % 35;
            $num = ($num - $mod) / 35;
            $code = $source_string[$mod].$code;
        }
        if(empty($code[3]))
            $code = str_pad($code,4,'0',STR_PAD_LEFT);
        return $code;
    }
//解密函数
    function unlockcode($code) {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        if (strrpos($code, '0') !== false)
            $code = substr($code, strrpos($code, '0')+1);
        $len = strlen($code);
        $code = strrev($code);
        $num = 0;
        for ($i=0; $i < $len; $i++) {
            $num += strpos($source_string, $code[$i]) * pow(35, $i);
        }
        return $num;
    }

 

posted on 2023-08-30 15:09  kevin_yang123  阅读(537)  评论(0编辑  收藏  举报