欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PHP des 3des加解密

程序员文章站 2024-03-14 13:28:46
...

开启Mcrypt扩展,获取mcrypt的加密算法与模式列表:

$cipher_list = mcrypt_list_algorithms();//mcrypt支持的加密算法列表  
$mode_list = mcrypt_list_modes();   //mcrypt支持的加密模式列表  
echo '<xmp>';  
print_r($cipher_list);  
print_r($mode_list);  
echo '</xmp>';

封装了一个DES加解密的类 适用于MCRYPT_RIJNDAEL_128,3DES算法,PKCS7填充 其它未测

使用时记得更改算法与模式,将其中的MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC替换即可

<?php
class StdDes
{
    private $key = "";
    private $iv = "";

    /**
     * 构造,传递二个已经进行base64_encode的KEY与IV
     *
     * @param string $key
     * @param string $iv
     */
    function __construct($key, $iv)
    {
        if (empty($key) || empty($iv)) {
            echo 'key and iv is not valid';
            exit();
        }
        $this->key = $key;
        $this->iv = $iv;
    }

    /**
     *加密
     * @param <type> $value
     * @return <type>
     */
    public function encrypt($value)
    {
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
        $iv = base64_decode($this->iv);
        $value = $this->PaddingPKCS7($value);
        $key = base64_decode($this->key);
        mcrypt_generic_init($td, $key, $iv);
        $ret = base64_encode(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_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
        $iv = base64_decode($this->iv);
        $key = base64_decode($this->key);
        mcrypt_generic_init($td, $key, $iv);
        $ret = trim(mdecrypt_generic($td, base64_decode($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', 'cbc');
        $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);
    }
}
/*
//使用
include('StdDes.class.php');
$key = 'abcdefgh';
$iv = 'abcdefgh';
$msg = 'test string';
$des = new StdDes(base64_encode($key), base64_encode($iv));
$rs1 = $des->encrypt($msg);
echo $rs1 . '<br />';
$rs2 = $des->decrypt($rs1);
echo $rs2;
*/
?>