Log in

View Full Version : Do I need to escape a string if it's being encoded?



Schmoopy
04-03-2009, 09:49 PM
Hi, as the title suggests, I have a password that I'm encrypting before it is inserted into the database, do I still need to mysql_real_escape_string it or not?

Here is the code if you're interested:



$salt = substr(sha1(uniqid(rand(), true)), 0 , 10); // Generate a unique 10 character salt
$encpass = sha1($salt . $_POST['password']); // Encrypt password with salt
$pass = $salt . $encpass; // Salt + Encrypted password, salt is prepended so it can be matched when a user logs in

$query = "INSERT INTO admin (user, pass) VALUES ('$user', '$pass')";

Twey
04-03-2009, 09:55 PM
In this case, no, you don't, but only because the return value of sha1() is guaranteed to contain only digits from 0 to F.

Your idea of a 'salt' is a little wacky. If you ever want to be able to work with the hashed (not encrypted) value again, then you need to be able to regenerate the salt: that means that anything random (like rand()) or unique (like uniqid()) is expressly not what you want, unless you store the results for later retrieval.

Schmoopy
04-03-2009, 10:01 PM
Ok thanks and yea I'm storing the salt along with the hash and just so you don't think I'm completely crazy I was following the guidelines as stated here:

http://phpsec.org/articles/2005/password-hashing.html

Twey
04-03-2009, 10:40 PM
You seem to have missed the other feature used there, though: prepared statements. :)

Schmoopy
04-03-2009, 11:45 PM
What do you mean by prepared statements? The fact he has what I have within a function?

Twey
04-04-2009, 04:21 AM
No, the method used of inserting values into an existing SQL query. It handles escaping and the like automatically.