Codepath

Password Authentication

Password authentication is the most popular type of online user authentication.

The most secure way to perform password authentication is by encrypting passwords using a one-way Cryptographic Hash Algorithm.

The authentication process can be described in five steps.

  1. Encrypt user's preferred password.
  2. Store encrypted string (hash) with the user's record in the database.
  3. User submits their username and password from a login page.
  4. Encrypt the attempted password.
  5. Verify the new hash is the same as the stored hash.

It is not necessary to decrypt the stored password because the same input string should return the same output string.


Password Authentication in PHP

PHP (version 5.5 or later) simplifies password authentication with the functions password_hash() and password_verify(). These functions use bcrypt and incorporate best practices for password hashing so that developers do not risk making mistakes. They set the bcrypt format string, set a bcrypt cost parameter, and create a random salt to pass to bcrypt.

<?php
  // Encryption/Hashing
  $hashed_password = password_hash($password, PASSWORD_BCRYPT);

  // Verification example
  $is_match = password_verify($attempted_password, $hashed_password);
?>
Fork me on GitHub