How to Secure Passwords in PHP?

 Hi There,

In this tutorial you will learn How to Secure Passwords in PHP?

Password hashing is one of the most basic security considerations that must be made when designing any application that accepts passwords from users.

The best way to encrypt and decrypt passwords is to use a standard library in PHP.

These are some things to keep in mind when handling the password.

  1. Never use md5(), sha1 for securing your password, even with salt, it is always dangerous!!
  2. Never try to make your own password hashing. Someone could easily outrun your smartness putting the system vulnerable.
  3. Make your password secured with latest hashing algorithms as below.
  4. To generate a hash from the string, we use the password_hash() function.

Generate hash using  password_hash() function.

(PHP 5 >= 5.5.0, PHP 7)

password_hashCreates a password hash

    
  
<?php

    // Your original Password
    $password = 'Pccdh@429@*io.';

    //PASSWORD_BCRYPT or PASSWORD_DEFAULT use any in the 2nd parameter
    /*
    PASSWORD_BCRYPT always results 60 characters long string.
    PASSWORD_DEFAULT capacity is beyond 60 characters
    */
    $password_encrypted = password_hash($password, PASSWORD_BCRYPT);

    ?>
 
 

Verify your password using password_verify() function:

 
   
    <?php 
    if (password_verify($password_inputted_by_user, PASSWORD_BCRYPT)) {
        // Success!
        echo 'Password Matches';
    }else {
        // Invalid credentials
        echo 'Password Mismatch';
    }
 
 

 password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

 Reference: https://www.php.net/manual/en/function.password-hash.php


Comments

  1. Sir,
    Very Useful Tutorial...

    In this password_hash method.. After Encryption We cant decrypt?

    ReplyDelete
  2. Thanks for your comment. We can't decrypt it. Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash.

    ReplyDelete

Post a Comment