Best password encryption in php

Best password encryption in php

Hey, guys in this post we are going to discuss the best and probably the securest way to Encrypt password in PHP. Encryption of password is a day to day job for a PHP developer from creating a simple login form to creating a big eCommerce website we heavily use password encryption. Theirs a lot of question come to mind while password encryption. So we will tackle them one by one.

Why i should encrypt password?

Suppose your website got hacked and all your user database is in the hands of the hacker. If you do not encrypt password all your user credentials are in the hands of a hacker on the other hand if you encrypt password hacker cannot access users account because he has encrypted passwords, not original password.

Why i should leave MD5()?

md5() is not recommended for password encryption and their are thousand of online tools available to decrypt md5 encrypted passwords.
0SQAl

Best password encryption in php

Best password encryption in PHP till date is password_hash this method automatically add salts for your password and made then even harder to decrypt Added in 5.5.0

Code to encrypt password

<?php
	$password ="test123";
	$encPassword = password_hash($password,PASSWORD_DEFAULT);

	echo $encPassword;
?>

Output (Your output may be different because every time a random salt is added to password)
Capture


How to check password

Now the question arises that if every time a different password is generated then how will we able to check password? The answer to that question is password_verify

Code to check password

<?php
	$hash ="$2y$10$6npimTwfZwyg7w5YkuItauZ.GbhbbHeNcII4SuknxtyWwuhlfZL4W";
	$password = "test123";

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

Output
s

A Small problem

if i am using PHP version 5.3 how will i able to use this function? The answer is you can still use all the method. Their is a awseom library availblable will make use of all the password encryption method possible before 5.5.0 password_compact (library)

Encryption code with password_compact library

<?php
	require_once("libs/password.php"); //include the password_compact libarary
	$password ="test123";
	$encPassword = password_hash($password,PASSWORD_DEFAULT);
	echo $encPassword;
?>

One thought on “Best password encryption in php

Leave a Reply

Your email address will not be published. Required fields are marked *