php 可逆的加密算法
阿新 • • 發佈:2017-06-30
implode lod clas mes red array 算法 strlen blog
代碼:
1 <?php 2 3 class Test { 4 5 private $authCodeKey = ‘khUvFB9pijNyCYMGZdzqeKalyg7dh‘; 6 7 function authCode($input, $key) { 8 9 # Input must be of even length. 10 if (strlen($input) % 2) { 11 //$input .= ‘0‘; 12 } 13 14 # Keys longer than the input will be truncated.15 if (strlen($key) > strlen($input)) { 16 $key = substr($key, 0, strlen($input)); 17 } 18 19 # Keys shorter than the input will be padded. 20 if (strlen($key) < strlen($input)) { 21 $key = str_pad($key, strlen($input), ‘0‘, STR_PAD_RIGHT);22 } 23 24 # Now the key and input are the same length. 25 # Zero is used for any trailing padding required. 26 27 # Simple XOR‘ing, each input byte with each key byte. 28 $result = ‘‘; 29 for ($i = 0; $i < strlen($input); $i++) { 30 $result.= $input{$i} ^ $key{$i}; 31 } 32 return $result; 33 } 34 35 /** 36 * 加密 37 */ 38 function encrypt($sessionId) { 39 40 $hashKey = $this->base64url_encode($this->authCode($sessionId, $this->authCodeKey)); 41 $hashKey = $this->base64url_encode($sessionId); 42 return $hashKey; 43 } 44 45 46 /** 47 * 解密 48 */ 49 function decrypt($hashKey) { 50 51 $authCodeKey = ‘khUvFB9pijNyCYMGZdzqeKalyg7dh‘; 52 $sessionId = $this->authCode($this->base64url_decode($hashKey), $this->authCodeKey); 53 $sessionId = $this->base64url_decode($hashKey); 54 return $sessionId; 55 } 56 57 // url傳輸需要替換部分字符 58 function base64url_encode($data) { 59 return rtrim(strtr(base64_encode($data), ‘+/‘, ‘-_‘), ‘=‘); 60 } 61 // url傳輸需要替換部分字符 62 function base64url_decode($data) { 63 return base64_decode(str_pad(strtr($data, ‘-_‘, ‘+/‘), strlen($data) % 4, ‘=‘, STR_PAD_RIGHT)); 64 } 65 }
測試代碼:
1 $uId = ‘gouge‘; 2 $signKey = ‘gouge-test123‘; 3 $timestamp = time(); 4 5 // 需要加密的值 根據實際情況添加 6 $signParam = array($uId, $timestamp, $signKey); 7 $sessionId = implode(‘,‘, $signParam); 8 9 $e = new Test(); 10 // 加密 11 $r = $e->encrypt($sessionId); 12 // 解密 13 $t = $e->decrypt($r); 14 15 echo $r; 16 echo "<br/>"; 17 echo $t;
輸出結果:
1、加密 =》Z291Z2UsMTQ5ODc5NTMxNixnb3VnZS10ZXN0MTIz
2、解密 =》gouge,1498795316,gouge-test123
php 可逆的加密算法