How to Encrypt and Decrypt Password in PHP

In our previous tutorial, we have explained how to make password generator with strength checker using JavaScript. In this tutorial, we will explain how to create secure password with PHP.

Having a secured and strong password is important since there are always security threats to web applications. So it’s very important to use strong and secure password to avoid the chances of Brute force attack or any other security breach.

Creating a strong and secure password is always challenge in PHP. Thanks to PHP Password API (available in version 5.5.0 and above) that provided best secured way to encrypt and decrypt passwords. The API provide method password_hash() to generate a hash from the string and method password_verify() to verify that the given hash matches the given password.

So let’s proceed to implement password encryption and decryption with PHP.

1. Password Encryption

We can use method password_hash() to generate a new password hash from the string. There are algorithms (PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I, PASSWORD_ARGON2ID ) supported by this method.


We can use the PASSWORD_DEFAULT algorithm that returns the password hash that can expand beyond 60 characters. Additional options can also be passed to this function to set the cost of encryption and also the salt to be used during hashing.

<?php
  
  $userPassword = "mypassword@123";
  
  $passwordHash = password_hash($userPassword, 
          PASSWORD_DEFAULT);
  
  echo "Generated password: ".$passwordHash;
  
?>

Ouput:

$2y$10$AqtJMX9YfkLlF1ZXgsaLzu02aqY1HK5/uELya2blIZhxNr7kjDjKW

2. Password Decryption

We can use the method password_verify() to verify that the given hash that generated by password_hash(), matches the given password. The method returns true if the password and hash match otherwise it return false.

<?php
  
  $userPassword = "mypassword@123";
  
  $hash = 
"$2y$10$AqtJMX9YfkLlF1ZXgsaLzu02aqY1HK5/uELya2blIZhxNr7kjDjKW";
  
  $verified = password_verify($userPassword, $hash);
  
  if ($verified) {
      echo 'Password is verified!';
  } else {
      echo 'Password is not correct!';
  }
  
?>

Ouput:

Password is verified!


Leave a Reply

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