PHP Encrypt Decrypt using Base64
Posted by tech on
March 24, 2008
Here are two methods to encrypt and decrypt using Base64. I forgot where I got this from but these 2 methods are pretty handy. Make sure you remember your key as your string will be encrypted and decrypted according to what you specify as key. Key is a string here.
Usage is as follows:
$encrypted = encrypt("to encrypt string", "chitgoks");
$decrypted = decrypt($encrypted, "chitgoks");
$decrypted will return to encrypt string.
function encrypt($string, $key) {
$result = '';
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
return base64_encode($result);
}
function decrypt($string, $key) {
$result = '';
$string = base64_decode($string);
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return $result;
}









April 11th, 2010 at 4:33 am
Wonderful piece of content, this is very similar to a site that I have. Please check it out sometime and feel free to leave me a comenet on it and tell me what you think. I’m always looking for feedback.
September 4th, 2010 at 6:34 pm
Nice piece of code have resolve my problem. I just looking for this. Thumbs up.
September 4th, 2010 at 6:36 pm
thanks! do subscribe to my rss feeds
June 21st, 2011 at 12:34 pm
You’ve got great insights about PHP, keep up the good work!
July 13th, 2011 at 8:15 am
Thank you, thank you! Just what was needed! +1 for you.