16
04
Secure Password Encryption with Password Hash In PHP

Hi friends in this post we going to discuss about the best and probably the secured way to encrypt the password in php. Now a days encryption of password is done from simple login form to create a big ecommerce website. Normally we used many encryption technique to encrypt the password. Some of is SHA and MD5. There will be lot question willl come to programmers mind while encrpting the password. We can see the answer one by one.

PHP Password Hashing

Why should i encrypt the password ?

Today most of the hackers are trying to hack the database directly to collect the user information. suppose our website is hacked by the hacker and all your user credential are taken by the hacker he can easily access the user account. In order to avoid this dangerous situation we must encrypt the password.

Why should we avoid using MD5 encryption and decryption ?

In the current situation, many online tools and many ready made coding is available to decrypt the md5 encrypted password.

What is the best password encryption in php ?

The best method of encrypting the password in the current date is password_hash this method automatically add salts to your password and made them very harder to decrypt.

Examples - How to encrypt the password using password_hash ?


 $password ="pass123";
 $encPassword = password_hash($password,PASSWORD_DEFAULT);
 
echo $encPassword;

Output - Your output may be different because a random salt is added to your password

$2y$10$65NKTMrc3psZOuy4nsgV2.8rmCV82Q4VavJxkPgGGqGQjlUwEglwm 

How to check or verify the password correct or not ?

The password is verified using password_verify method

Example - Code to verify password

$hash = "$2y$10$65NKTMrc3psZOuy4nsgV2.8rmCV82Q4VavJxkPgGGqGQjlUwEglwm";
$password = "pass123";

if(password_verify($password,$hash)){
        echo "Password is valid";
    }else{
        echo "Invalid password";
    }

Output:

Password is valid

Note :

If any one using php version 5.5 lesser password_hash function will not work. So you can download the library password_compact(library).

Example - How to encrypt the password with password_compact library

 require_once("libs/password.php"); //include the password_compact library
 $password ="pass123";
 $encPassword = password_hash($password,PASSWORD_DEFAULT);
 echo $encPassword;

By posted on - 16th Apr 2016