This is my first attempt in securely storing passwords and I would like to make sure that everything is done correctly. I was advised to use SHA-256 hashing alongside salt.
Assuming user submitted their password thorough form, we get the password via
$password = $_POST["password"];
What is correct way to salt $password and use SHA-256 hashing on it, so it can than be stored in a password field "password CHAR(64)" in a database?
Once done and stored how would I than compare value stored in a database to one user entered in a login form? Lets assume $loginPassword = $_POST["loginPassword"];
is what user entered.
If you're on PHP 5.5 or later, there's the built-in password_hash() and password_verify() with Bcrypt - if you're on PHP 5.3.7 or later, there's the password_compat compatibility library; all this is per the PHP.net Safe Password Hashing FAQ entry.
Essentially, on PHP 5.3.7 and above, replace the old crypt() with password_hash() and password_verify().
See my answer to PHP Secure password generation and storage for some more details on cost choice, but it boils down to the very simple:
to generate the hash, then you store the output string, and then verify with:
Both examples come from the PHP.net Password Hashing page.
Instead of using SHA family methods, you can use the
crypt()
function to salt it for you.Here is an example script (save and login) using PDO.
Save password in DB
Login script