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

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

/
error_reporting(0);
header("Content-Type:text/html;charset=utf-8");
class DES3
{
var iv = "xfdeqghd";
/
*
* @title 加密
* @param string 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;
           }
       }

}
// ret = dess->from_json(jsonpost));

你可能感兴趣的:(PHP7.2接口加解密(3DES)openssl方式 兼容旧版mcrypt)