php rc4可加密解密函数整理。
/** * Crypt/decrypt strings with RC4 stream cypher algorithm. * * @param string $key Key * @param string $data Encripted/pure data * @see http://pt.wikipedia.org/wiki/RC4 * @return string */ function rc4($key, $data) { // Store the vectors "S" has calculated static $SC; // Function to swaps values of the vector "S" $swap = function (&$v1, &$v2) { $v1 = $v1 ^ $v2; $v2 = $v1 ^ $v2; $v1 = $v1 ^ $v2; }; $ikey = crc32($key); if (!isset($SC[$ikey])) { // Make the vector "S", basead in the key $S = range(0, 255); $j = 0; $n = strlen($key); for ($i = 0; $i < 255; $i++) { $char = ord($key{$i % $n}); $j = ($j + $S[$i] + $char) % 256; $swap($S[$i], $S[$j]); } $SC[$ikey] = $S; } else { $S = $SC[$ikey]; } // Crypt/decrypt the data $n = strlen($data); $data = str_split($data, 1); $i = $j = 0; for ($m = 0; $m < $n; $m++) { $i = ($i + 1) % 256; $j = ($j + $S[$i]) % 256; $swap($S[$i], $S[$j]); $char = ord($data[$m]); $char = $S[($S[$i] + $S[$j]) % 256] ^ $char; $data[$m] = chr($char); } return implode('', $data); }
使用方法:
秘钥 : ENCRYPT_KEY = 'n01nemN0KsIHytH6skEo';
明文(原文) : $data = 'type=php&id=2';
密文(加密后) :
$ciphertext = urlencode(base64_encode(rc4(ENCRYPT_KEY, $data . '&len=' . strlen($data))));
明文(解密后) :
$originaltext = rc4(ENCRYPT_KEY, base64_decode($ciphertext));