PHP实现rc4加密算法,此算法的解密方法是重新加密一次,便可还原
/*
* rc4加密算法
* $pwd 密钥
* $data 要加密的数据
*/
function rc4 ($pwd,$data)//$pwd密钥 $data需加密字符串
{
$key[] ="";
$Box[] ="";
$pwd_length = strlen($pwd);
$data_length = strlen($data);
for ($i = 0; $i < 256; $i++)
{
$key[$i] = ord($pwd[$i % $pwd_length]);
$Box[$i] = $i;
}
for ($j = $i = 0; $i < 256; $i++)
{
$j = ($j + $Box[$i] + $key[$i]) % 256;
$tmp = $Box[$i];
$Box[$i] = $Box[$j];
$Box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $data_length; $i++)
{
$a = ($a + 1) % 256;
$j = ($j + $Box[$a]) % 256;
$tmp = $Box[$a];
$Box[$a] = $Box[$j];
$Box[$j] = $tmp;
$k = $Box[(($Box[$a] + $Box[$j]) % 256)];
$cipher .= chr(ord($data[$i]) ^ $k);
}
return $cipher;
}
* rc4加密算法
* $pwd 密钥
* $data 要加密的数据
*/
function rc4 ($pwd,$data)//$pwd密钥 $data需加密字符串
{
$key[] ="";
$Box[] ="";
$pwd_length = strlen($pwd);
$data_length = strlen($data);
for ($i = 0; $i < 256; $i++)
{
$key[$i] = ord($pwd[$i % $pwd_length]);
$Box[$i] = $i;
}
for ($j = $i = 0; $i < 256; $i++)
{
$j = ($j + $Box[$i] + $key[$i]) % 256;
$tmp = $Box[$i];
$Box[$i] = $Box[$j];
$Box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $data_length; $i++)
{
$a = ($a + 1) % 256;
$j = ($j + $Box[$a]) % 256;
$tmp = $Box[$a];
$Box[$a] = $Box[$j];
$Box[$j] = $tmp;
$k = $Box[(($Box[$a] + $Box[$j]) % 256)];
$cipher .= chr(ord($data[$i]) ^ $k);
}
return $cipher;
}