class phpmcrypt{/* 操作句柄 */private $crypt = null;/* 生成的密钥 */private $key = null;/* 初始向量 */private $iv = null;/* 支持的最长密钥 */private $ks = null;/* 数据类型是否可以接受 */private $accept = false; // false 不可以接受 true 可以接受/* 是否需要序列化 */private $serialize = false; //false 不需要序列化 true 需要序列化 public function __construct($secretkey='!@#$%^'){ /* 打开加密算法和模式 */ $this->crypt = mcrypt_module_open('tripledes','','nofb',''); /* 创建初始向量,并且检测密钥长度。 */ $this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($this->crypt), mcrypt_rand); /* 获取支持的最长密钥 */ $this->ks = mcrypt_enc_get_key_size($this->crypt); /* 生成密钥 */ $this->key = substr(md5($secretkey),0,$this->ks);}/***数据类型是否可以接受和序列化*$data int|string 要加密的数据*return boolean*/private function acceptandserialize($data){ $type = gettype($data); switch($type){ case 'string': case 'integer': case 'float': case 'double ': $this->accept = true; $this->serialize = false; break; case 'array': case 'object': $this->accept = true; $this->serialize = true; break; default: $this->accept = false; $this->serialize = false; }}/***加密数据*$data mixed 要加密的数据*return string|boolean*/public function encrypt($data){ $this->acceptandserialize($data); if( empty($data) || ($this->accept == false) ){ return false; } //序列化 if( $this->serialize ){ $data = serialize($data); } /* 初始化加密 */ mcrypt_generic_init($this->crypt,$this->key,$this->iv); /* 加密数据 */ $encrypt = mcrypt_generic($this->crypt,$data); /* 字符串以 mime base64 编码。此编码方式可以让中文字或者图片也能在网络上顺利传输 */ $encrypt = base64_encode($encrypt); if( $this->serialize ){ $encrypt .='|'.$this->serialize; } /* 结束加密,执行清理工作 */ mcrypt_generic_deinit($this->crypt); return $encrypt;}/***解密数据*$data string 要解密的数据*return mixed*/public function decrypt($data){ if( empty($data) ){ return false; } /* 判断是否序列化 */ if( strpos($data,'|') ){ $tempdata = explode('|',$data); $data = $tempdata[0]; $this->serialize = $tempdata[1]; } /* 初始化解密 */ mcrypt_generic_init($this->crypt,$this->key,$this->iv); /* 解密数据 */ $data = base64_decode($data); $decrypt = mdecrypt_generic($this->crypt,$data); /* 解序列化 */ if( $this->serialize){ $decrypt = unserialize($decrypt); } /* 结束加密,执行清理工作 */ mcrypt_generic_deinit($this->crypt); return $decrypt;}public function __destruct(){ /* 关闭加密模块 */ mcrypt_module_close($this->crypt);}}//int|float|字符串$ophpmcrypt = new phpmcrypt(123);$encrypt = '中国*上海-021';$encrypt = $ophpmcrypt->encrypt($encrypt);echo $encrypt;echo '
';$decrypt = $ophpmcrypt->decrypt($encrypt);echo $decrypt;//数组|对象$ophpmcrypt = new phpmcrypt(123);$encrypt = array('name'=>'张三','age'=>100);$encrypt = $ophpmcrypt->encrypt($encrypt);echo $encrypt;echo '
';$decrypt = $ophpmcrypt->decrypt($encrypt);print_r($decrypt);
以上就介绍了php加密数据操作类,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。