PHP使用对称加密算法(3DES)加密及解密示例

<?php
/**
 *    DESede(3DES)操作类库
 *    @author    Ken(QQ:2480990710)
 *    @blog		 http://ken.01h.net/
 *    @date      2020-3-25
 */
class DESede
{
    private $key = "";
    private $iv = "";

    /**
     * 构造
     * @param string $key
     * @param string $iv
     */
    function __construct($key, $iv)
    {
        $this->key = $key;
        $this->iv = $iv;
    }

    /**
     *加密
     * @param <type> $value
     * @return <type>
     */
    public function encrypt($value)
    {
        $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');  //ecb模式
        $value = $this->PaddingPKCS7($value);
        @mcrypt_generic_init($td, $this->key, $this->iv);
        $ret = mcrypt_generic($td, $value);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return $ret;
    }

    /**
     *解密
     * @param <type> $value
     * @return <type>
     */
    public function decrypt($value)
    {
        $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, '');  //ecb模式
        @mcrypt_generic_init($td, $this->key, $this->iv);
        $ret = trim(mdecrypt_generic($td, $value));
        $ret = $this->UnPaddingPKCS7($ret);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return $ret;
    }

    private function PaddingPKCS7($data)
    {
        $block_size = mcrypt_get_block_size('tripledes', 'ecb');  //ecb模式
        $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);
    }
}

//用法
$key = '0123456789ABCDEFFEDCBA98765432100123456789ABCDEF';
$iv = '';
$msg = '6210985840034852662';
$key = hex2bin($key);  //上面的key是16进制的,所以这里转为二进制。
$des = new DESede($key, $iv);
$result1 = $des->encrypt($msg);
echo '加密结果(base64编码): ' . base64_encode($result1) . '<br />';
echo '加密结果(16进制): ' . bin2hex($result1) . '<br />';
$result2 = $des->decrypt($result1);
echo '解密结果: ' . $result2;

?>

发表评论

邮箱地址不会被公开。 必填项已用*标注