Tuesday, December 16, 2008

Text encryption on PHP

A long time ago I had to implement text encryption on Java for some messages that needed to be sent through a socket, and I found a very good encryption algorithm on the net.

Recently I needed text encryption for a similar scenario, but this time the technology was PHP. So, I decided to "translate" this algorithm from Java to PHP and now I want to share it with you, in case you need it.

Encrypt:

function encrypt($text, $seed) {
$encText = "";
$pwLength = strlen($seed);
$i=6;
for ($x=0; $x < strlen($text); $x++) {
$i = ($i%$pwLength)+1;
$a = ord(substr($text, $x, 1));
$b = ord(substr($seed, $i-1, 1));
$encText .= ($a ^ $b);
$encText .= ",";
}
return $encText;
}

Decrypt:

function decrypt($text, $seed){
if(!$text == ""){
if (strlen($text) == 1)
return "999999";

$pwLength = strlen($seed);
$strText = "";
$hold;
$i = 6;
$crypt = explode("," ,$text);
for ($x = 0; $x < sizeof($crypt) - 1; $x++) {
if (strlen($crypt[$x])>2) {
$test=0;
$test = (int) $crypt[$x];
if ($test == 0) $crypt[$x] = substr($crypt[$x], 1,1);
}
$i = ($i % $pwLength) + 1;
$a = (int)($crypt[$x]);
$b = ord(substr($seed, $i-1, 1));
$hold = chr($a ^ $b);
$strText .= $hold;
}
return trim($strText);
}else{
return "";
}
}

Example:


$msg = "This is the best blog!";
$seed = "mySeed";
echo $msg;
$encrypted = encrypt($msg, $seed);
echo $encrypted;
$decrypted = decrypt($encrypted, $seed);
echo $decrypted;


Output:
This is the best blog!
57,17,58,22,69,13,30,89,39,13,0,68,15,28,32,17,69,6,1,22,52,68,
This is the best blog!

I hope this algorithm helps you protect your information!