Years ago while working through the framework of Hastymail, I came across a need to have a simple and fast lightweight encryption routine. At the time the mcrypt module of PHP was not so widely available as it is now, and I wanted something without external dependencies including PHP mods that were not default on most distros. RC4 is an older, lightweight encryption algorithm, by no means uncrackable, but suitable for certain encryption tasks in which limited overhead is required and cipher strength is not a top priority. So I wrote a simple RC4 implementation in PHP based on the by then widely available algorithm. It's a single function that takes two arguments, a string to encrypt/decrypt and a "secret key" that forms the basis of the encryption.
function simple_crypt($input, $key) {
$k_tmp = preg_split('//', $key, -1, PREG_SPLIT_NO_EMPTY);
foreach($k_tmp as $char) {
$k[] = ord($char);
}
unset($k_tmp);
$message = preg_split('//', $input, -1, PREG_SPLIT_NO_EMPTY);
$rep = count($k);
for ($n=0;$n<$rep;$n++) {
$s[] = $n;
}
$i = 0;
$f = 0;
for ($i = 0;$i<$rep;$i++) {
$f = (($f + $s[$i] + $k[$i]) % $rep);
$tmp = $s[$i];
$s[$i] = $s[$f];
$s[$f] = $tmp;
}
$i = 0;
$f = 0;
foreach($message as $letter) {
$i = (($i + 1) % $rep);
$f = (($f + $s[$i]) % $rep);
$tmp = $s[$i];
$s[$i] = $s[$f];
$s[$f] = $tmp;
$t = $s[$i] + $s[$f];
$done = ($t^(ord($letter)));
$i++;
$f++;
$enc_array[] = chr($done);
}
$coded = implode('', $enc_array);
return $coded;
}
Be warned it produces some oddball ascii characters in the cipher text so if saved in a db might require a blob field (not sure, I have never had a need to save the ciphertext in a db). RC4 is a bit antiquated now, but it is useful if you need something fast and you do not need it to have super secret security clearance. I still use this code today as a part of a system that produces unpredictable psudo-random links to files that contain within the encrypted payload a timestamp that allows us to track how long ago the link was produced so we can easily set an expiration. Since the next link produced for the same content is always different and realistically unpredictable we can combine this with the link expiration ability to create a really effective hotlinking protection system.
| No Images with this post |