How to Encrypt and Decrypt Passwords in PHP

PHP encryption is important to the privacy and safety of your web data. The API provides method password_hash() to generate a hash from the string and method password_verify() to verify that the given hash matches the given password. In this tutorial, we will learn How to Encrypt and Decrypt Passwords in PHP.
The following algorithms are currently supported when using this function:
  • PASSWORD_DEFAULT – Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
  • PASSWORD_BCRYPT – Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the “$2y$” identifier. The result will always be a 60 character string, or false on failure.
  • PASSWORD_ARGON2I – Use the Argon2i hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.
  • PASSWORD_ARGON2ID – Use the Argon2id hashing algorithm to create the hash. This algorithm is only available if PHP has been compiled with Argon2 support.
Password Encryption
The below example shows the method of using the password_hash() method:
Syntax:
Example:
Ouput
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.
Syntax:
Verifies that the given hash matches the given password. password_verify() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_verify()
Example:
Ouput:Password is valid!