PHP7 Password Hashing
In this article, we will learn how to store more secure password in database by password hashing.
Web security is an important topic, it attracts both developers who created the application and hackers who try to exploit the system. As the developers are using modern technology to advanced their applications, the attackers are also using advanced hacking technology. This results in a large number of web applications vulnerabilities.
PHP7 cryptography hash functions are considered more secure for digital signature, authentication, password hashing and much more web security. In this article, you will learn modern password hashing using PHP7 Sodium Cryptography Library. For this, we should have enabled Sodium extension. If you do not have this enabled, you can learn from here -
'Install PHP Libsodium in Wampserver'
Hash a password for storage
For password hashing, we have used 'sodium_crypto_pwhash_str()' hashing method, it generates an ASCII encoded hash for password storage.
sodium_crypto_pwhash_str(string $password, int $opslimit , int $memlimit)
$password - Password entered by the user at the time of registration.
$opslimit - It represents the maximum amount of computations to perform. PHP provides some constants to set this operation limit. In this article, we are using SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE.
$memlimit - It represents the maximum amount of RAM that the function will use. PHP provides some constants to set this limit. In this article, we are taken SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE to set limit. This below code generates a hash string of 97 bytes.
<?php $password = 'password'; $hash = sodium_crypto_pwhash_str( $password, SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE ); ?>
Use this generated hash string as a password value in the SQL insert query.
Verify user password
Now, let's know how to verify the user with the correct password at the time of login. For this, the PHP Sodium Crypto Library provides a function sodium_crypto_pwhash_str_verify() that verify a password matches with the stored hash.
sodium_crypto_pwhash_str_verify(string $hash , string $password )
This function accepts two parameters -
$hash - hash generated by sodium_crypto_pwhash_str() or fetched password hash value from the database storage.
$password - password entered by the user at the time of login.
<?php echo sodium_crypto_pwhash_str_verify($hash, $password) ? 'Correct password' : 'Error'; ?>
This function always returns a Boolean value, i.e., TRUE if the password and hash match, or FALSE otherwise.
Related ArticlesPHP7 Sodium Encryption Decryption
Recover forgot password using PHP and MySQL
PHP Secure User Registration with Login/logout
PHP user registration & login/ logout with secure password encryption