I'm trying to send encrypted data over the url to another site (using file_get_contents("anotherUrl.php?hash=$encryptedString")
. The problem is, sometimes, the encryption contains some special characters, like +, and this causes the decryption to fail.
Here are my encryption / decryption methods:
public function encrypt($string, $key)
{
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
}
public function decrypt($encrypted, $key)
{
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
}
Here's an example encrypted string which contains a +
, and I'm guessing that this causes the decryption to fail.
oWCrVPaS+5GbxcQFc0fulUk/zRAkDD60av4zlPiWskE=
Any ideas how I should solve this? I've tried to do urlencode()
and urldecode()
on the hash, however that also seems to cause the encryption to break. Is there a way to change the encryption algorithm to get it to only return url safe characters?
In order to solve this problem I now use the following (after 3 hours of pain), and it works great.
Feel free to copy and paste
Instead of using Base64 for encoding your data you can also use Base32 (RFC 4648) which is URL-safe because it only uses letters A–Z (case-insensitive) and the digits 2–7. There is already a PHP library for encoding/decoding. Note that Base32 takes ~20% more space than Base64.
You can also use URLcrypt which is a handy library helping you with encryption and Base32 encoding.
Take a look at this thread:
Passing base64 encoded strings in URL
Essentially you DO want to
urlencode()
before sending the string, however you do NOT want tourldecode()
at the other end.