PHP crypt(), password_hash() Functions (original) (raw)

Last Updated : 21 Jun, 2023

In the previous article on md5(), sha1(), and hash() Functions we saw that one of the major drawbacks of the method was that these algorithms were very fast due to less complexity and thus more vulnerable to attacks, they are even suggested not to use in a full-fledged project of greater importance. Thus, PHP now provides with a couple new methods to hash user passwords in a much more optimized and secure way. The methods are discussed as follows:

crypt() Function

Syntax:

string crypt ($string, $salt)

Parameters: The function an take up to a maximum of two parameters as follows:

Return Type: This function returns the hashed string. As crypt() was better than its predecessors it was widely used, but the reliability of the function was questionable, hence PHP now provides a built-in function to serve the purpose of Password Hashing and is recommended for use.

password_hash() Function

Syntax:

string password_hash($string, algo,algo, algo,options)

Parameters: The function an take up to a maximum of three parameters as follows:

Return Type: This function returns the hashed string on success or FALSE. Below program illustrates the working of crypt() and password_hash() in PHP:

PHP

<?php

$str = 'Password' ;

$options = [

`` 'cost' => 10,

`` 'salt' => '$P27r06o9!nasda57b2M22'

`` ];

echo sprintf( "Result of crypt() on %s is %s\n" ,

`` $str , crypt( $str , $options [ 'salt' ]));

echo sprintf( "Result of DEFAULT on %s is %s\n" ,

`` $str , password_hash( $str , PASSWORD_DEFAULT));

echo sprintf( "Result of BCRYPT on %s is %s\n" , $str ,

`` password_hash( $str , PASSWORD_BCRYPT, $options ));

?>

Output:

Result of crypt() on Password is $PFKQN2rkmKu6 Result of DEFAULT on Password is 2y2y2y10$yqFvDGy v2Tz4d/A/yulbFe5ISH9oR3gvU7GQLMYRKR7XQJnGpQOau Result of BCRYPT on Password is 2y2y2y10$JFAyN3Iw Nm85IW5hc2RhNOlEBYnR992.gf.5FqZhHSbln3a4jtQpi

Important points to note:

Reference: