PHP mcrypt 实现对称加密(DES)算法


class DesUtils{
    private $key;
    private $td;
    private $ks;
    public function __construct($key){
        $this->key = $key;
        /* 打开加密算法和模式 */
        $this->td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_ECB, '');
        /* 创建初始向量,并且检测密钥长度。 
         * Windows 平台请使用 MCRYPT_RAND。 */
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), MCRYPT_RAND);
        $this->ks = mcrypt_enc_get_key_size($this->td);
        /* 初始化加密 */
        mcrypt_generic_init($this->td, substr($this->key, 0,$this->ks), $iv);
    }
    private function byteArr2HexStr($arrB){
        $iLen = strlen($arrB);
        $sb = array();
        for ($i = 0; $i < $iLen; $i++) {
            $intTmp = ord($arrB[$i]);
            // 把负数转换为正数
            while ($intTmp < 0) {
                $intTmp = $intTmp + 256;
            }
            // 小于0F的数需要在前面补0
            if ($intTmp < 16) {
                $sb[]="0";
            }
            $sb[] = dechex($intTmp);
        }
        return implode("", $sb);
    }
    private function hexStr2ByteArr($strIn){
        $iLen = strlen($strIn);
        $arrOut = array();
        for ($i = 0; $i < $iLen; $i = $i + 2) {
            //echo $i,PHP_EOL;
            $strTmp = substr($strIn, $i, 2);
            $arrOut[$i / 2] = chr(hexdec($strTmp));
        }
        return implode("", $arrOut);
    }
    public function encrypt($string){
        $pad = $this->ks - (strlen($string) % $this->ks);
        $string = $string.str_repeat(chr($pad),$pad);
        $encrypted = mcrypt_generic($this->td, $string);
        return $this->byteArr2HexStr($encrypted);
    }
    public function decrypt($encrypted){
        $encrypted = $this->hexStr2ByteArr($encrypted);
        $decrypted = mdecrypt_generic($this->td, $encrypted);
        $padding = ord($decrypted[strlen($decrypted)-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
    public function __destruct(){
        /* 结束解密,执行清理工作,并且关闭模块 */
        mcrypt_generic_deinit($this->td);
        mcrypt_module_close($this->td);
    }
}

$test = "3400000000000000000";
$des = new DesUtils("leemenz");// 自定义密钥
echo "身份证加密前的字符:" . $test. PHP_EOL;
$encrypted = $des->encrypt($test);
echo "身份证加密后的字符:" . $encrypted. PHP_EOL;
echo "身份证解密后的字符:" . $des->decrypt($encrypted). PHP_EOL;
echo "================================\n";
$test = "L23322中国6";
$des = new DesUtils("leemenz");// 自定义密钥
echo "身份证加密前的字符:" . $test. PHP_EOL;
$encrypted = $des->encrypt($test);
echo "身份证加密后的字符:" . $encrypted. PHP_EOL;
echo "身份证解密后的字符:" . $des->decrypt($encrypted). PHP_EOL;