How to encrypt the $_GET data in php? - php

As in php we use $_GET to pass variables in the url , i want to pass variables which include the id of the user which i want to be anonymous, so can something be done which can encrypt the variable before passing it and the the variable once taken on the page can be decrypted to get the original variable value.
for eg:
Before passing variable $id=10;
Passed in the url as $id=dasfgjg;
when taken from the url and decrypted $id=10;
How can this be achieved?

You can use an RC4 cipher if you intend to encrypt/decrypt only on the server-side
http://www.phpkode.com/source/s/rc4-cipher-0-1/rc4-cipher-0-1/RC4.php
$my_secret_key = '3klmsd94mms.saeo44o!!3le';
if( isset($_GET['p']) ) {
$id = RC4::decrypt($my_secret_key, $_GET['p']);
// ....
}
else {
echo 'Go to the page';
}

Just generate random strings (make sure it's unique) for each record in the database and save it there, too. Then use this as an identifier. Note that, of course, this has nothing to do with encryption.

A quick and dirty way to achieve this (for each request)
on the client, create a string like 'xx:10:yy' where xx and yy are strings consisting pf random characetrs
on the client, create a salted hash of the users salted/hashed password
use this hash as a key and the string from the first bullet as cleartext for encryption with e.g. crypt.js
in the request send the encrypted string and the salt
on the server use the transmited salt and the users salted/hashed password to recover the key
on the server use mcrypt or friends to decrypt the string
on the server use standard PHP text processing functions to recover the payload from the decrypted string

Related

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 . i.e; 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.

Convert ASP function to PHP to generate password

I am working on converting an ASP site to PHP. The site uses a 3rd party API. The 3rd party API requires a UserID which was stored in the database and a password for each user. The ASP site didn't save the passwords in the database, instead they used the following function to derive the password every time based on the UserID:
public static string GetLmsUserPassword(int userId)
{
var hash = userId.ToString().MD5();
return hash.Substring(15, 4) + hash.Substring(4, 4);
}
In PHP, I wrote the following:
function lms_password($user_id) {
$hash = md5((int)$user_id);
$password = substr($hash,15,4).substr($hash,4,4);
return $password;
}
However, it appears the password generated in PHP does not match the password in ASP. I am wondering if ASP does md5 differently?
An example UserID is actually a string, not just a number: 22E21F5D-7979-467E-928D-4EFCC323BDCB
The difference in results between the .NET and PHP versions could be due to the way each casts a string to an int. Try casting your example id in both, and compare.
ASP: var hash = userId.ToString().MD5();
See that ToString() part? That means the ID is probably being interpreted as a string.
Your PHP: $hash = md5((int)$user_id);
explicitly casts it as an int, which will hash to a completely different value.
An example UserID is actually a string, not just a number: 22E21F5D-7979-467E-928D-4EFCC323BDCB
So... why are you casting it as an int? :I
edit: I also like that the password appears to be statically generated from a hash of the userID. Very secure.

sha1 encode exact value of parameter instead of the variable value

I'm working with an application that requires sha1 encoding for certain form values.
The problem is that when I use the following
<?php echo(hash("sha1","par1=".$_POST['p1']."&par2=".$_POST['p2'])); ?>
It gives me a sha1 encoding of the actual string, while I want to get a sha1 encoding of the posted values, so in this example I want to get
<?php echo(hash("sha1","par1=firstvalue&par2=secondvalue")); ?>
How can I realize this? Is it actually that simple and am I thinking way to difficult?
That because it identifies that para1=some_value as string not para1 as variable and some_value string
To achieve what you want you should hash every variable alone
Or I suggest that you implement your own encoding algorithm
Why not do it like this? Though I would have though either way would result in the same thing....
$hash_this = "par1=".$_POST['p1']."&par2=".$_POST['p2'];
echo sha1($hash_this);
Though that will do it if you want to hash the string of the values all together, rather than the values, if you want to store the values - then you should probably hash each value, so you could at least compare them later. Useful for a login system where you want to save a password to a database, which is more secure than literally just storing the password...
$password = sha1($_POST['password']);
If you hash the string, you have no idea which value is wrong

md5 encrypt cookiedata with serialized array

I was attempting to
encrypt de cookie data with md5, but I can not validate the hash back.
It has got to do, with the fact that cookie_data is a serialized array, because normal stringvalues work ok.
It's actually from a codeigniter class, but it does not work??
Does anyone know what the problem might be?
$hash = substr($session, strlen($session)-32);
$session= substr($session, 0, strlen($session)-32);
if ($hash !== md5($session.$this->encrypt_key))
{........
and the cookie value is encrypted like this
$cookie_data = $cookie_data.md5($cookie_data.$this->encrypt_key);
EDIT
I found that the answer is to use urlencode en urldecode in the proces of creating and validate
md5 hashes, because setcookie does urlencode automaticly, and thereby possibly changing the hash.
thanks, Richard
You have a typo:
md5($sessie.$this->encrypt_key))
should be
md5($session.$this->encrypt_key))
If you develop with notices turned on you'll catch this kind of thing much more easily.
You're not encrypting your data, you're signing it.
md5 is a oneway function. It is not a reversible one, so you can't decrypt the data.
The only thing you can do is encrypt the original data (if you saved it elsewhere) and check the result of this second computation.
If the value retrieved and the new value calculated are the same, the hash you received is valid (As you are doing in your code).
EDIT
You know, with just three lines of code I will guess some possible causes:
$session doesn't contains at the beginning of your code the same value of cookie_data.
you are using multibyte strings and strlen is not mb aware (use the idioms substr($session,0,-32) to get the payload part of the string.
maybe substr doesn't cope with multibyte strings too, use explicitally mb_substr (or whatever it is called).
To me the first case is the more probable. For what I can see.
I was attempting to encrypt de cookie
data with md5, but I can not decrypt
it back for validation.
md5 isnt an encryption method. it creates a one-way hash that cant be turned back into the original data.
If you want to encrypt data try mcrypt

Need a simple hash in PHP

I need to create a simple hashing method for passing some data in a URL. It doesn't need to be very secure, it just shouldn't be obvious to most people.
The hash needs to contains the numerical id of the sender and the id of the recipient and I should be able to decode the data after reading the appended hash.
Any ideas? I'd like the hash to be a short as possible, simply because this url is meant to be shared via IM, email, etc..
Hash is one way only. If you want to decrypt it, you have to encrypt it. Try mcrypt with one of these.
For non secure stuff you can try base64_encode, You can also base_convert each numeric id from 10 to 36 digits or so. Multiplying the numbers with a secret constant could also help.
$obscurity = base_convert($recipientId * 42, 10, 36) . ':' . base_convert($senderId * 42, 10, 36)
Try base64 encoding/decoding. put together with the apache option "Multiviews" or apache mod_rewrite, would make your urls look like:
http://mysite.com/messages/[encoded string here]
base64 definitely should do the trick if you want to decode it again.
Note that this is not a 'hash', a hash generally means one-way encryption.
$senderId = 1234;
$recipientId = 5678;
$myString = $senderId . ":" . $recipientId;
echo base64_encode($myString);
You could use encryption, as mentioned by #OIS.
Or you could use a hash and store the hash values in a database keyed to sender id and recipient id. PHP has md5() and sha1() built in.

Categories