PHP代码<?php
/**
* cr4加密解密
* @link http://en.wikipedia.org/wiki/RC4
*/
class RC4
{
/**
* 加密
* @param string $key 私匙
* @param mix $data 需要加密的数据
* @param boolean $decrypted 是否解密
* @return 16进制字符串
*/
static public function Encrypted($key, $data, $decrypted=false)
{
$keyLength = strlen($key);
$S = array();
for($i = 0; $i < 256; $i++) $S[$i] = $i;
$j = 0;
for ($i = 0; $i < 256; $i++)
{
$j = ($j + $S[$i] + ord($key[$i % $keyLength])) % 256;
self::swap($S[$i], $S[$j]);
}
$dataLength = strlen($data);
$output = "";
for ($a = $j = $i = 0; $i < $dataLength; $i++)
{
$a = ($a + 1) % 256;
$j = ($j + $S[$a]) % 256;
self::swap($S[$a], $S[$j]);
$k = $S[(($S[$a] + $S[$j]) % 256)];
$output .= chr(ord($data[$i]) ^ $k);
}
return ($decrypted) ? $output : bin2hex($output);
}
/**
* 解密
* @param string $a 私匙
* @param mix $b 需要解密的数据
* @return 字符串
*/
static public function Decrypted($a, $b)
{
if (function_exists("hex2bin"))
{
return self::Encrypted($a, hex2bin($b), true);
}
else
{
return self::Encrypted($a, pack("H*", $b), true); // hex2bin php5.4才支持
}
}
static private function swap(&$a, &$b)
{
$tmp = $a;
$a = $b;
$b = $tmp;
}
}
echo $cipher = RC4::Encrypted('key', 'abcdefg');
echo "\n";
echo RC4::Decrypted('key', $cipher);
相关标签:PHP
本文原创发布php中文网,转载请注明出处,感谢您的尊重!