美文网首页
PHP7.2接口加解密(3DES)openssl方式 兼容旧版m

PHP7.2接口加解密(3DES)openssl方式 兼容旧版m

作者: GAOJUNJUN | 来源:发表于2021-03-02 16:33 被阅读0次

    <?php
    /*
    *2021-3-2
    *使用3DES加密
    *必须开启openssl扩展
    *算法公开,请对key严格保密

    /
    error_reporting(0);
    header("Content-Type:text/html;charset=utf-8");
    class DES3
    {
    var key = "jt4j41n5fdefgssdfxkuxhak"; variv = "xfdeqghd";
    /
    *
    * @title 加密
    * @param string value 要传的参数 * @ //OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING //AES-128-ECB|AES-256-CBC|BF-CBC * @return json * */ public function encrypt(value)
    {

        //参考地址:https://stackoverflow.com/questions/41181905/php-mcrypt-encrypt-to-openssl-encrypt-and-openssl-zero-padding-problems#
        $value = $this->PaddingPKCS7($value);
        $key = $this->key;
        $iv = $this->iv;
        $cipher = "DES-EDE3-CBC";
        if (in_array($cipher, openssl_get_cipher_methods())) {
            $result = openssl_encrypt($value, $cipher, $key, OPENSSL_SSLV23_PADDING, $iv);
        }
        return $result;
    }
    
    /**
     * @title 解密
     * @param string $value 要传的参数
     * @return json
     * */
    public function decrypt($value)
    {
        $key = $this->key;
        $iv = $this->iv;
        $decrypted = openssl_decrypt($value, 'DES-EDE3-CBC', $key, OPENSSL_SSLV23_PADDING, $iv);
        $ret = $this->UnPaddingPKCS7($decrypted);
        return $ret;
    }
    
    
    private function PaddingPKCS7($data)
    {
        $block_size = 8;
        $padding_char = $block_size - (strlen($data) % $block_size);
        $data .= str_repeat(chr($padding_char), $padding_char);
        return $data;
    }
    
    private function UnPaddingPKCS7($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);
    }
       function from_json($s){
        
           $yz=preg_match('/[^,:{}\\[\\]0-9.\-+Eaeflnr-u \n\r\t]/',$s) ? '1' : '0';
           if($yz==1){
               $arr=json_decode($s,ture);
               return $arr;
               }
           }
    

    }
    // des = new DES3(); // echoret = des->encrypt("a=1&b=2") . "\n"; // echodess->from_json(dess->decrypt(jsonpost));

    相关文章

      网友评论

          本文标题:PHP7.2接口加解密(3DES)openssl方式 兼容旧版m

          本文链接:https://www.haomeiwen.com/subject/ahkxqltx.html