PHP: Using password_hash() instead of crypt()

Passwords should be easy to remember but hard to guess. With the number of internet services increasing quickly, it becomes very difficult to remember passwords and hence most people tend to use the same password across various services. In case, one of them gets compromised, it becomes really easy for a hacker to gain access to other services.

While creating a web app, it’s really important that you never store passwords as plain text. Internet services that send you an email with your password as plain text can never be trusted, because it means that either your password is stored as plain text or it can be easily recovered from the algorithm it is being stored with. The best way to store passwords is by hashing it.

Hashing functions take the password string as input and throw out a hash which is completely different even if a single character differs. This way, it becomes nearly impossible to guess the password from the hash.

Using password_hash() function in PHP is the best way to encrypt user passwords and store them in database. password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

Example code:

<?php
	$password = "mypassword";
	echo password_hash($password,PASSWORD_BCRYPT );
 
	//outputs $2y$10$Om2NuBIEAFCpCZmyA5GfNOsxRxhtYlL9NRvXSg59KlH6J9z5HnT0O
?>

To match the user password with the hash, you can simply use the password_verify() function which returns a TRUE or FALSE based on whether the password matches the hash or not

<?php
	$hash = "$2y$10$Om2NuBIEAFCpCZmyA5GfNOsxRxhtYlL9NRvXSg59KlH6J9z5HnT0O";
	if (password_verify('mypassword', $hash)) {
    		echo 'Password is valid!';
	} else {
	    echo 'Invalid password.';	
	}
?>

This way, it is only possible to verify if the input matches the hash or not but isn’t possible to figure out the password using the hash. password_hash() saves you from creating salts and using it with crypt().

password_hash() works with PHP >= 5.5.0 but can also be used with PHP >= 5.3.7 using password_compat.

Leave a Reply