MENU

3DES 解密方法(工作模式CBC/填充方式pkcs5padding) PHP代码

May 4, 2019 • 已被 257 位童鞋围观过 • 代码分享

原始数据需要PKCS5Padding的填充,经过Google搜索、查阅PHP文档后发现官方提供了PKCS5Padding的示例代码。

//加密时,pkcs5padding 填充方式
function pkcs5_pad ($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}
//解密时,pkcs5padding 填充方式
function pkcs5_unpad($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);
}

3DES 解密方法(工作模式CBC/填充方式pkcs5padding) PHP代码 带demo

<?php
//解密Padding
function pkcs5_unpad($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);
}
class MagicCrypt {
    private $iv = "yooer.me";//密钥偏移量IV,可自定义
    private $encryptKey = "123456789abc";//AESkey,可自定义
    //加密
    public function encrypt($encryptStr) {
        $localIV = $this->iv;
        $encryptKey = $this->encryptKey;
        $module = @mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, $localIV);
        @mcrypt_generic_init($module, $encryptKey, $localIV);
        //Padding
        $block = @mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC);
        $pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad
        $encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples
        //encrypt
        $encrypted = @mcrypt_generic($module, $encryptStr);
        //Close
        @mcrypt_generic_deinit($module);
        @mcrypt_module_close($module);
        return base64_encode($encrypted);
    }
    //解密
    public function decrypt($encryptStr) {
        $localIV = $this->iv;
        $encryptKey = $this->encryptKey;
        //Open module
        $module = @mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, $localIV);
        @mcrypt_generic_init($module, $encryptKey, $localIV);
        $encryptedData = base64_decode($encryptStr);
        $encryptedData = @mdecrypt_generic($module, $encryptedData);
        $encryptedData = pkcs5_unpad($encryptedData);
        return $encryptedData;
    }
}
$str = '我们都是好孩子www.yooer.me';
$encryptObj = new MagicCrypt();
echo "原始: {$str},长度: ",strlen($str),"\r\n";
$result = $encryptObj->encrypt($str);//加密结果
echo "加密: {$result},长度: ",strlen($result),"\r\n";
$go=$result;
echo "原始: {$go},长度: ",strlen($go),"\r\n";
$d_str = $encryptObj->decrypt($go);//解密结果
echo "解密: {$d_str},长度: ",strlen($d_str),"\r\n";


Last Modified: September 28, 2023