欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

aes/cbc/pkcs5padding/128加解密

程序员文章站 2024-03-14 14:42:46
...
    //******aes/cbc/pkcs5padding/128加解密******
    private function aesEncrypt($data,$iv=''){
        $enc_key = 'KlW';//随机生成16为由大小写字符和数字组成的字符串
        $enc_iv = self::aesRandom(16,'1234567890abcdefghijklmnopqrstuvwxyz');//随机生成16位iv
        if($iv){
            $enc_iv=$iv;
        }
        $method = MCRYPT_RIJNDAEL_128;
        $mode = MCRYPT_MODE_CBC;
        //优化
        $block = mcrypt_get_block_size($method, $mode);
        $pad = $block - (strlen($data)%$block);
        $pad = $data.str_repeat(chr($pad), $pad);

        $td = mcrypt_module_open($method, '', $mode, '');
        mcrypt_generic_init($td , $enc_key , $enc_iv);
        $encrypt = mcrypt_generic($td, $pad);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return base64_encode($enc_iv.$encrypt);//iv拼密串之后base64
    }

    private function aesDecrypt($data){
        $dec_key = 'lW';//随机生成16为由大小写字符和数字组成的字符串
        $data = base64_decode($data) ;//base64
        $dec_iv = substr($data, 0, 16);//前16位为iv
        if(strlen($dec_iv)<16){
            return false;
        }
        $data = substr($data,16);       //16位后未密串

        $method = MCRYPT_RIJNDAEL_128;
        $mode = MCRYPT_MODE_CBC;
        $td = mcrypt_module_open($method, '', $mode, '');
        mcrypt_generic_init($td , $dec_key , $dec_iv);
        $decrypt = mdecrypt_generic($td, $data);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        //Remove the padding
        $pad = ord($decrypt[($len = strlen($decrypt))-1]);
        //优化
        $beforePad = strlen($decrypt) - $pad;
        $decrypt = substr($decrypt, $beforePad) == str_repeat(substr($decrypt, -1), $pad) ? substr($decrypt, 0, $len - $pad) : $decrypt;
        return $decrypt;
    }

    private function aesRandom($length, $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789')
    {
        $hash = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++)
        {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
    private function checkOpenid($openid){
        if(!$openid){
            $json = json_encode(array('success'=>false,'msg'=>'参数非法'));
            return $json;
        }
//        $openid = str_replace(' ', '+', urldecode($openid));
        return $this->aesDecrypt(urldecode($openid));
    }
相关标签: 加解密