Encrypt password before storing in database?

Use php's crypt library. Md5 is not encryption, it is hashing.

Also, salt your passwords. Why?

  • This answer
  • Another good answer

While the answer below is technically still correct, php has new recommendations with regards to the hashing algorithms to use. Their recommendation, as of php >= 5.5.0, is to use the password_hash and password_verify functions to hash and verify hashed passwords . As an added benefit, these functions automatically include an individualized salt as part of the returned hash, so you don't need to worry about that explicitly.


If you don't care about retrieving the actual password's value (from the database encrypted value), you can run a one-way hash algorithm on it (such as sha1). This function will return a specific length string (hash) which cannot be used to find the original string (theoretically). It is possible that two different strings could create the same hash (called a collision) but this shouldn't be a problem with passwords.
Example: $pass = sha1($_REQUEST['pass']);

One thing, to make it a little more secure is to add a salt to the hash and run the hash function again. This makes it more difficult to generate a password hash maliciously since the salt value is handled server-side only.
Example: $pass = sha1(sha1($_REQUEST['pass']).sha1("mySalt@$#(%"));


First, you should create a random user salt. Then you should store that and the password hash in the database.

$salt = md5(unique_id().mt_rand().microtime());
$pass = sha1($salt.$_REQUEST['pass']);

and save the $salt and $pass in the database. Then when they go to login you look up their row and check the hash:

$user = query('SELECT * FROM `user` WHERE username = ?', array($_REQUEST['username']));

if($user)
{
    // If the password they give maches
    if($user->pass === sha1($user->salt. $_REQUEST['pass']))
    {
        // login
    }
    else
    {
        // bad password
    }
}
else
{
    // user not found
}

Creating a user salt for each account insures rainbow tables are useless and anyone that broken into your server would have to brute-force each password.