Safe encryption for short strings in PHP and Java
this is my first question here:
I want the PHP script to include encrypted user's ID on each page. I will then read it using JS and send it over to Java server where I decode the value.
I want to make it secure-ish so that people cannot fake their IDs. (Don't worry, this will not be used for authentication.)
The encrypted IDs might be MySQL's auto increment column 1,2,3.. and I'm not in a position to change that.
These properties would be nice to have:
- The encrypted IDs should be only valid for a day, ideally for one time use / a second
- T开发者_StackOverflowhe encrypted IDs should not be easily faked (ideally even by the users themselves)
Feel free to suggest other kinds of solutions. Thanks!
Using a secure hash function to hash a combination of a user id and some value that changes periodically might be a good idea. For example, you could pick a 128-bit random number each day, then set the ID to be the hash of that value concatenated with the user ID. Assuming that you use a good hash, like SHA-256, this is cryptographically secure.
Something along the lines of hashing a timestamp with the user ID would probably be best and checking to see the time difference between the timestamp given and the current timestamp. You'll have to ensure the difference acceptance is big enough to account for any server latency though.
Consider using an algorithm that the numbers have to pass in order to be valid. Bank cards, IMEI (mobile phones) and some other major ones use the Luhn Algorithm - http://en.wikipedia.org/wiki/Luhn_algorithm
I can't think of any to securely decrypt with only JavaScript, as you'd need to include the password in the source code, which isn't very secure.
The best way would be to encrypt and decrypt with PHP: you can call PHP from within JavaScript code (using AJAX.)
So, for example:
encrypt.php
<?php
$password = "KEYVALUE";
$secret_text = "USERID HERE"
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $password, $secret_text, MCRYPT_ENCRYPT);
echo $encrypted_text;
?>
Then you have something called decrypt.php, and all that is does is accept a GET argument, and the ONLY output is the decrypted text (no HTML code or anything. Technically you probably should use XML for AJAX, but since it's only one value...)
decrypt.php
<?php
$password = "KEYVALUE";
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $password, $_GET['decrypt'], MCRYPT_DECRYPT);
echo $decrypted_text;
?>
You can test this out by calling
decrypt.php?decrypt=encrypted_string
.
From here I'd call "decrypt.php?decrypt=encrypted_string" script from within JavaScript, and JavaScript can then read the decrypted value.
A quick introduction to AJAX can be found here: http://www.yourhtmlsource.com/javascript/ajax.html .
精彩评论