If I have this PHP script for a login system:
$user = $_POST['user_name'];
$pass = md5($_POST['user_pass']);
require_once("connection_file.php");
$sql = "SELECT * FROM login_table WHERE user_n = :us AND user_p = :password";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':us', $user, PDO::PARAM_STR);
$stmt->bindValue(':password', $pass, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
if($result)
{
//echo $msg = "user exist";
if(session_status() == PHP_SESSION_NONE)
{
session_start();
foreach($result as $row)
{
$hash = password_hash($row['user_pass'], PASSWORD_BCRYPT);
if(password_verify($row['user_pass'], $hash))
{
$_SESSION['userid'] = $row['user_id'];
$_SESSION['role'] = $row['user_role'];
header("Location: homepage.php");
}
}
}
}
else
{
$msg = "Wrong credentials";
header("Location: login_page.php");
}
And as you see I am already saving my password in database as MD5
and I am using $pass = md5($_POST['user_pass']);
to verify if the text input by the user is equal to MD5
hash.
Now my question is should I use the
password_hash
andpassword_verify
as I am using in this script ? Or usingMD5
would be enough ?And my second question is can I save passwords in database using the hash string result or it is okay to use the md5 one?
Yes, you should migrate to the new API and never use MD5 for this purpose again, immediately.
If you're not using
password_hash()
/password_verify()
and want to migrate your code to a more secure method, seamlessly:legacy_password
(or equivalent).legacy_password
toTRUE
).When a user attempts to login, first check if the
legacy_password
flag is set. If it is, first pre-hash their password with MD5, then use this prehashed value in place of their password. Afterwards, recalculate the bcrypt hash and store the new hash in the database, disabling thelegacy_password
flag in the process. A very loose example in PHP 7+ follows:Usage:
Proactively upgrading legacy hashes is a security win over an opportunistic strategy (rehashing when the user logs in, but leave the insecure hashes in the database for inactive users): With a proactive strategy, if your server gets compromised before everyone logs in again, their passwords are already using an acceptable algorithm (bcrypt, in the example code).
The above example code is also available in Bcrypt-SHA-384 flavor.
Also, this has nothing to do with encryption.