php AES加密解密

cipher = $cipher;
    }

    public function set_mode($mode)
    {
        $this->mode = $mode;
    }

    public function set_iv($iv)
    {
        $this->iv = $iv;
    }

    public function set_key($key)
    {
        $this->secret_key = $key;
    }

    public function require_pkcs5()
    {
        $this->pad_method = 'pkcs5';
    }

    protected function pad_or_unpad($str, $ext)
    {
        if ( is_null($this->pad_method) )
        {
            return $str;
        }
        else
        {
            $func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
            if ( is_callable($func_name) )
            {
                $size = mcrypt_get_block_size($this->cipher, $this->mode);
                return call_user_func($func_name, $str, $size);
            }
        }
        return $str;
    }

    protected function pad($str)
    {
        return $this->pad_or_unpad($str, '');
    }

    protected function unpad($str)
    {
        return $this->pad_or_unpad($str, 'un');
    }

    public function encrypt($str)
    {
        if (version_compare(PHP_VERSION, '7.1', '>='))
        {
            return base64_encode(openssl_encrypt($str, 'aes-256-ecb', $this->secret_key, true));
        }
        else
        {
            $str = $this->pad($str);
            $td = mcrypt_module_open($this->cipher, '', $this->mode, '');

            if ( empty($this->iv) )
            {
                $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
            }
            else
            {
                $iv = $this->iv;
            }

            mcrypt_generic_init($td, $this->secret_key, $iv);
            $cyper_text = mcrypt_generic($td, $str);
            $rt=base64_encode($cyper_text);
            //$rt = bin2hex($cyper_text);
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);

            return $rt;
        }
    }

    public function decrypt($str){
        if (version_compare(PHP_VERSION, '7.1', '>='))
        {
            return openssl_decrypt(base64_decode($str), 'aes-256-ecb', $this->secret_key, true);
        }
        else
        {
            $td = mcrypt_module_open($this->cipher, '', $this->mode, '');

            if ( empty($this->iv) )
            {
                $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
            }
            else
            {
                $iv = $this->iv;
            }

            mcrypt_generic_init($td, $this->secret_key, $iv);
            //$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
            $decrypted_text = mdecrypt_generic($td, base64_decode($str));
            $rt = $decrypted_text;
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);

            return $this->unpad($rt);
        }
    }

    public static function hex2bin($hexdata) {
        $bindata = '';
        $length = strlen($hexdata);
        for ($i=0; $i < $length; $i += 2)
        {
            $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
        }
        return $bindata;
    }

    public static function pkcs5_pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    public static function pkcs5_unpad($text)
    {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text)) return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
        return substr($text, 0, -1 * $pad);
    }
}


load->model('player_model');
        $CI->load->model('bet_order_model');
        $CI->load->model('trans_log_model');

        $parm_m = $CI->input->get('m',true);
        $parm_account = isset($parm['account']) ? $parm['account'] : '';
        $parm_order_no = isset($parm['orderNo']) ? $parm['orderNo'] : ''; // 商户传过来的流水号
        $parm_money = isset($parm['money']) ? $parm['money'] : 0;
        $account_name = $parm_m.'_'.$parm_account;
        $money = intval(floatval($parm_money)*100); // 转换金额(正数)(这里转成以分为单位)
        $type = $parm['type']; // 转换类型(0存款,1提款)

        if($parm_order_no == ''){
            $data = ['code'=>STATE_CODE_FAIL,'msg'=>'流水号不能为空','data'=>new stdClass()];
            return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
        }

        $trans_log_id = 0;
        $trans_log = $CI->trans_log_model->get_by_order_no($parm_order_no,'id');
        if(empty($trans_log)){
            $trans_log_id = $CI->trans_log_model->add([
                'orderNo' => $parm_order_no,
                'account' => $parm_account,
                'merchantId' => $parm_m,
                'transType' => $type,
                'money' => $parm['money'],
                'ctime' => time()
            ]);
        }else{
            $data = ['code'=>STATE_CODE_FAIL,'msg'=>'该订单已经存在','data'=>new stdClass()];
            return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
        }

        if($parm_account == ''){
            $data = ['code'=>STATE_CODE_FAIL,'msg'=>'账号不能为空','data'=>new stdClass()];
            return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
        }



        if($money <= 0){
            $data = ['code'=>STATE_CODE_FAIL,'msg'=>'额度须大于0','data'=>new stdClass()];
            return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
        }

        $player = $CI->player_model->get_by_account($account_name,'id,sm_coins,sm_isRAM,sm_merchantId,sm_ip');
        if(!$player){
            $CI->player_model->create_account($account_name,$parm_account,$parm_m,'');
            $player = $CI->player_model->get_by_account($account_name,'id,sm_coins,sm_isRAM,sm_merchantId,sm_ip');
            if(!$player)
            {
                $data = ['code'=>STATE_CODE_FAIL,'msg'=>'创建玩家失败','data'=>new stdClass()];
                return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换:创建玩家失败');
            }
        }

        if($player['sm_isRAM'] == YES)
        {
            foreach (explode('|',KBE_POLLER_PORT_BASES) as $port){
                $coins = $type == TRANS_TYPE_SAVE ? $money : -$money;
                $res = intval(send_to_kbe(POLLER_TYPE_TRANS,['playerID'=>$player['id'],'coins'=>$coins],$port));
                if($res == 0){
                    $data = ['code'=>STATE_CODE_FAIL,'msg'=>'游戏引擎异常','data'=>new stdClass()];
                    return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换:服务器已关掉,但是sm_isRAM==1');
                }
                if($res != self::TRANS_STATE_UNFIND) // 找到了玩家
                {
                    if($trans_log_id > 0){$CI->trans_log_model->update($trans_log_id,['isSuccess'=>YES]);}
                    $data = ['code'=>STATE_CODE_SUCCESS,'msg'=>'','data'=>new stdClass()];
                    return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
                }
            }
            $data = ['code'=>STATE_CODE_FAIL,'msg'=>'找不到玩家','data'=>new stdClass()];
            return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换:在kbe层找不到玩家,但是sm_isRAM==1');
        }
        else // 不在线
        {
            switch ($type)
            {
                case TRANS_TYPE_SAVE:
                    $num = $CI->player_model->update($player['id'],['sm_coins'=>$player['sm_coins']+$money]);
                    if($num <= 0){
                        $data = ['code'=>STATE_CODE_FAIL,'msg'=>'保存数据失败','data'=>new stdClass()];
                        return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
                    }else{
                        $CI->bet_order_model->add([
                            'playerID' => $player['id'],
                            'merchantId' => $player['sm_merchantId'],
                            'settlement' => $money,
                            'balance' => $player['sm_coins']+$money,
                            'ip' => $player['sm_ip'],
                            'ctime' => get_microtime()
                        ]);
                        if($trans_log_id > 0){$CI->trans_log_model->update($trans_log_id,['isSuccess'=>YES]);}
                        $data = ['code'=>STATE_CODE_SUCCESS,'msg'=>'','data'=>new stdClass()];
                        return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
                    }
                    break;
                case TRANS_TYPE_GET:
                    if($player['sm_coins'] < $money){
                        $data = ['code'=>STATE_CODE_FAIL,'msg'=>'可取的钱不够','data'=>new stdClass()];
                        return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
                    }
                    $num = $CI->player_model->update($player['id'],['sm_coins'=>$player['sm_coins']-$money]);
                    if($num <= 0){
                        $data = ['code'=>STATE_CODE_FAIL,'msg'=>'保存数据失败','data'=>new stdClass()];
                        return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
                    }else{
                        $CI->bet_order_model->add([
                            'playerID' => $player['id'],
                            'merchantId' => $player['sm_merchantId'],
                            'settlement' => -$money,
                            'balance' => $player['sm_coins']-$money,
                            'ip' => $player['sm_ip'],
                            'ctime' => get_microtime()
                        ]);
                        if($trans_log_id > 0){$CI->trans_log_model->update($trans_log_id,['isSuccess'=>YES]);}
                        $data = ['code'=>STATE_CODE_SUCCESS,'msg'=>'','data'=>new stdClass()];
                        return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
                    }
                    break;
                default:
                    $data = ['code'=>STATE_CODE_FAIL,'msg'=>'参数不合法1','data'=>new stdClass()];
                    return $CI->load->view_echo(json_encode($data,JSON_UNESCAPED_UNICODE), 'api', '额度转换');
            }
        }
    }
}
key = $key;
    }
    function encrypt($input) {
        if (version_compare(PHP_VERSION, '7.1', '>='))
        {
            return base64_encode(openssl_encrypt($input, 'des-ecb', $this->key, true));
        }
        else
        {
            $size = mcrypt_get_block_size('des', 'ecb');
            $input = $this->pkcs5_pad($input, $size);
            $key = $this->key;
            $td = mcrypt_module_open('des', '', 'ecb', '');
            $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
            @mcrypt_generic_init($td, $key, $iv);
            $data = mcrypt_generic($td, $input);
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);
            $data = base64_encode($data);
            return preg_replace("/\s*/", '',$data);
        }
     }
    function decrypt($encrypted) {
        if (version_compare(PHP_VERSION, '7.1', '>='))
        {
            return openssl_decrypt(base64_decode($encrypted), 'des-ecb', $this->key, true);
        }
        else
        {
            $encrypted = base64_decode($encrypted);
            $key =$this->key;
            $td = mcrypt_module_open('des','','ecb','');
            //使用MCRYPT_DES算法,cbc模式
            $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
            $ks = mcrypt_enc_get_key_size($td);
            @mcrypt_generic_init($td, $key, $iv);
            //初始处理
            $decrypted = @mdecrypt_generic($td, $encrypted);
            //解密
            mcrypt_generic_deinit($td);
            //结束
            mcrypt_module_close($td);
            $y=$this->pkcs5_unpad($decrypted);
            return $y;
        }
     }
    function pkcs5_pad ($text, $blocksize) {            
        $pad = $blocksize - (strlen($text) % $blocksize);           
        return $text . str_repeat(chr($pad), $pad);    
     }       
    function pkcs5_unpad($text) {           
        $pad = ord($text{strlen($text)-1});         
        if ($pad > strlen($text))                
            return false;           
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad)                 
            return false;           
        return substr($text, 0, -1 * $pad);    
     }    
}     

//$a = new DES1('11112222');
//echo $a->encrypt('1,1_kxroot54321,1537254581,b4828fb1e71ea6154ca3d7f32521ca5a');
//
//
//# -*- coding: utf-8 -*-
//import base64
//import pyDes
//
//data = b"1,1_kxroot54321,1537254581,b4828fb1e71ea6154ca3d7f32521ca5a"
//k = pyDes.des(b"11112222", pyDes.ECB, b"", pad=None, padmode=pyDes.PAD_PKCS5)
//d = k.encrypt(data)
//print("Encrypted: %r" % d)
//print(base64.b64encode(d))
//print("Decrypted: %r" % k.decrypt(d))
//assert k.decrypt(d) == data

你可能感兴趣的:(php AES加密解密)