175

How much more safe is this than plain MD5? I've just started looking into password security. I'm pretty new to PHP.

$salt = 'csdnfgksdgojnmfnb';

$password = md5($salt.$_POST['password']);
$result = mysql_query("SELECT id FROM users
                       WHERE username = '".mysql_real_escape_string($_POST['username'])."'
                       AND password = '$password'");

if (mysql_num_rows($result) < 1) {
    /* Access denied */
    echo "The username or password you entered is incorrect.";
} 
else {
    $_SESSION['id'] = mysql_result($result, 0, 'id');
    #header("Location: ./");
    echo "Hello $_SESSION[id]!";
}
3
  • Note php 5.4+ has this built in Commented Feb 10, 2014 at 8:23
  • Also see Openwall's PHP password hashing framework (PHPass). Its portable and hardened against a number of common attacks on user passwords.
    – jww
    Commented Oct 12, 2014 at 0:11
  • 1
    Obligatory "use PDOs instead of string interpolation", for people stumbling across this question today.
    – anon
    Commented May 17, 2018 at 19:08

7 Answers 7

275

The easiest way to get your password storage scheme secure is by using a standard library.

Because security tends to be a lot more complicated and with more invisible screw up possibilities than most programmers could tackle alone, using a standard library is almost always easiest and most secure (if not the only) available option.


The new PHP password API (5.5.0+)

If you are using PHP version 5.5.0 or newer, you can use the new simplified password hashing API

Example of code using PHP's password API:

<?php
// $hash is what you would store in your database
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT, ['cost' => 12]);

// $hash would be the $hash (above) stored in your database for this user
$checked = password_verify($_POST['password'], $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}

(In case you are still using legacy 5.3.7 or newer you can install ircmaxell/password_compat to have access to the build-in functions)


Improving upon salted hashes: add pepper

If you want extra security, the security folks now (2017) recommend adding a 'pepper' to the (automatically) salted password hashes.

There is a simple, drop in class that securely implements this pattern, I recommend: Netsilik/PepperedPasswords (github).
It comes with a MIT License, so you can use it however you want, even in proprietary projects.

Example of code using Netsilik/PepperedPasswords:

<?php
use Netsilik/Lib/PepperedPasswords;

// Some long, random, binary string, encoded as hexadecimal; stored in your configuration (NOT in your Database, as that would defeat the entire purpose of the pepper).
$config['pepper'] = hex2bin('012345679ABCDEF012345679ABCDEF012345679ABCDEF012345679ABCDEF');

$hasher = new PepperedPasswords($config['pepper']);

// $hash is what you would store in your database
$hash = $hasher->hash($_POST['password']);

// $hash would be the $hash (above) stored in your database for this user
$checked = $hasher->verify($_POST['password'], $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}


The OLD standard library

Please note: you should not be needing this anymore! This is only here for historical purposes.

Take a look at: Portable PHP password hashing framework: phpass and make sure you use the CRYPT_BLOWFISH algorithm if at all possible.

Example of code using phpass (v0.2):

<?php
require('PasswordHash.php');

$pwdHasher = new PasswordHash(8, FALSE);

// $hash is what you would store in your database
$hash = $pwdHasher->HashPassword( $password );

// $hash would be the $hash (above) stored in your database for this user
$checked = $pwdHasher->CheckPassword($password, $hash);
if ($checked) {
    echo 'password correct';
} else {
    echo 'wrong credentials';
}

PHPass has been implemented in some quite well known projects:

  • phpBB3
  • WordPress 2.5+ as well as bbPress
  • the Drupal 7 release, (module available for Drupal 5 & 6)
  • others

The good thing is that you do not need to worry about the details, those details have been programmed by people with experience and reviewed by many folks on the internet.

For more information on password storage schemes, read Jeff`s blog post: You're Probably Storing Passwords Incorrectly

Whatever you do if you go for the 'I'll do it myself, thank you' approach, do not use MD5 or SHA1 anymore. They are nice hashing algorithm, but considered broken for security purposes.

Currently, using crypt, with CRYPT_BLOWFISH is the best practice.
CRYPT_BLOWFISH in PHP is an implementation of the Bcrypt hash. Bcrypt is based on the Blowfish block cipher, making use of it's expensive key setup to slow the algorithm down.

0
32

Your users will be much safer if you used parameterized queries instead of concatenating SQL statements. And the salt should be unique for each user and should be stored along with the password hash.

2
  • 1
    There is a good article about security in PHP at Nettuts+, password salting is also mentioned. Maybe you should take a look at: net.tutsplus.com/tutorials/php/… Commented Oct 18, 2009 at 10:38
  • 3
    The Nettuts+ is a very bad article to use as a model - it includes use of MD5 which can be brute forced very easily even with salt. Instead, just use the PHPass library which is far, far better than any code you may find on a tutorial site, i.e. this answer: stackoverflow.com/questions/1581610/…
    – RichVel
    Commented Nov 8, 2011 at 11:58
13

A better way would be for each user to have a unique salt.

The benefit of having a salt is that it makes it harder for an attacker to pre-generate the MD5 signature of every dictionary word. But if an attacker learns that you have a fixed salt, they could then pre-generate the MD5 signature of every dictionary word prefixed by your fixed salt.

A better way is each time a user changes their password, your system generate a random salt and store that salt along with the user record. It makes it a bit more expensive to check the password (since you need to look up the salt before you can generate the MD5 signature) but it makes it much more difficult for an attacker to pre-generate MD5's.

5
  • 3
    Salts are usually stored together with the password hash (e.g. the output of the crypt() function). And since you have to retrieve the password hash anyway, using a user specific salt will not make the procedure any more expensive. (Or did you mean generating a new random salt is expensive? I don't really think so.) Otherwise +1.
    – Inshallah
    Commented Oct 17, 2009 at 10:02
  • For purposes of security, you may want to provide access to the table only through stored procedures and prevent the hash from ever being returned. Instead, the client passes what it thinks is the hash and gets a success or failure flag. This allows the stored proc to log the attempt, create a session, etc. Commented Mar 25, 2010 at 20:09
  • @Inshallah - if all users have the same salt, then you can reuse the dictionary attack you use on user1 against user2. But if each user has a unique salt, you will need to generate a new dictionary for each user you want to attack. Commented Mar 25, 2010 at 20:27
  • @R Samuel - that's exactly why I voted your answer up, because it recommends the best-practice strategy to avoid such attacks. My comment was meant to express my perplexity about what you said regarding the additional cost of a per-user salt, which I didn't understand at all. (since "salts are usually stored together with the password hash" any additional storage and CPU requirements for a per-user salt are so microscopic, that they need not even be mentioned...)
    – Inshallah
    Commented Mar 27, 2010 at 21:55
  • @Inshallah - I was thinking about the case where you have the database checked if the hashed password is okay (then you have one db retrieval to get the salt and a second db access to check the hashed password). You are right about the case where you download the salt/hashed password in a single retrieval and then do the comparison on the client. Sorry for the confusion. Commented Mar 28, 2010 at 22:21
12

With PHP 5.5 (what I describe is available to even earlier versions, see below) around the corner I'd like to suggest to use its new, built-in solution: password_hash() and password_verify(). It provides several options in order to achieve the level of password security you need (for example by specifying a "cost" parameter through the $options array)

<?php
var_dump(password_hash("my-secret-password", PASSWORD_DEFAULT));

$options = array(
    'cost' => 7, // this is the number of rounds for bcrypt
    // 'salt' => 'TphfsM82o1uEKlfP9vf1f', // you could specify a salt but it is not recommended
);
var_dump(password_hash("my-secret-password", PASSWORD_BCRYPT, $options));
?>

will return

string(60) "$2y$10$w2LxXdIcqJpD6idFTNn.eeZbKesdu5y41ksL22iI8C4/6EweI7OK."
string(60) "$2y$07$TphfsM82o1uEKlfP9vf1fOKohBqGVXOJEmnUtQu7Y1UMft1R4D3d."

As you might see, the string contains the salt as well as the cost that was specified in the options. It also contains the algorithm used.

Therefore, when checking the password (for example when the user logs in), when using the complimentary password_verify() function it will extract the necessary crypto parameters from the password hash itself.

When not specifying a salt, the generated password hash will be different upon every call of password_hash() because the salt is generated randomly. Therefore comparing a previous hash with a newly generated one will fail, even for a correct password.

Verifying works like this:

var_dump(password_verify("my-secret-password", '$2y$10$BjHJbMCNWIJq7xiAeyFaHOGaO0jjNoE11e0YAer6Zu01OZHN/gk6K'));
var_dump(password_verify("wrong-password", '$2y$10$BjHJbMCNWIJq7xiAeyFaHOGaO0jjNoE11e0YAer6Zu01OZHN/gk6K'));

var_dump(password_verify("my-secret-password", '$2y$07$TphfsM82o1uEKlfP9vf1fOKohBqGVXOJEmnUtQu7Y1UMft1R4D3d.'));
var_dump(password_verify("wrong-password", '$2y$07$TphfsM82o1uEKlfP9vf1fOKohBqGVXOJEmnUtQu7Y1UMft1R4D3d.'));

I hope that providing these built-in functions will soon provide better password security in case of data theft, as it reduces the amount of thought the programmer has to put into a proper implementation.

There is a small library (one PHP file) that will give you PHP 5.5's password_hash in PHP 5.3.7+: https://github.com/ircmaxell/password_compat

5
  • 2
    In most cases it is better to omit the salt parameter. The function creates a salt from the random source of the operating system, there is very little chance that you can provide a better salt on your own. Commented Jun 6, 2013 at 10:54
  • 1
    That's what I wrote, didn't I? "if no salt is specified, it is randomly generated, for that reason it is preferable to not specify a salt"
    – akirk
    Commented Jun 6, 2013 at 11:09
  • Most examples show how to add both parameters, even when it is not recommended to add a salt, so i wonder why? And to be honest, i read only the comment behind the code, not on the next line. Anyway, wouldn't it be better when the example shows how to use the function best? Commented Jun 6, 2013 at 11:38
  • how should i check if the saved password and entered password are the same?i am using password_hash() and password_verify no matter what password(correct or not) i used i end up with correct password Commented Aug 25, 2015 at 11:27
  • For password_verify the first parameter is what the user entered, the second is the hash from the database. It should only return true if the password was correct. I am not sure what your problem is?
    – akirk
    Commented Aug 31, 2015 at 14:48
0

That's fine with me. Mr Atwood wrote about the strength of MD5 against rainbow tables, and basically with a long salt like that you're sitting pretty (though some random punctuation/numbers, it could improve it).

You could also look at SHA-1, which seems to be getting more popular these days.

6
  • 6
    The note at the bottom of Mr Atwood's post (in red) links off to another post from a security practicioner that states using MD5, SHA1 and other fast hashes for storing passwords is very wrong.
    – sipsorcery
    Commented Oct 17, 2009 at 7:19
  • 2
    @Matthew Scharley: I don't agree that the additional effort imposed by expensive password hashing algorithms is false security. It's to guard against brute-forcing of easily guessable passwords. If you're limiting login attempts, then you're protecting against the same thing (although a bit more effectively). But if an adversary has access to the DB stored hashes, he will be able to brute force such (easily guessable) passwords fairly quickly (depending on how easily guessable). The default for the SHA-256 crypt algorithm is 10000 round, so that would make it 10000 times more difficult.
    – Inshallah
    Commented Oct 17, 2009 at 9:48
  • 3
    The slow hashes are actually made by iterating a fast one a very large number of times, and shuffling the data around in between each iteration. The goal is to ensure that even if the bad guy gets a copy of your password hashes, he has to burn a considerable amount of CPU time to test his dictionary against your hashes.
    – caf
    Commented Oct 18, 2009 at 5:51
  • 4
    @caf: I believe the bcrypt algorithm makes use of the parameterizable expensiveness of the Eksblowfish key scheduling; not entirely sure how this works, but key scheduling is often a very expensive operation done during the init a cipher context object, before any encryption is done.
    – Inshallah
    Commented Oct 18, 2009 at 9:17
  • 3
    Inshallah: This is true - the bcrypt algorithm is a different design, where the underlying crypto primitive is a block cipher rather than a hash function. I was referring to schemes based on hash functions, like PHK's MD5 crypt().
    – caf
    Commented Oct 18, 2009 at 21:54
0

I want to add:

  • Don't limit users passwords by length

For compatibility with old systems often set a limit for the maximum length of the password. This is a bad security policy: if you set restriction, set it only for the minimum length of passwords.

  • Don't send user passwords via email

For recovering a forgotten password you should send the address by which user can change the password.

  • Update the hashes of users passwords

The password hash may be out of date (parameters of the algorithm may be updated). By using the function password_needs_rehash() you can check it out.

Not the answer you're looking for? Browse other questions tagged or ask your own question.