The Secure Way to Store Passwords with PHP

Passwords are indisputably one of the most sensitive data types to deal with for web developers, especially back end developers who are in charge of PHP and MySQL. Storing passwords is not tricky considering you are just required to do a one-way conversion of them:

$password = 'ilovjenny84';
$salt = 'SHAKY SHARKY 333'; // whatever string
$password_hash = sha1($salt.sha1($password.$salt)); // $password_hash = 4c3c8cbb4aa5de1c3ad9521501c6529506c6e5b4

At user sign-in, you just need to hash the entered password all the same way again with the identical $salt you used for storing the password, and compare it with the stored hash string.

Mathematically speaking, with the same attempted password and a consistent salt, the generated hash string will be exactly the same with that stored in the database. From the nature of SHA1 algorithm, you can be rest assured that the attempted password is exactly the same with the password whose hash string is stored.

7 thoughts on “The Secure Way to Store Passwords with PHP”

      1. You are wrong. MD5 is not cracked.
        MD5 is just popular that there are many Rainbowtables and Online Databases.
        But there have been some researches about collisions which are not useable by normal crackers or even on salted hashes.

        1. I’m afraid it is. Familiarize yourself with what a collision is. The moment the research results are published, it’s over. It IS usable by normal crackers. A few minutes on a single notebook can get the job done.

          It’s cryptography for crying out loud, when an encryption / hashing method is left far behind the advance edge, it’s simply over.

      1. Furthermore,

        a) SHA-1 is not strong enough. You should be using Eksblowfish/bcrypt, SHA-256 or SHA-512.
        b) DO NOT use the same salt in every password. Read the link that Yang Yang posted for info on why.

  1. i second clark’s comment
    as a hacker , my security system uses the first 5 letters of my client’s password as the salt for storing the clients password (the minimum length of password is 10) while registering .
    and while login , i use the the first 5 letters of the password provided to login as the salt, to compare the password so , no salts are on my servers , only hashes

Comments are closed.

Scroll to Top