• PHP AES cbc模式 pkcs7 128加密解密


    今天在对接一个第三方接口的时候,对方需要AES CBC模式下的加密。这里简单写一个demo
    
    class Model_Junjingbao extends Model
    {
       
        private static $_partnerKey  = '6d70a09e4d0f8095';
        //获取库存,更新价格信息
        public static function test($productId=2780)
        {
           
            $data = array(
                'productId'=>$productId,
                'startTime'=>'2018-04-09',
                'endTime'=>'2018-04-10'
            );
       
             $str = json_encode($data);
            $xcrypt =  self::aes_cbc_pkpadding($str);
            
            var_dump($xcrypt);//加密结果
            var_dump(self::aes_cbc_pkpadding_back($xcrypt));//解密结果
        }
    
    
        //AES加密数据
        private static function aes_cbc_pkpadding($str)
        {
           
            $block= mcrypt_get_block_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC);
            $pad=$block-(strlen($str)%$block);
            if($pad<=$block) {
                $char=chr($pad);
                $str.=str_repeat($char,$pad);
            }
            $xcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::$_partnerKey, $str, MCRYPT_MODE_CBC);
          
           
            return $xcrypt;
        }
    
        //AES解密数据
        private static function aes_cbc_pkpadding_back($xcrypt)
        {
    
            $string = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::$_partnerKey, $xcrypt, MCRYPT_MODE_CBC);
            $slast = ord(substr($string, -1));
            $slastc = chr($slast);
            if (preg_match("/$slastc{" . $slast . "}/", $string)) {
                $string = substr($string, 0, strlen($string) - $slast);
                return $string;
            } else {
                return false;
            }
        }
    
    }
    
    执行test方法

    加密结果

    
    øæ׌“j·A" OÈ[ótcÚ‡2Y‰XXÒ¦½™Ép¬p[DâFw`?oàá¹d&x4(çôl£‰¡±Ü‘I¾'ä YÖsÓd°Ý·^$’4höè¶Â÷GÂ)
    

    解密结果

    
    {"productId":2780,"startTime":"2018-04-09","endTime":"2018-04-10"}
    

    原文地址:https://segmentfault.com/a/1190000016251926

  • 相关阅读:
    day 01
    day14
    day12
    day13
    day11
    day9
    day10
    day08
    day07
    day06
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9971623.html
Copyright © 2020-2023  润新知