<?php<br/>/**<br/> * 一个简单基于密匙的加解密类<br/> * 启用了压缩可用于传输大量文本 <br/> * 配合数字签名可以完成较为安全的数据传输.<br/> */<br/>class myEncrypt<br/>{<br/> const _privateKey = '_';<br/> public $key; # 密匙<br/> public $compressLevel; # 压缩级别 0 为不压缩<br/> public function __construct($key = null,$compressLevel = 0)<br/> {<br/> $key = md5(self::_privateKey.$key);<br/> $num = $this->getKeyNum($key);<br/> $this->key = array(<br/> 'main' => $key,<br/> 'num' => $num,<br/> );<br/> settype($compressLevel,'integer');<br/> $this->compressLevel = $compressLevel;<br/> }<br/> private function getKeyNum($key)<br/> {<br/> $keyReady = 0;<br/> for ($i=0;$i<strlen($key);$i++)<br/> {<br/> $keyReady += ord($key[$i]);<br/> }<br/> $keyReady = self::_privateKey.$keyReady;<br/> return $keyReady;<br/> }<br/> private function getDResult($content,$pKey)<br/> {<br/> $len = strlen($pKey);<br/> $count = ceil(strlen($content)/$len);<br/> $contentReady = array();<br/> for ($i=0;$i<$count;$i++)<br/> {<br/> $start = $i*$len;<br/> $current = substr($content,$start,$len);<br/> $contentReady[$i] = ($current ^ $pKey);<br/> }<br/> $content = implode($contentReady);<br/> return $content;<br/> }<br/> public function encrypt($content)<br/> {<br/> $key = $this->key['main'];<br/> $num = $this->key['num'];<br/> $content = base64_encode($content); # 这里使用base64是为了便于传输<br/> $content = $this->getDResult($content,$key);<br/> $content = $this->getDResult($content,$num);<br/> if ($this->compressLevel)<br/> {<br/> $content = gzcompress($content,$this->compressLevel);<br/> }<br/> $content = base64_encode($content);<br/> return $content;<br/> }<br/> public function decrypt($content)<br/> {<br/> $key = $this->key['main'];<br/> $num = $this->key['num'];<br/> $content = base64_decode($content);<br/> if ($this->compressLevel)<br/> {<br/> $content = gzuncompress($content);<br/> }<br/> $content = $this->getDResult($content,$num);<br/> $content = $this->getDResult($content,$key);<br/> $content = base64_decode($content);<br/> return $content;<br/> }<br/>}<br/>$myEncrypt = new myEncrypt('MoX!',9);<br/>$zString = str_repeat('测试一下压缩~',20);<br/>$encode = $myEncrypt->encrypt('测试下中文~abcdefg haha~'.$zString);<br/>echo $encode."<br /> ";<br/>$myEncrypt = new myEncrypt('MoX!',true);<br/>echo $myEncrypt->decrypt($encode);<br/>?>
一个简单基于密匙的加解密类
最新推荐文章于 2024-09-07 17:02:25 发布