天天看點

php 3DES|DES 加密解密(通用)

 phpseclib

php 3DES|DES 加密解密(通用)

<?php  

//set_include_path(get_include_path().path_separator.'phpseclib');  

include('crypt/des.php');  

$des = new crypt_des();  

$des->setkey('abcdefgh');  

$plaintext = 'a';  

$jiami = base64_encode($des->encrypt($plaintext));  

echo "encode:".$jiami."<br/>";  

echo "decode:".$des->decrypt(base64_decode($jiami));  

?>   

是以php端必須自定義一個函數對加密字元串進行pkcs7模式補位填充 。

另外一點就是雙方的key注意進行base64編碼,最後php端經過3des加密後得到的結果也需要進行base64編碼。

以上幾點都做好之後,加密結果就一緻了。

再谷歌一番發現這麼一段代碼(原作者“幻想曲.net”),實作了上述規則,這個3des加密類相容.net 和java :

php 3DES|DES 加密解密(通用)

class std3des  

{  

    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_3des, '', 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;  

     *解密 

    public function decrypt($value)  

        $ret = trim(mdecrypt_generic($td, base64_decode($value)));  

        $ret = $this->unpaddingpkcs7($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 substr($text, 0, -1 * $pad);  

}  

//使用  

include('std3des.class.php');  

$key = 'abcdefgh';  

$iv = 'abcdefgh';  

$msg = 'test string';  

$des = new std3des(base64_encode($key), base64_encode($iv));  

$rs1 = $des->encrypt($msg);  

echo $rs1 . '<br />';  

$rs2 = $des->decrypt($rs1);  

echo $rs2;  

?>