views:

34

answers:

2

Hi There,

I need to encrypt a string using MySQL's AES_ENCRYPT function, then attach that encrypted string to the end of a URL, such that it can then be decrypted and used by a PHP script on the other end.

Basically, I am encrypting the string (using MySQL's AES_ENCRYPT), I am then using PHP's rawurlencode() function to make it "URL safe". I then pass the encrypted string in a URL, which is then retrieved by the PHP script on the other end where it gets successfully decrypted... about 95% of the time.

Seems as though about 5% of strings are encrypting in such a way that they are getting corrupted somewhere in the process, and can't be decoded on the other end after being passed by a URL. Can anyone help me out here? Is there a 100% fool-proof way to do this? I have also tried using urlencode() as well as base64_encode() in varying combinations.

Thanks.

A: 

URLs have a finite maximum length. AES-encrypted strings do not.

URLs are not an appropriate vector for passing arbitrary information. Using an HTTP POST is a much better way, if you must communicate over HTTP.

About why you are having problems: quoting from the PHP manual page on urlencode:

Note: Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2. PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use & instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities() or htmlspecialchars().

Borealid
Thanks for your response, I can confirm that string length is not the problem.
Callum
A: 

Solved.

Once I have encrypted the string using MySQL's AES_ENCRYPT function, I use PHP's bin2hex() function to convert that encrypted data (which is in binary form) in to Hexidecimal. I then pass the Hexidecimal as a string on the end of the URL. Once the URL is received on the other end, I then use this custom PHP function to revert the Hex string back to binary:

function hex2bin($data) {
    $len = strlen($data);
    return pack("H" . $len, $data);
}

From there, all that's left to do is decrypt the data using MySQL's AES_DECRYPT function, and wha-la. The original string is successfully restored.

Callum