php中des加解密,适用于php7.2以上版本,使用openssl加密扩展

本实例为(cbc模式),如果你需要用到(ECB模式)的话,记得把iv偏移量去掉,不写就是了

//des加密(cbc模式)
	public function encrypt($str,$key)
    {
    	$str = $this->pkcsPadding($str, 8);
        $v = pack('H*', "1234567890abcdef");
        $key = str_pad($key, 8, '0'); //3DES加密将8改为24
        $sign = openssl_encrypt($str, 'DES-CBC', $key,OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,$v);
        $sign = base64_encode($sign);
        return $sign;
    }


    //des解密(cbc模式)
	public function decrypt($encrypted,$key)
    {
        $encrypted = base64_decode($encrypted);
        $v = pack('H*', "1234567890abcdef");
        $key = str_pad($key, 8, '0'); //3DES加密将8改为24
        $sign = @openssl_decrypt($encrypted, 'DES-CBC', $key,OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,$v);
        $sign = $this->unPkcsPadding($sign);
        $sign = rtrim($sign);
        return $sign;
    }

    /**
     * 填充
     *
     * @param $str
     * @param $blocksize
     * @return string
     */
    private function pkcsPadding($str, $blocksize)
    {
        $pad = $blocksize - (strlen($str) % $blocksize);
        return $str . str_repeat(chr($pad), $pad);
    }

     /**
     * 去填充
     * 
     * @param $str
     * @return string
     */
    private function unPkcsPadding($str)
    {
        $pad = ord($str{strlen($str) - 1});
        if ($pad > strlen($str)) {
            return false;
        }
        return substr($str, 0, -1 * $pad);
    }

 

你可能感兴趣的:(php中des加解密,适用于php7.2以上版本,使用openssl加密扩展)