November 01, 2008

Low level encryption in PHP

I was creating this site ih PHP where in there are lots of configuration details. Details like DB username and password, site theme information, etc. The site would be installed and used by an unknown person who would become the site admin. Now, if the admin is not so computer savvy and wanted to change some of the configurations, he could easily edit the configurations which could screw up several things. To correct the data, the admin will have to reinstall the whole site. In order to prevent this from happening, I wanted to encrypt the config data.

I used a simple conbination of hex conversion and binary packing to do this. Here is the code I used for this:


function hex2bin($h)
{
if (!is_string($h)) return null;
$r='';
for ($a=0; $a<strlen($h); $a+=2)
{
$r.=chr(hexdec($h{$a}.$h{($a+1)}));
}
return $r;

}

$config_data = file ("normal.txt");
$CFGSTR = "DO NOT EDIT THIS FILE";
foreach ($config_data as $n_str)
{
$hex_str = bin2hex ( $n_str );
$bin_str = pack ('h*', $hex_str);
$CFGSTR = $CFGSTR."\n".$bin_str;
}

$fp = fopen ("club.cfg", "w+");
fwrite ($fp, $CFGSTR, strlen ($CFGSTR));
fclose ($fp);

$cfg_data = file ("club.cfg");
echo "<hr>CONFIG DATA: <br>";
for ($i=1; $i<23; $i++)
{
$cfg_arr = unpack ('h*',$cfg_data[$i]);
$cfg = "";
foreach ($cfg_arr as $c)
$cfg = $cfg.$c;
$cfg = hex2bin ($cfg);

echo "$cfg <br>";
}


A brief explanation on the above code: The normal.txt file contains the ACSII data. This would be converted to a non-human readable format and stored in club.cfg file. My site is a club of sorts, so the name "club". Anyway, the first part of encryption is to convert the data to hex. Then pack it to a binary format. The reason why im converting it to hex first is to make the code platform independent. I am storing each configuration detail in a seperate line. So I can reference the data by the line number. The second foreach loop reads thils encrypted file and displays the data. The hex2bin function was created by someone else. (Ref + credits: http://us.php.net/bin2hex).

So a simple conbination of hex conversion and binary packing is good enough to create and easy low level data encryption in php.

Peace ..V,