简体   繁体   中英

Encrypted values (mcrypt_encrypt) in URL parameters generating different results while requesting.How to tackle the situation?

I am using the following function to encrypt a string ($str) using a key ($key) to make a unique key.

Sample Code:

<?php

$key = "####";
$str = "123456789";

$encrypted_key = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $str, MCRYPT_MODE_CBC, md5(md5($key))));

echo $encrypted_key; // 3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw+6WAns=
?>

The function is returning values consisting special characters including '+' . I am storing this values in database as a unique ID.

However in certain conditions, I need to pass the $encrypted_key through URLs . ie; for using it with RESFful web services

Sample URL:

www.example.com/index.php?encrypted_key=3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw+6WAns=

But this when requested through URL will decode '+' into 'spaces'

Code:

echo $encrypted_key = $_REQUEST['encrypted_key'];

// 3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw 6WAns=

This conversion is further affecting the DB checks :

'3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw 6WAns=' against '3rfmDKb/Ig5FuUnkY8fiHpqA3FD4PflXMksJw+6WAns='

Also I am having a concern of storing these encrypted values into indexed MySQL DB columns.

What should be the best practice to be adopted here? Any advise will be highly appreciated.

This answer only addresses the representation, not the likely-to-be-wrong use of crypto.

When you build objects that have special representation rules like database queries, paths in URLs, HTML code, JS code, and so on, you must ensure that you perform the proper kind of encoding of the values so that they roundtrip without harm.

For database query parameters, do not use string concatenation. Use prepared statements and placeholders.

For URLs, use the proper URL encoding function or an URL builder to construct your URL, do not blindly concatenate strings.

First, is not a good idea to use encrypted values as Unique ID or as Conditional Field, because they will change for the same value. This is very commom in encryption. If an encryption algorithm don't change the result for the same entry, it is not a good encryption.

Second, I had the same problem to deal with encryption and URL, and in my case a made my own encryption algorithm, using only valid characters for URL.

It is not dificult to implement an encryption: I used the ASCII code, one simple key, one simple math function, and nothing more. To decryption, I "reversed" the math function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM