The Best Way to Store Password in Database - PHP 2017 Edition


As time is moving forward our computers are getting faster and faster traditional hashing algorithm have become more susceptible to cracking. There is a huge increase in security related attacks and we need to make sure that the user's password we store is secured and uncrackable. So how can we store the password in database securely?

There are 3 approaches of storing passwords in database

1) As plain text (Worst Method)

       Never every store password in plain text why? because many people use same passwords for all their login credentials. So if your site is hacked your users are in big trouble.

2) By encrypting using key before storing (Not recommended)

      Encrypting password using some secure key is another method. But this method has a huge flaw. If the attacker gets the key then he can simply decrypt every password. Some of the big MNC's like adobe use this method and they admire that they made mistake.

3) By Hashing the password (Recommended method)

     Hashing is the transformation of a string of characters into usually a shorter fixed-length value that represents the original string. There are many hashing algorithms out there like md5, sha256, Bcrypt etc. Out which md5 is most common and still used by many web developers out there. Even I used md5 in my first PHP project 2 years back.

MD5 is dead

      One of the main reason beside collision attack is because it is too fast. A modern computer is a medium grade graphic card can crack 10 Billion md5 hashes per second. Watch below video for more info on that

Now how to store password in 2017

     The answer is to use a very slow hashing algorithm with some random salt. The PHP official recommends one is the bcrypt algorithm. The bcrypt is very slow and since we are adding some random salt along with it is literally impossible for the attacker to crack a password. 

   PHP provide a default function called password_hash to hash the password using bcrypt with random salt and password_verify function to verify it. A sample code is given below.

<?php

echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT)."\n";

$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

 

Security
9th Mar 2017 12:39:32 PM
PHP SQL MySQL
9004

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.