<?php
class McryptModel
{
protected $td = '';
protected $iv = '';
protected $key = '';
private static $instance = null;
private function __construct($cipher,$mode,$key)
{
$this->cipher = $cipher;
$this->mode = $mode;
$this->key = $key;
}
public static function getInstance($cipher=MCRYPT_RIJNDAEL_128,$mode=MCRYPT_MODE_CBC,$key='xingdong365')
{
if(self::$instance === null){
self::$instance = new self($cipher,$mode,$key);
}
return self::$instance;
}
public function encrypt($str)
{
$td = mcrypt_module_open($this->cipher,'',$this->mode,'');//打开算法模块
$this->td = $td;
$iv_size = mcrypt_enc_get_iv_size($td);//获取向量大小
$iv = mcrypt_create_iv($iv_size,MCRYPT_RAND);//初始化向量
$this->iv = $iv;
$num = mcrypt_generic_init($td,$this->key,$iv);//初始化加密空间
$encrypt = mcrypt_generic($td,$str);//执行加密
mcrypt_generic_deinit($td);//结束加密,执行清理工作
return base64_encode($encrypt);
}
public function decrypt($str)
{
$str = base64_decode($str);
$td = $this->td;
mcrypt_generic_init($td,$this->key,$this->iv);
$decrypt = mdecrypt_generic($td,$str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);//关闭算法模块
return $decrypt;
}
}
$m = McryptModel::getInstance();
echo $e = $m->encrypt('hello');
echo "<hr>";
echo $m->decrypt($e);
//des加密
function des_encrypt($encrypt, $key='xingdong365'){
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES,MCRYPT_MODE_ECB),MCRYPT_RAND);
$passcrypt = mcrypt_encrypt(MCRYPT_DES ,$key, $encrypt, MCRYPT_MODE_ECB, $iv);
$resturn = base64_encode($passcrypt);
return $resturn;
}
//des解密
function des_decrypt($decrypt, $key='xingdong365'){
$decoded = base64_decode($decrypt);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES,MCRYPT_MODE_ECB),MCRYPT_RAND);
$resturn = mcrypt_decrypt(MCRYPT_DES ,$key, $decoded, MCRYPT_MODE_ECB, $iv);
return $resturn;
}
action
本站未注明转载的文章均为原创,并采用
CC BY-NC-SA 4.0授权协议,
转载请注明来源,谢谢!如本站内容对你有所帮助的话,欢迎订阅关注
邢栋博客,唠嗑(分享)每日的折腾经历。
已有 0 条评论