php - How to hash a password with random salt? -


here code hashing password random salt. unfortunately, doesn't want work, gives incorrect password.

part 1 of script user encodes credentials.

<?php   echo "enter username \n";   $username = trim(fgets(stdin));   echo "enter password\n";   $password = trim(fgets(stdin));   //connecting database   $con=mysqli_connect("localhost","sqldata","sqldata","accounts");   // check connection   if (mysqli_connect_errno()) {     echo "failed connect mysql: " . mysqli_connect_error();   }   $salt = time();   $hashedpassword = sha1($password . $salt);   echo "$hashedpassword";   mysqli_query($con,"insert login (username, salt, password)     values ('$username', '$hashedpassword','$salt')");   mysqli_close($con) ?> 

the second part of script user enters credentials.

<?php   echo "enter username \n";   $username = trim(fgets(stdin));   echo "enter password\n";   $password = trim(fgets(stdin));   //connecting database   $db = mysql_connect("localhost","sqldata","sqldata") or die(mysql_error());   //selecting our database   $db_select = mysql_select_db("accounts", $db) or die(mysql_error());   $result= mysql_query("select * login username = '$username' ");   if ( !$result ) exit("$username wasn't found in database!");   $row = mysql_fetch_array($result);   $storedpassword = $row['password'];   $salt = $row['salt'];   $hashedpassword = sha1($password . $salt);   if ( $storedpassword != $hashedpassword ) {     exit( 'incorrect password!' );   } else {     echo "ok";   } ?> 

you're storing salt in password column, , vice-versa.

mysqli_query($con,"insert login (username, salt, password)    values ('$username', '$hashedpassword','$salt')"); 

changes to:

mysqli_query($con,"insert login (username, password, salt)    values ('$username', '$hashedpassword','$salt')"); 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -