How to Store Encrypted Passwords in MySQL Database for Users on Your Website using PHP

Tiempo de lectura: 2 minutos

If you have a website, you need to securely store user passwords.

Storing passwords in plain text compromises user privacy and leaves an open door for hackers to access them if they enter the system.

One simple way to store these passwords is by applying a Hash function.

A Hash function is a one-way mathematical algorithm, meaning it cannot be reversed. All data encrypted using a Hash cannot be decrypted and will have the same number of characters.

Example:

Word: Dog
Hash Function: 33efffe3294

Word: Berry
Hash Function: 5f43a2aa94f

As seen in the example, the word “Dog” and the word “Berry” differ by only one letter, yet they generate two completely different Hash codes (logic would suggest that only one character of the Hash would change, but that’s not the case). This means that comparing words to guess the next Hash is not possible.

The interesting thing is that we can store passwords of varying lengths, and the Hash function will always return the same size of Hash.

Now you might be wondering, how do we use all of this?

We can think of the Hash as the license plate (unique) for each password or words it is applied to. Here’s what needs to be done:

To store the password:

  1. The user enters their password in plain text.
  2. The system applies a secure Hash function and generates the Hash string.
  3. The system stores this Hash string as the password associated with the user.

To authenticate in the system:

  1. The user enters their password in plain text.
  2. The system applies the same Hash function used to store it in the previous step.
  3. The system retrieves the stored password (Hash string) and compares it with the generated Hash.
  4. If they match, Bingo! The user is authenticated in the system.

In PHP, it would look something like this:

<?php
$password = "Dog";
$passwordHash = hash('md5', $password);
?>

In the line $passwordHash = hash('md5', $password);, the Hash string is generated using md5, but you can use different hash algorithms.

You can find the available hash algorithms on this website: https://www.php.net/manual/en/function.hash.php

Now you know how to properly store user passwords.

Leave a Comment