PHP - Encryption and Decryption

From Global Programming Syntax

Jump to: navigation, search

Encryption and decryption can be useful for if you want to be able to retrieve passwords or securely transfer data. However usually the best way of storing passwords is using a hash inside a hash as it is then irreversible. But for things like emails, you may want to use an encryption so only encrypted results are stored in the database. This way if someone hacks into your database then all emails and hashed/encrypted data will be safe. That is as long as you use a strong enough encryption. One of the things that you must be aware of is that reversible encryption will usually mean that the encoded result is longer in length than the original string resulting in more disk space being used. While this might sound like a bad thing it is actually quite good as it provides more uniqueness to the encryption and the data is spread out through more characters. For example, 4 characters could be decoded to 1 character making it harder for the hacker to decipher for the algorithm. An example of a basic encryption algorithm is as follows:

<?php
function text_encode($input) {
$arr=str_split($input,1);
$result='';
foreach($arr AS $val) {
$b=floor(ord($val)/4);
$a=$b+$b+32+($val%4);
$b+=64-(ord($val)%4);
$c=64+(ord($val)%4);
$result.=chr($a).chr($b).chr($c);
}
return $result;
}
 
function text_decode($input) {
$arr=str_split($input,3);
$result='';
foreach ($arr AS $group) {
$sub=str_split($group,1);
$c=ord($sub[2]);
$c-=64;
$b=ord($sub[1]);
$b-=(64-$c);
//echo $b;
$chr=$b*4;
$chr+=$c;
$result.=chr($chr);
}
return $result;
}
 
$text=text_encode('Testing...');
echo text_decode($text);
?>

Now you can see how to encode and decode text your next question might be when or why would I ever use a reversible encryption. Basically if you have a database with user details then it would be best to encrypt the personal details so they can never be stolen even if the database is hacked. In addition you may use this in php generated text files or as a safe way transferring data between two servers. So be safe by using encryption on sensitive data.

Personal tools
languages
page stats
Toolbox