[php] Best way to store passwords in MYSQL database

Yes I know storing passwords in plain text is not advised.Is there a best and easy way to store passwords so that the application remains secure ??

This question is related to php

The answer is


You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.


Hashing algorithms such as sha1 and md5 are not suitable for password storing. They are designed to be very efficient. This means that brute forcing is very fast. Even if a hacker obtains a copy of your hashed passwords, it is pretty fast to brute force it. If you use a salt, it makes rainbow tables less effective, but does nothing against brute force. Using a slower algorithm makes brute force ineffective. For instance, the bcrypt algorithm can be made as slow as you wish (just change the work factor), and it uses salts internally to protect against rainbow tables. I would go with such an approach or similar (e.g. scrypt or PBKDF2) if I were you.


Passwords in the database should be stored encrypted. One way encryption (hashing) is recommended, such as SHA2, SHA2, WHIRLPOOL, bcrypt DELETED: MD5 or SHA1. (those are older, vulnerable

In addition to that you can use additional per-user generated random string - 'salt':

$salt = MD5($this->createSalt());

$Password = SHA2($postData['Password'] . $salt);

createSalt() in this case is a function that generates a string from random characters.

EDIT: or if you want more security, you can even add 2 salts: $salt1 . $pass . $salt2

Another security measure you can take is user inactivation: after 5 (or any other number) incorrect login attempts user is blocked for x minutes (15 mins lets say). It should minimize success of brute force attacks.


Store a unique salt for the user (generated from username + email for example), and store a password. On login, get the salt from database and hash salt + password.
Use bcrypt to hash the passwords.


best to use crypt for password storing in DB

example code :

$crypted_pass = crypt($password);

//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
   echo("hello user!")
}

documentation :

http://www.php.net/manual/en/function.crypt.php