Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

PHP - Plus sign with GET query

I have a PHP script that does basic encryption of a string through the method below:

<?php
$key = 'secretkey';
$string = $_GET['str'];

if ($_GET['method'] == "decrypt")
{
    $output = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "");
}

if ($_GET['method'] == "encrypt")
{
    $output= base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
}

echo $output;
?>

An example of a URL to encrypt a string would look like this:

Encrypt.php?method=encrypt&str=the quick fox

Which would return this as the encrypted string:

LCuT/ieVa6cl3/4VtzE+jd9QPT3kvHYYJFqG6tY3P0Q=

Now to decrypt the string all you have to do is change the "method" query to "decrypt", like so:

Encrypt.php?method=decrypt&str=LCuT/ieVa6cl3/4VtzE+jd9QPT3kvHYYJFqG6tY3P0Q=

The only problem is that when that encrypted string is decrypted it returns this:

??§rYV}ì35??·n?ì(??X8T;b

I have narrowed down the problem to the plus sign that is in the encrypted string. PHP's GET method seems to translate a plus sign into a blank space. I have searched this bug and found out that it has already been filed here. I have tried different methods listed on that page and others with no success. The closest I got is by using this:

$fixedstring = str_replace(" ", "+", $string);

and then using $fixedstring in the encryption methods, the problem is, upon decryption, all blank spaces are converted to plus signs. Any ideas?

I know using POST would make more sense but I am using GET for specific reasons. I will spare the details.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you'll read the entirety of that bug report you'll see a reference to RFC 2396. Which states that + is reserved. PHP is correct in translating an unencoded + sign to a space.

You could use urlencode() the ciphertext when returning it to the user. Thus, when the user submits the ciphertext for decryption, you can urldecode() it. PHP will do this automatically for you if it comes in via the GET string as well.

Bottom line: The + must be submitted to PHP as the encoded value: %2B


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...