Zend - The PHP Company




Algorithms

Add Code


RC4 encryption function  

Type: code fragment
Added by: danzarrella
Entered: 06/02/2002
Last modified: 02/12/2001
Rating: **** (5 votes)
Views: 10532
A very easy to use RC4 function, written entirely in php, using the function on plaintext returns the Encrypted string and using it on encrypted text returns the plaintext... its that simple. The security of the algorythmn is dependant on the size of the key used and any size key can be used with this function.


<?php
function RC4($keyfile$data) { //ecncrypt $data with the key in $keyfile with an rc4 algorithm
    
$pwd implode(''file($keyfile));
        
$pwd_length strlen($pwd);
    for (
$i 0$i 255$i++) {
          
$key[$i] = ord(substr($pwd, ($i $pwd_length)+11));
            
$counter[$i] = $i;
        }
        for (
$i 0$i 255$i++) {
            
$x = ($x $counter[$i] + $key[$i]) % 256;
            
$temp_swap $counter[$i];
            
$counter[$i] = $counter[$x];
            
$counter[$x] = $temp_swap;

        }
        for (
$i 0$i strlen($data); $i++) {
                        
$a = ($a 1) % 256;
            
$j = ($j $counter[$a]) % 256;
            
$temp $counter[$a];
            
$counter[$a] = $counter[$j];
            
$counter[$j] = $temp;
            
$k $counter[(($counter[$a] + $counter[$j]) % 256)];
            
$Zcipher ord(substr($data$i1)) ^ $k;
            
$Zcrypt .= chr($Zcipher);
        }
        return 
$Zcrypt;
}
?>


Usage Example


$text="test";
$keyfile="key.txt";
$encrypted=RC4($keyfile, $text);
$plaintext=RC4($keyfile, $text);


Rate This Script





Search



This Category All Categories