PHP7.2+ 版本,DEC-CBC加解密

PHP技术
416
0
0
2022-06-17
标签   PHP加密
代码备份录——PHP7.2 加解密之—— DES-CBC

加解密

public static function encrypt($str,$key){
        $str = urlencode($str);
        $str = base64_encode($str);
        $str = self::pkcsPadding($str, 8);
        // 此处根据自己不同偏移量进行修改 
        $v = $key;//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 = strtoupper(bin2hex($sign));
        return $sign;
    }

    //des解密(cbc模式) 
    public static function decrypt($encrypted,$key){
        $encrypted = hex2bin($encrypted);
        // 此处根据自己不同偏移量进行修改 
        $v = $key;//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 = self::unPkcsPadding($sign);
        $sign = rtrim($sign);
        $sign = base64_decode($sign);
        $sign = urldecode($sign);
        return $sign;
    }

相关代码

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

    }

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