user978905
user978905

Reputation: 5527

Trying to wrap my head around PHP password salt/encryption

Right now I am developing an application that will allow online registration. For development, the password check just checks a MySQL row to make sure the value matches the value in the input field.

This code checks to see that the row exists:

$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
                    $num = mysql_num_rows($res);
                    //check if there was not a match
                    if($num == 0){
                        //if not display error message
                        echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";

I'm confused about implementing a salt system. How would I alter this script to check for the encrypted password? I haven't found a great tutorial that explains this in detail.

Upvotes: 0

Views: 286

Answers (2)

Aaron
Aaron

Reputation: 359

A salt is a set of characters added to the beginning or end of the password before encryption and unencryption to make it harder to run a brute force attack.

Your first create the salt which is just a random fixed series of characters and then prepend it to the password before hashing it. You should also escape your data before putting it into the query to prevent MySQL injection attacks.

Do this when entering the pass into the database

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass']);
$pass_hash = md5($SALT.$password);
mysql_query(*query to insert $username and $pass_hash into db*)

To check if the password is correct

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['pass']);
$res = mysql_query(*query to extract $pass_hash from db where username==$username)
//get the password from the $res and put it in a var
if(md5($SALT.$pass_hash_from_db) == $password){*correct pass*} else {*invalid login*}

Set $SALT to some large random static string such as $SALT="WEHGFHAWEOIfjo;cewrxq#$%";

Upvotes: 2

Tobias
Tobias

Reputation: 9380

You would have to generate a new salt if the user registers and save it in your database.

// you save this in the database
$encPass = encFunction( $password.$salt );

and when some user wants to logint you check if this password is a the password column of this user.

Note:
- encFunction is your encryption function

Upvotes: 0

Related Questions