<?php /** * 加密/解密函数 * * @param string $string 要加密的明文或要解密的密文 * @param string $operation DECODE=解密|ENCODE或其它=加密 * @param string $key 加密/解密的密钥 * @param int $expiry 密文有效期,0表示永久有效 * @return string 加密后的密文/解密后的明文 */ function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { $ckeyLength = 4; $key = md5($key ? $key : 'default_key'); $keyA = md5(substr($key, 0, 16)); $keyB = md5(substr($key, 16, 16)); $keyC = $ckeyLength ? $operation == 'DECODE' ? substr($string, 0, $ckeyLength) : substr(md5(microtime()) , -$ckeyLength) : ''; $cryptKey = $keyA . md5($keyA . $keyC); $keyLength = strlen($cryptKey); $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckeyLength)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyB) , 0, 16) . $string; $stringLength = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); for ($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptKey[$i % $keyLength]); } for ($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } for ($a = $j = $i = 0; $i < $stringLength; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result.= chr(ord($string[$i]) ^ $box[($box[$a] + $box[$j]) % 256]); } if ($operation == 'DECODE') { if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyB) , 0, 16)) { return substr($result, 26); } else { return ''; } } else { return $keyC . str_replace('=', '', base64_encode($result)); } } $string = 'PHP是世界上最好の语言'; $key = '这是密钥'; echo "原始的字符串:{$string}<br>" . PHP_EOL; // 原始的字符串:PHP是世界上最好の语言 // 加密操作 $ciphertext = authcode($string, 'ENCODE', $key); echo "加密后的密文:{$ciphertext}<br>" . PHP_EOL; // 加密后的密文:61f0FauPLccfurlvf3cJCQuSeLVAeN1jENbNLZ6elFynE6Sm2nnTpH2fgXJBC98MHdWX+9bN51st82E // 解密操作 $plaintext = authcode($ciphertext, 'DECODE', '这是密钥', $key); echo "解密后的明文:{$plaintext}<br>" . PHP_EOL; // 解密后的明文:PHP是世界上最好の语言
Copyright © 2024 码农人生. All Rights Reserved