PHP Proper Password Handling

It is important we encrypt passwords in some way. If they are stored in plain text, then it is trivial for an attacker to extract data such as credentials or payment info after a data breach.

Encrypting/Hashing Our Passwords

Encrypted passwords cannot be used for access on their own. They are essentially scrambled, not resembling the actual password. Password strength is irrelevant if they can just access them as plain text. We can use many algorithms for this but some inbuilt PHP functions include:

password_hash($password, <algorithm>, [options])

//options - cost ...
$option = 
    'cost' => 12,

This takes the password you pass it, and hashes/encrypts it based on the encryption method you give it.

We can use the function as content for a variable. The hash of the actual password to be uploaded to the database for example.

$passwordHash = password_hash($password, 

Original Sample Password:


Example End Hash:


Salting & Issues

Encrypted passwords are useless to a hacker in such form but can be brute-forced to get their real value. This takes a while depending on password complexity, but shortcuts can be taken.
A famous example is the concept of a rainbow table. This in short means that a given hash is already precomputed to represent 'x' password. This means a given hash can potentially be cross-referenced to a password in seconds.

We do have a solution to this. You can add a salt to the hash which in concept is a password for the password hash. This, in theory, makes every hash unique, making rainbow tables redundant.

A salt should be long and randomly generated. This is not invincible but does greatly improve security. You should never create your own salt, randomness is hard to replicate manually. The function password_hash( ) will auto-generate a salt and append it to the hash, that is unlikely to be precomputed.

Registration & Authentication

The hash will provide all the needed info for the password side of the logon for verification and access to the real data. We need to store the algorithm, the cost and the salt in the database

Upon registration, we will generate a hash-based upon the desired password and store it in the database. We need to be able to compare user input, which is not hashed to that of the hashed form in the database in such structure.

The original password is not stored anywhere but the user's memory and discretion. Luckily PHP makes this very easy for us, we have a verification function, as below:

password_verify($passwdAttempt, $passwordHash)

if (password_verify($passwdAttempt, $passwordHash)) {
 // Do action for correct password
else {
 // Do action for wrong password