PHP的DES加解密

<?php
class DES
{
    protected $m_key;
    protected $m_iv;
    
    function DES($key, $iv) {
        $this->m_key = $key;
        $this->m_iv = $iv;
    }
    
    //加密
    function encrypt($str) {
        $size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
        $strPad = $this->pkcs5_pad($str, $size);
	    $strCbc = mcrypt_cbc(MCRYPT_DES, $this->m_key, $strPad, MCRYPT_ENCRYPT, $this->m_iv);
	    $strHex = bin2hex($strCbc);
	    $strUpper = strtoupper($strHex);
        return $strUpper;
    }
    
    //解密
    function decrypt($str) {
		$strLower = strtolower($str);
        $strBin = hex2bin($strLower);
        $strCbc = mcrypt_cbc(MCRYPT_DES, $this->m_key, $strBin, MCRYPT_DECRYPT, $this->m_iv);
        $strUnpad = $this->pkcs5_unpad($strCbc);
        return $strUnpad;
    }

    function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    
    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);
    }
}
?>
相關文章
相關標籤/搜索