Open In App

How to Secure hash and salt for PHP passwords ?

Salting and hashing is a technique to store the password in a database. In cryptography, salting means to add some content along with the password and then hashing it. So salt and hash provide two levels of security. Salting always makes unique passwords i.e if there are two same passwords, after salting, the resulting string will change. Salting used along with hashing increases the level of security of the passwords.

Salting and hashing: In PHP, storing the password by salting and hashing is done by the password_hash() method. This method takes three parameters and returns a final hash of that password.



Syntax:

string password_hash( string $pass, int $algo, array $options )

Parameters:



Return Value: It returns the hashed password and FALSE on failure.

Example: This example is a demonstration of showing the password_hash(), making of hash and comparing it.




<?php
  
// Store the string into variable
$password = 'Password';
  
// Use password_hash() function to
// create a password hash
$hash_default_salt = password_hash($password,
                            PASSWORD_DEFAULT);
  
$hash_variable_salt = password_hash($password,
        PASSWORD_DEFAULT, array('cost' => 9));
  
// Use password_verify() function to
// verify the password matches
echo password_verify('Password',
            $hash_default_salt ) . "<br>";
  
echo password_verify('Password',
            $hash_variable_salt ) . "<br>";
  
echo password_verify('Password123',
            $hash_default_salt );
  
?>

Output:

1
1
0

In this example, the password_verify() method is used to compare the hash created with the string entered as a parameter. It takes the hash and the string to be compared as parameters and return true if the password is correct else it returns false.

Article Tags :