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









October 5th, 2009 at 9:30 am
This is a great piece of work. Got a PayPal donation area?
October 5th, 2009 at 9:33 am
Never mind - found that donation box and sent some. Thanks, I hope many people send you donations for your sharing.
October 5th, 2009 at 9:37 am
thanks ubernerd!
you are the second one to give a donation in this blog. thank you!
January 24th, 2010 at 1:27 am
This does not seem to work when the string being encoded has a line feed.
Line feeds were converted to space after decoding. Any fix for that?
January 24th, 2010 at 2:09 am
ems. not as of the moment but perhaps you can convert your line feed to some other characters and convert it back once you have it decrypted