Home > php教程 > PHP源码 > rc4加密解密

rc4加密解密

PHP中文网
Release: 2016-05-26 08:18:37
Original
3293 people have browsed it

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(&#39;key&#39;, &#39;abcdefg&#39;);
echo "\n";
echo RC4::Decrypted(&#39;key&#39;, $cipher);
Copy after login

                   

Related labels:
php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template