<?php
date_default_timezone_set('Asia/Shanghai');
/**
* 3DES加密解密
* Created on 2010-03-12 by caixudong
*
*/
//if (class_exists('DesCrypt'))
// return NULL;
class DesCrypt {
var $key = '';
var $deviceid = '';
var $user = '';
var $lsh = '';
var $ciphertext = '';
var $hciphertext = '';
var $decrypted_data = '';
/**
* 加密
* @param $str
* @return string
*/
public function en($str) {
$cipher = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
if (mcrypt_generic_init($cipher, substr($this->key, 0, 8), $iv) != -1) {
$this->ciphertext = mcrypt_generic($cipher, $this->pad($str));
mcrypt_generic_deinit($cipher);
// 以十六进制字符显示加密后的字符
$this->hciphertext = bin2hex($this->ciphertext);
printf("<p>3DES encrypted:\n%s</p>", $this->ciphertext);
printf("<p>3DES HexEncrypted:\n%s</p>", $this->hciphertext);
}
mcrypt_module_close($cipher);
return $this->ciphertext;
}
/**
* 解密
* @param $str
* @return string
*/
public function de($str) {
$str = pack('H*', $str);
$cipher = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
if (mcrypt_generic_init($cipher, substr($this->key, 0, 8), $iv) != -1) {
$this->decrypted_data = mdecrypt_generic($cipher, $str);
mcrypt_generic_deinit($cipher);
}
mcrypt_module_close($cipher);
return $this->unpad($this->decrypted_data);
}
private function pad($data) {
$data = str_replace("\n", "", $data);
$data = str_replace("\t", "", $data);
$data = str_replace("\r", "", $data);
return $data;
}
private function 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);
}
}
如果是3des,将MCRYPT_DES修改为MCRYPT_3DES,个人笔记
php解密之DES/3DES
最新推荐文章于 2024-08-17 14:22:19 发布