Reputation: 11845
How can I sanitize a string that receives a hash+random salt?
I can remove the white spaces, check the length and use mysqli_real_escape_string
, but is it sufficient? The filter_var
is really useful but it can't help in this case, right?
Upvotes: 3
Views: 19923
Reputation: 1700
Just to be clear, you're receiving from an un-trusted source a hash (effectively random data) + salt (actually random data), and you want to 'sanitize' it? There is probably a definition of sanity that applies (a data format like base64 encoding, a maximum / expected length), but I strongly suspect there is a functional security mistake in there somewhere.
Most notably, why are you accepting a hash+salt from an un-trusted source, rather than accepting a password and doing the transformation within your trusted environment? Accepting a hash+salt from an un-trusted source probably turns them into plain-text equivalents (you lose the benefit you got from hashing and salting the original password).
Upvotes: 2
Reputation: 1056
First validate that the password matches your given validation rules. You can use a regular expression for this. Often passwords may consistent of a-z, 0-9, perhaps some punctuation and must be within a certain length - say 6-12 characters. Use preg_match()
to validate the string for its contents and length. Something like preg_match('/^[a-z0-9]{6,12}$/i',$pass)
might be a start.
Next you can hash the password. You may use the function crypt()
to do so. This will create a one-way encrypted string that you can use to compare against later when the user attemps to authenticate.
Finally, to store the password, yes using mysqli_real_escape_string()
will do the trick to prepare it for use in your SQL insert or update statement.
Upvotes: -1
Reputation: 437336
If you are going to put the variable in an SQL query, then you either need to call mysqli_read_escape_string
or (even better!) use prepared statements.
There's no other sanitization you need to do. However, if the value will be coming from freeform user input (e.g. a text box instead of a drop down menu) then you may also want to trim whitespace and lowercase it as a courtesy to the user (to correct accidental mistakes they might make). It really depends on the application.
Upvotes: 2