但下面的版本作了一些調整
加入字元編碼轉換、演算法優化、使用PHP5語法
使用方法
$a = new AzDG();; $q = $a->Crypt('許功蓋中文測試','0123456789','big5'); echo $a->decrypt($q,'0123456789' );
class AzDG { private $strPrivateKey = '0123456789'; private $strDefaultCharset = 'big5'; private $strTargetCharset = ''; private $strSourceText = ''; private $intSourceLength = 0; function __construct() { } private function private_key_crypt($arg_strSourceText) { $strEncryptKey = md5($this - > strPrivateKey); $intCRCLength = 0; $strReturn = ""; $intSourceLength = strlen($arg_strSourceText); for ($i = 0; $i < $intSourceLength; ++$i) { if ($intCRCLength > 31) { $intCRCLength = 0; } $strReturn. = ($arg_strSourceText[$i] ^ $strEncryptKey[$intCRCLength++]); } return $strReturn; } public function crypt($arg_strSourceText, $arg_strPrivateKey = null, $arg_strCharset = null) { $this - > strSourceText = $arg_strSourceText; $this - > intSourceLength = strlen($this - > strSourceText); if (!is_null($arg_strPrivateKey)) { $this - > strPrivateKey = $arg_strPrivateKey; } if (!is_null($arg_strCharset) AND!empty($arg_strCharset)) { $this - > strTargetCharset = $arg_strCharset; if (!$this - > convert_encoding()) { die('編碼轉換失敗'); } } $strCRCKey = md5(microtime()); $intCRCLength = 0; $strTmp = ""; for ($i = 0; $i < $this - > intSourceLength; ++$i) { if ($intCRCLength > 31) { $intCRCLength = 0; } $strTmp. = $strCRCKey[$intCRCLength].($this - > strSourceText[$i] ^ $strCRCKey[$intCRCLength++]); } return base64_encode($this - > private_key_crypt($strTmp)); } public function decrypt($arg_strSourceText, $arg_strPrivateKey = null, $arg_strCharset = null) { if (!is_null($arg_strPrivateKey)) { $this - > strPrivateKey = $arg_strPrivateKey; } if (!is_null($arg_strCharset) AND!empty($arg_strCharset)) { $this - > strTargetCharset = $arg_strCharset; if (!$this - > convert_encoding()) { die('編碼轉換失敗'); } } $this - > strSourceText = $this - > private_key_crypt(base64_decode($arg_strSourceText)); $this - > intSourceLength = strlen($this - > strSourceText); $strReturn = ''; for ($i = 0; $i < $this - > intSourceLength; ++$i) { $strReturn. = ($this - > strSourceText[$i++] ^ $this - > strSourceText[$i]); } return $strReturn; } private function convert_encoding() { //預設轉碼失敗 $blnIconvPassed = false; if (function_exists('iconv') AND $strEncodedData = iconv($this - > strDefaultCharset, $this - > strTargetCharset. '//TRANSLIT', $this - > strSourceText)) { $blnIconvPassed = true; $this - > strSourceText = $strEncodedData; } //如果 iconv 轉換失敗,再嚐試用mb_convert_encoding編碼 else if (!$blnIconvPassed AND function_exists('mb_convert_encoding') AND $strEncodedData = @mb_convert_encoding($this - > strSourceText, $this - > strTargetCharset, $this - > strDefaultCharset)) { $blnIconvPassed = true; $this - > strSourceText = $strEncodedData; } return $blnIconvPassed; } }
1 則留言:
nice!
張貼留言