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;
}









July 20th, 2011 at 8:20 am
Nice code thanks for help.
July 20th, 2011 at 8:25 am
@jombs: you’re welcome. do +1 this post
September 16th, 2011 at 5:08 am
Nice Job…
Continue……………
November 25th, 2011 at 12:24 am
Nice job…….
December 29th, 2011 at 3:12 pm
Hi, this works great but i am using the encrypted string to form part of a URL address and for some encryption a ‘+’ symbol is included which causes an error is there a way to stop ‘+’ symbols being used in the encryption?
Thanks in advance