Secure hash and salt for PHP passwords

248,184

Solution 1

DISCLAIMER: This answer was written in 2008.

Since then, PHP has given us password_hash and password_verify and, since their introduction, they are the recommended password hashing & checking method.

The theory of the answer is still a good read though.

TL;DR

Don'ts

  • Don't limit what characters users can enter for passwords. Only idiots do this.
  • Don't limit the length of a password. If your users want a sentence with supercalifragilisticexpialidocious in it, don't prevent them from using it.
  • Don't strip or escape HTML and special characters in the password.
  • Never store your user's password in plain-text.
  • Never email a password to your user except when they have lost theirs, and you sent a temporary one.
  • Never, ever log passwords in any manner.
  • Never hash passwords with SHA1 or MD5 or even SHA256! Modern crackers can exceed 60 and 180 billion hashes/second (respectively).
  • Don't mix bcrypt and with the raw output of hash(), either use hex output or base64_encode it. (This applies to any input that may have a rogue \0 in it, which can seriously weaken security.)

Dos

  • Use scrypt when you can; bcrypt if you cannot.
  • Use PBKDF2 if you cannot use either bcrypt or scrypt, with SHA2 hashes.
  • Reset everyone's passwords when the database is compromised.
  • Implement a reasonable 8-10 character minimum length, plus require at least 1 upper case letter, 1 lower case letter, a number, and a symbol. This will improve the entropy of the password, in turn making it harder to crack. (See the "What makes a good password?" section for some debate.)

Why hash passwords anyway?

The objective behind hashing passwords is simple: preventing malicious access to user accounts by compromising the database. So the goal of password hashing is to deter a hacker or cracker by costing them too much time or money to calculate the plain-text passwords. And time/cost are the best deterrents in your arsenal.

Another reason that you want a good, robust hash on a user accounts is to give you enough time to change all the passwords in the system. If your database is compromised you will need enough time to at least lock the system down, if not change every password in the database.

Jeremiah Grossman, CTO of Whitehat Security, stated on White Hat Security blog after a recent password recovery that required brute-force breaking of his password protection:

Interestingly, in living out this nightmare, I learned A LOT I didn’t know about password cracking, storage, and complexity. I’ve come to appreciate why password storage is ever so much more important than password complexity. If you don’t know how your password is stored, then all you really can depend upon is complexity. This might be common knowledge to password and crypto pros, but for the average InfoSec or Web Security expert, I highly doubt it.

(Emphasis mine.)

What makes a good password anyway?

Entropy. (Not that I fully subscribe to Randall's viewpoint.)

In short, entropy is how much variation is within the password. When a password is only lowercase roman letters, that's only 26 characters. That isn't much variation. Alpha-numeric passwords are better, with 36 characters. But allowing upper and lower case, with symbols, is roughly 96 characters. That's a lot better than just letters. One problem is, to make our passwords memorable we insert patterns—which reduces entropy. Oops!

Password entropy is approximated easily. Using the full range of ascii characters (roughly 96 typeable characters) yields an entropy of 6.6 per character, which at 8 characters for a password is still too low (52.679 bits of entropy) for future security. But the good news is: longer passwords, and passwords with unicode characters, really increase the entropy of a password and make it harder to crack.

There's a longer discussion of password entropy on the Crypto StackExchange site. A good Google search will also turn up a lot of results.

In the comments I talked with @popnoodles, who pointed out that enforcing a password policy of X length with X many letters, numbers, symbols, etc, can actually reduce entropy by making the password scheme more predictable. I do agree. Randomess, as truly random as possible, is always the safest but least memorable solution.

So far as I've been able to tell, making the world's best password is a Catch-22. Either its not memorable, too predictable, too short, too many unicode characters (hard to type on a Windows/Mobile device), too long, etc. No password is truly good enough for our purposes, so we must protect them as though they were in Fort Knox.

Best practices

Bcrypt and scrypt are the current best practices. Scrypt will be better than bcrypt in time, but it hasn't seen adoption as a standard by Linux/Unix or by webservers, and hasn't had in-depth reviews of its algorithm posted yet. But still, the future of the algorithm does look promising. If you are working with Ruby there is an scrypt gem that will help you out, and Node.js now has its own scrypt package. You can use Scrypt in PHP either via the Scrypt extension or the Libsodium extension (both are available in PECL).

I highly suggest reading the documentation for the crypt function if you want to understand how to use bcrypt, or finding yourself a good wrapper or use something like PHPASS for a more legacy implementation. I recommend a minimum of 12 rounds of bcrypt, if not 15 to 18.

I changed my mind about using bcrypt when I learned that bcrypt only uses blowfish's key schedule, with a variable cost mechanism. The latter lets you increase the cost to brute-force a password by increasing blowfish's already expensive key schedule.

Average practices

I almost can't imagine this situation anymore. PHPASS supports PHP 3.0.18 through 5.3, so it is usable on almost every installation imaginable—and should be used if you don't know for certain that your environment supports bcrypt.

But suppose that you cannot use bcrypt or PHPASS at all. What then?

Try an implementation of PDKBF2 with the maximum number of rounds that your environment/application/user-perception can tolerate. The lowest number I'd recommend is 2500 rounds. Also, make sure to use hash_hmac() if it is available to make the operation harder to reproduce.

Future Practices

Coming in PHP 5.5 is a full password protection library that abstracts away any pains of working with bcrypt. While most of us are stuck with PHP 5.2 and 5.3 in most common environments, especially shared hosts, @ircmaxell has built a compatibility layer for the coming API that is backward compatible to PHP 5.3.7.

Cryptography Recap & Disclaimer

The computational power required to actually crack a hashed password doesn't exist. The only way for computers to "crack" a password is to recreate it and simulate the hashing algorithm used to secure it. The speed of the hash is linearly related to its ability to be brute-forced. Worse still, most hash algorithms can be easily parallelized to perform even faster. This is why costly schemes like bcrypt and scrypt are so important.

You cannot possibly foresee all threats or avenues of attack, and so you must make your best effort to protect your users up front. If you do not, then you might even miss the fact that you were attacked until it's too late... and you're liable. To avoid that situation, act paranoid to begin with. Attack your own software (internally) and attempt to steal user credentials, or modify other user's accounts or access their data. If you don't test the security of your system, then you cannot blame anyone but yourself.

Lastly: I am not a cryptographer. Whatever I've said is my opinion, but I happen to think it's based on good ol' common sense ... and lots of reading. Remember, be as paranoid as possible, make things as hard to intrude as possible, and then, if you are still worried, contact a white-hat hacker or cryptographer to see what they say about your code/system.

Solution 2

A much shorter and safer answer - don't write your own password mechanism at all, use a tried and tested mechanism.

  • PHP 5.5 or higher: password_hash() is good quality and part of PHP core.
  • PHP 4.x (obsolete): OpenWall's phpass library is much better than most custom code - used in WordPress, Drupal, etc.

Most programmers just don't have the expertise to write crypto related code safely without introducing vulnerabilities.

Quick self-test: what is password stretching and how many iterations should you use? If you don't know the answer, you should use password_hash(), as password stretching is now a critical feature of password mechanisms due to much faster CPUs and the use of GPUs and FPGAs to crack passwords at rates of billions of guesses per second (with GPUs).

As of 2012, you could crack all 8-character Windows passwords in 6 hours using 25 GPUs installed in 5 desktop PCs. This is brute-forcing i.e. enumerating and checking every 8-character Windows password, including special characters, and is not a dictionary attack. With modern GPUs, you can of course crack more passwords or use fewer GPUs - or rent the GPUs in the cloud for a few hours at reasonable cost.

There are also many rainbow table attacks on Windows passwords that run on ordinary CPUs and are very fast.

All this is because Windows still doesn't salt or stretch its passwords, even in Windows 10. This is still true in 2021. Don't make the same mistake as Microsoft did!

See also:

  • excellent answer with more about why password_hash() or phpass are the best way to go.
  • good blog article giving recommmended 'work factors' (number of iterations) for main algorithms including bcrypt, scrypt and PBKDF2.

Solution 3

I would not store the password hashed in two different ways, because then the system is at least as weak as the weakest of the hash algorithms in use.

Solution 4

As of PHP 5.5, PHP has simple, secure functions for hashing and verifying passwords, password_hash() and password_verify()

$password = 'anna';
$hash = password_hash($password, PASSWORD_DEFAULT);
$expensiveHash = password_hash($password, PASSWORD_DEFAULT, array('cost' => 20));

password_verify('anna', $hash); //Returns true
password_verify('anna', $expensiveHash); //Also returns true
password_verify('elsa', $hash); //Returns false

When password_hash() is used, it generates a random salt and includes it in the outputted hash (along with the the cost and algorithm used.) password_verify() then reads that hash and determines the salt and encryption method used, and verifies it against the provided plaintext password.

Providing the PASSWORD_DEFAULT instructs PHP to use the default hashing algorithm of the installed version of PHP. Exactly which algorithm that means is intended to change over time in future versions, so that it will always be one of the strongest available algorithms.

Increasing cost (which defaults to 10) makes the hash harder to brute-force but also means generating hashes and verifying passwords against them will be more work for your server's CPU.

Note that even though the default hashing algorithm may change, old hashes will continue to verify just fine because the algorithm used is stored in the hash and password_verify() picks up on it.

Solution 5

Though the question has been answered, I just want to reiterate that salts used for hashing should be random and not like email address as suggested in first answer.

More explanation is available at- http://www.pivotalsecurity.com/blog/password-hashing-salt-should-it-be-random/

Recently I had a discussion whether password hashes salted with random bits are more secure than the one salted with guessable or known salts. Let’s see: If the system storing password is compromised as well as the system which stores the random salt, the attacker will have access to hash as well as salt, so whether the salt is random or not, doesn’t matter. The attacker will can generate pre-computed rainbow tables to crack the hash. Here comes the interesting part- it is not so trivial to generate pre-computed tables. Let us take example of WPA security model. Your WPA password is actually never sent to Wireless Access Point. Instead, it is hashed with your SSID (the network name- like Linksys, Dlink etc). A very good explanation of how this works is here. In order to retrieve password from hash, you will need to know the password as well as salt (network name). Church of Wifi has already pre-computed hash tables which has top 1000 SSIDs and about 1 million passwords. The size is of all tables is about 40 GB. As you can read on their site, someone used 15 FGPA arrays for 3 days to generate these tables. Assuming victim is using the SSID as “a387csf3″ and password as “123456″, will it be cracked by those tables? No! .. it cannot. Even if the password is weak, the tables don’t have hashes for SSID a387csf3. This is the beauty of having random salt. It will deter crackers who thrive upon pre-computed tables. Can it stop a determined hacker? Probably not. But using random salts does provide additional layer of defense. While we are on this topic, let us discuss additional advantage of storing random salts on a separate system. Scenario #1 : Password hashes are stored on system X and salt values used for hashing are stored on system Y. These salt values are guessable or known (e.g. username) Scenario#2 : Password hashes are stored on system X and salt values used for hashing are stored on system Y. These salt values are random. In case system X has been compromised, as you can guess, there is a huge advantage of using random salt on a separate system (Scenario #2) . The attacker will need to guess addition values to be able to crack hashes. If a 32 bit salt is used, 2^32= 4,294,967,296 (about 4.2 billion) iterations will can be required for each password guessed.

Share:
248,184
luiscubal
Author by

luiscubal

Updated on July 27, 2022

Comments

  • luiscubal
    luiscubal almost 2 years

    It is currently said that MD5 is partially unsafe. Taking this into consideration, I'd like to know which mechanism to use for password protection.

    This question, Is “double hashing” a password less secure than just hashing it once? suggests that hashing multiple times may be a good idea, whereas How to implement password protection for individual files? suggests using salt.

    I'm using PHP. I want a safe and fast password encryption system. Hashing a password a million times may be safer, but also slower. How to achieve a good balance between speed and safety? Also, I'd prefer the result to have a constant number of characters.

    1. The hashing mechanism must be available in PHP
    2. It must be safe
    3. It can use salt (in this case, are all salts equally good? Is there any way to generate good salts?)

    Also, should I store two fields in the database (one using MD5 and another one using SHA, for example)? Would it make it safer or unsafer?

    In case I wasn't clear enough, I want to know which hashing function(s) to use and how to pick a good salt in order to have a safe and fast password protection mechanism.

    Related questions that don't quite cover my question:

    What's the difference between SHA and MD5 in PHP
    Simple Password Encryption
    Secure methods of storing keys, passwords for asp.net
    How would you implement salted passwords in Tomcat 5.5

  • luiscubal
    luiscubal over 15 years
    I see. But in my case, the person may have multiple emails. Should I use the ID(BIGINT primary key) instead?
  • luiscubal
    luiscubal over 15 years
    The target site shouldn't contain anything too sensitive(it's not a bank), but still I'd rather have it secured.
  • rmeador
    rmeador over 15 years
    @luiscubal: as long as the values for your salt come from a sufficiently large space, it will be a good salt. Your ID value will probably suffice, especially if the number of records is large (the number of IDs will be large).
  • Tom Haigh
    Tom Haigh over 15 years
    you could use anything that the user only has one of, but ideally something that doesn't change.
  • frankodwyer
    frankodwyer over 15 years
    multiple hashing also protects against dictionary and brute force attacks - i.e. it simply makes them take longer to compute.
  • Jason S
    Jason S over 15 years
    I'd include something secret as well. The point is, you want the hash function's input to be consistent for a correct password, but you also want it to be nonguessable so someone can't brute-force guess the password offline. (vs. having to do it through your webpage which is much slower)
  • frankodwyer
    frankodwyer over 15 years
    a secret doesn't help as your password DB is supposed to be secret anyway - if they can get hold of that DB, they can also find whatever secret you're using. it is however important that the salt is random.
  • frankodwyer
    frankodwyer over 15 years
    constant salt is not a great idea...probably not a fatal flaw but it unnecessarily weakens the scheme.
  • frankodwyer
    frankodwyer over 15 years
    double hashing does not reduce the result space. iterative hashing is a common control against dictionary and brute force attacks (it slows them down much more than it slows down your password checking).
  • frankodwyer
    frankodwyer over 15 years
    note, it's not really true that 'the computational power to decrypt' doesn't exist yet. since most passwords are dictionary words or dictionary derived, a dictionary based attack is usually very effective (hence the use of password policies and iteration counts).
  • Robert K
    Robert K over 15 years
    Frank, while what you say is true, the algorithmic cycles it takes to generate the words doesn't make it feasible. Don't forget the inclusion of the salt. Brute force will always work if they know your hash algorithm and salt, otherwise it's virtually impossible.
  • Robert K
    Robert K over 15 years
    But that doesn't make insecure passwords any safer. It just makes the database rows safer if compromised, at which point you should change your salt immediately and inform your users to change their passwords.
  • Berk D. Demir
    Berk D. Demir over 15 years
    double hashing won't give you a significant advantage but multi round hashing iterations are still a feasible defense against dictionary and bruce force attacks. Industrial strength password hashes use 1000+ rounds. PKCS#5's PBKDF1 suggests 1000 rounds minimum.
  • Robert K
    Robert K almost 15 years
    42, if I were designing a truly secure system, I'd suggest a military grade hash algorithm anyway with a ~16bit randomly generated number stored in the database. In general use, a salt with a password is better than none--unless either is compromised. I'm not claiming to be an expert, nothing is better than enforced password rotation plus a military-grade algorithm, but for basic non-critical software this is enough.
  • OldBuildingAndLoan
    OldBuildingAndLoan almost 15 years
    @wicked flea, I'm not arguing with you. Just pointing out how convoluted and complex this area of our work is. I keep hoping to get schooled by the be-all, end-all smartest, best practice for setting up a small web site's content management system. I'm still learning here. ...every time I read something that makes sense, I soon notice 5 other posts that contradict it. that round-and-round gets dizzying quickly :)
  • luiscubal
    luiscubal about 14 years
    Even if the attacker gets the salt, a "sitesalt:usersalt:password" string is still resistant to precomputed tables, since the attacker needs to generate the tables for every user(so the attack becomes far slower), unless of course a specific user is being targeted...
  • Gaurav Kumar
    Gaurav Kumar about 14 years
    Regarding "Even if the attacker gets the salt, a "sitesalt:usersalt:password" string is still resistant to precomputed tables" , Totally agree. My point is that sitesalt if made random and long, will make system more secure than it (sitesalt) being predictable. I've seen some people recommending use of email id etc as salt, and I discourage that.
  • o0'.
    o0'. almost 14 years
    "Even MD5 is still safe, as aside from a brute-force attack the computational power needed to decrypt doesn't exist yet." OMG, I don't believe it. MD5 can't be "decrypted", period. But it is definitly not safe, as it is. Ever heard of rainbow tables?
  • Robert K
    Robert K almost 14 years
    Look, if you're using MD5 on software that requires high security (like a store) then YOU'RE the fool, not me. I know that MD5 is extremely fast, but if you're designing forum software with good practices it's still generally secure.
  • luiscubal
    luiscubal almost 14 years
    Interesting revision. Is the user ID(say, an auto increment BIGINT) a good nonce? Or since it's not random it isn't good? Also, I'll have to store the nonce for each user in the database... Does the site key + nonce + HMAC provide significant improved security over a salted(with user ID) hash iterated multiple times? Similarly, is iterating HMAC multiple times good for security?
  • Francisc
    Francisc about 13 years
    Excellent post. Answered many of my own questions. However, I am uncertain of what it means to save the site_key in the file system. Could you please explain? For me, even a .php file in a folder on the server is the file system.
  • Drew Stephens
    Drew Stephens almost 13 years
    The article that 42 linked 404s—here's a copy chargen.matasano.com/chargen/2007/9/7/…
  • Konerak
    Konerak almost 13 years
    64 bits ought to be enough for anyone?
  • Robert K
    Robert K over 12 years
    I'll update it about bcrypt sometime. I've been busy and the scheme I suggested is at least moderately effective. Better that than someone just throwing a plain md5/sha1 hashed password in their DB.
  • zac1987
    zac1987 over 12 years
    no other way to save random number of $nonce except save it to db? If the hacker can get hashed_password from db, sure he able to get nonce from db too
  • JqueryToAddNumbers
    JqueryToAddNumbers about 12 years
    but these systems are better known and maybe already compromised. but it beats making your own when you don't know what your doing.
  • RichVel
    RichVel about 12 years
    Re "these systems are better known and maybe already compromised" - there is no reason why a well designed system for authentication should become "already compromised" just because it is better known. Libraries such as phpass are written by experts and reviewed by many people in detail - the fact they are well known goes along with detailed review by different people and is more likely to mean they are secure.
  • Robert K
    Robert K about 12 years
    You missed what I originally wrote. I said to use a random nonce, stored with the record, PLUS the email address. The addition of the email address makes for extra entropy for the hacker to work on. I've since rewritten my answer in favor of bcrypt.
  • ThiefMaster
    ThiefMaster almost 12 years
    I think even emailing a new password in case of a lost one is a bad idea. Why not email a link to a secure site that allows the user to change his password? That's much more comfortable (no need to change the password after logging in with the random one) and more secure since no password went over the wire unencrypted - remember, users are lazy and chances are good that they do not change the random password.
  • RichVel
    RichVel almost 12 years
    Given the recent password hash dumps from LinkedIn, Last.fm and others, this is quite topical. You are in good company in not knowing how to write your own password mechanism!
  • Tim Gautier
    Tim Gautier over 11 years
    Sending a temporary password through email that requires the user to change it the first time they use it and sending a "secure" link over email that allows them to set their password are equally risky. In either case anyone who intercepts the email can access the account as long as they use the link or password before the intended recipient does.
  • ircmaxell
    ircmaxell over 11 years
    @frankodwyer: yes, it is bad. sha1(sha1($foo)) effectively reduces the output space, because any collision of the inner function will automatically become a collision of the outer one. The degradation is linear, but it's still a concern. The iterative hashing methods feed data back in on each round, such as $hash = sha1(sha1($salt . $password) . $salt). But that's still not good... Stick with PBKDF2 or Bcrypt...
  • luiscubal
    luiscubal over 11 years
    Regarding your most recent edit: "require at least 1 upper case letter, 1 lower case letter, a number, and a symbol" is in direct contradiction with the xkcd comic in the link. It shows an example of a password with no symbols, but high entropy.
  • Robert K
    Robert K over 11 years
    @luiscubal I'm not sure Randall is right, so I don't 100% endorse his suggestion though I've tried it. With lowercase/spaces your entropy is ~4.75/character, which for 28 characters is about 131-133 bits of entropy. But there's only four words there, with ~1 million words in the English language that's 1e+24 combinations versus upper/lower/symbols at 28 characters is 3.18855e+55 or so. Anyway, I'm not 100% convinced.
  • luiscubal
    luiscubal over 11 years
    @RobertK Humans are imperfect random number generators, which greatly lowers the entropy in both cases. They won't pick a perfectly random [a-zA-Z0-9_$%#]{28} sequence - they are more likely to just pick something like $justinBieber28.
  • Robert K
    Robert K over 11 years
    @luiscubal You are correct. However a password manager that can do just that is invaluable. Which is the other problem with Randall's suggestion: his method produces pseudorandom combinations less random than our pseudorandom gibberish passwords. That's why it was only a suggestion of something to do. One's probably as secure as the other (for now).
  • luiscubal
    luiscubal over 11 years
    @RobertK Note that he never truly checks the entropy of "complete gibberish", because people tend not to use complete gibberish for passwords. Computer-generated passwords can be much better than human-generated passwords, but how many people would just hit the "regenerate" button until they got something easy to remember? Or even tweak the result to be simpler? All that lowers entropy.
  • Robert K
    Robert K over 11 years
    @luiscubal I said a password manager not just a generator. I personally use LastPass to generate/remember passwords, and just make the best password I can to lock that service down. That keeps entropy high for other sites. As a user it's the best solution I've come across so far.
  • ircmaxell
    ircmaxell over 11 years
    Just read the update, and it looks much better. Removing my -1. Perhaps it would be worth mentioning the new 5.5 APIs: php.net/manual/en/ref.password.php and the compatibility project: github.com/ircmaxell/password_compat And thanks for updating the answer!!!
  • Popnoodles
    Popnoodles over 11 years
    requiring at least 1 upper case letter, 1 lower case letter, a number, and a symbol will not improve the entropy of the password, it will just make it harder for people to remember.
  • Robert K
    Robert K over 11 years
    @popnoodles By expanding the character set and the number of used characters it expands the bits of entropy per character, it does NOT safeguard against non-random passwords by users.
  • Popnoodles
    Popnoodles over 11 years
    @RobertK By expanding the character set yes it increases, BUT by forcing all passwords to to follow rules decreases the amount of possible options. Let's say someone was to get a password by brute force. By telling them the user's password has 1 upper case letter, 1 lower case letter, a number, and a symbol, it means the number of tries they need is significantly less. By allowing the user to decide what they want, the hacker has to try harder.
  • PP.
    PP. over 10 years
    "This will improve the entropy of the password" - if you force somebody to use at least one number then you've reduced the entropy of the password as there are only 10 digits to choose from
  • PP.
    PP. over 10 years
    "don't write your own password mechanism at all" - but the truly paranoid will want to write their own to minimise probability the NSA have a backdoor.
  • RichVel
    RichVel over 10 years
    @PP - the chances of a peer-reviewed password hashing algorithm having an NSA backdoor are very low, in my view. The chances of someone who is not a real crypto expert writing a new password hashing mechanism without other vulnerabilities is much lower. And the typical webapp uses just MD5 or SHA-1 hashing, which is terrible - even Chris Shiflett's otherwise great Essential PHP Security book recommends MD5 ...
  • Admin
    Admin over 10 years
    Also consider hashing it on client side, this way even if the server got corrupted in any way, the original passwords cannot be retrieved!
  • Robert K
    Robert K over 10 years
    @derylius Unless your log in code is delivered in a plugin, you cannot verify that the javascript code is your original code with no compromises. Also, sending a hash to be compared against a hash in the DB is just as dangerous (it takes the place of the password). This isn't a very good, or safe, idea. It's better to rely upon connection security than it is javascript security.
  • Admin
    Admin over 10 years
    @RobertK I guess you misunderstood me. I didn't say do this instead of setting up a secure connection, what I suggested is to do this in addition, cause even if the connection is secure, if the server get compromised, then every single request sent to that server potentially shows plain passwords to the attackers. So my point is, that as a user I don't want to trust any server, but that doesn't mean I want to remember a 64 character long hash string instead of the color of my favorite fruit. (Further explanation here: xkcd.com/936)
  • Robert K
    Robert K over 10 years
    @derylius Yeah, I probably misunderstood. However, sending the hash to the server is just as bad. Though I think SQRL by Steve Gibson shows really good promise.
  • Admin
    Admin over 10 years
    @RobertK its really just a small addition that protects the password itself, not the environment. But since the passwords must be hashed anyway to store it, hashing it on client side instead of server side is not so much extra code adding some to the security without taking out any of it.
  • CodesInChaos
    CodesInChaos about 10 years
    MD5 and SHA1 are fast, so this is a bad diea.
  • martinstoeckli
    martinstoeckli about 10 years
    You should strike SHA512 from your list of decent hash algorithms, because it is too fast. Use it only in combination with PBKDF2. While BCrypt is based on blowfish, blowfish itself is an algorithm for encryption, not for hashing.
  • Iazel
    Iazel almost 10 years
    How do you store the random salt in the DB? I think you don't hash it (cannot be used for verification) nor store in clear (no real benefits if the attacker can read the DB). So, how you do it?
  • MrYellow
    MrYellow over 9 years
    I'm also of the opinion that passwords should not expire. Forcing users to create new passwords and disallowing them from using previously used passwords results in users choosing worse and worse combinations as they can never remember them. Sure they shouldn't be remembering anyway, but I'm talking reality not ideal world.
  • Robert K
    Robert K over 9 years
    @MrYellow In general I dislike password expiry too. But preventing the use of previous passwords is a good idea for high security applications. After all, you wouldn't want somebody alternating passwords on something highly sensitive. But I left those out because they felt like subjective conclusions. Those are harder to prove than "X algorithm can be calculated in Y M-hashes/sec".
  • MrYellow
    MrYellow over 9 years
    @RobertK I've heard strategies from people who will just reset their password 15 times to expire the "previously used" list and get back to a password they can remember... yeah agree the numbers aren't cut and dry on this part of the question. It's debatable and the correct choice is different depending on systems purpose.
  • Robert K
    Robert K over 9 years
    @MrYellow Yeah, I'm not surprised. About the only way the password expiry scheme would work is if past passwords were stored, then levenshtein distance was used to validate a new password. It's tyrannical, but it's about the only way to ensure users don't pick "password" then "password1", then "password2", etc. (Not that I advise doing this...)
  • CubicleSoft
    CubicleSoft about 9 years
    phpass is NOT the best way to go. Never has been and likely never will be. I reviewed the code several years ago and it is NOT secure on Windows or any platform where /dev/urandom is not available. It does NOT follow best-practices when it comes to security, using a combination of md5() and microtime() when it should be terminating the application instead of making false claims about security. It hasn't seen any updates since I reviewed the code despite PHP itself moving ahead in the security space with bcrypt in core. Stay FAR away from phpass.
  • RichVel
    RichVel about 9 years
    @CubicleSoft - can you recommend another PHP library for password hashing? Unless there's a better library, phpass will still be better than the vast majority of custom code that uses unsalted and unstretched MD5.
  • H2ONaCl
    H2ONaCl about 9 years
    wmfrancia wrote: "Salting adds a random string to the password so similar passwords don't appear the same in the DB". This does not make sense to me. Hashes in the DB will already appear dissimilar because that is a property of hash functions.
  • H2ONaCl
    H2ONaCl about 9 years
    wmfancia wrote in regard to a constant salt: "once an attacker figures out one password salt he has the salt for all of them". The same can be said that if the hacker figures out which DB field is the salt, he has the salts for all of them. Since a constant salt would probably not be in the DB, that is a good thing about a constant salt.
  • H2ONaCl
    H2ONaCl about 9 years
    Of course, these comments are not to suggest a random salt per user is not better than one salt per application. It is better.
  • CubicleSoft
    CubicleSoft about 9 years
    @RichVel - The password_hash() function. As mentioned earlier, it's built into PHP core (aka /ext/standard).
  • RichVel
    RichVel about 9 years
    @CubicleSoft - password_hash() defaults to bcrypt and has a cost function for stretching, so it seems good for people on PHP 5.5 or higher - php.net/manual/en/function.password-hash.php. phpass supports earlier PHP versions where it is certainly better than most people's custom code built on MD5 etc.
  • luiscubal
    luiscubal over 8 years
    This question was about hashes for passwords. 1 execution of sha512 (even if salted) is widely considered to not be good enough for password protection. (also that RNG is not cryptographically secure, so using it for password generation is risky).
  • cryptic ツ
    cryptic ツ over 8 years
    You have no idea what you're doing. Read the top answers in this post and you can see why your code is not just insecure, but makes no sense.
  • shalvasoft
    shalvasoft over 8 years
    ok. my code is not secure. so let me know why are you using in your algorithms ony sha256??? I know that sha512 is the best why not use it???
  • luiscubal
    luiscubal over 8 years
    @shalvasoft sha512 is pretty good for general purpose hashing, but password protection requires hashes with very specific properties ("being slow" is strangely a good thing, for instance, and sha512 is pretty fast). Some people have used sha512 as a building block to create password hashing functions, but nowadays the recommended approach is "use bcrypt and keep an eye on scrypt".
  • Andrew
    Andrew over 8 years
    Regarding forcing users to implement a password with every type of character: first it will piss them off and make them go away, two, it is not even necessary/useful. Instead just start locking out the account after too many attempts/too quick of attempts Even if you just restrict it to 1 password attempt per second, you've crippled a brute force cracker's options, no?
  • Iman Marashi
    Iman Marashi over 8 years
    How to recover password when users forgot it?
  • Vincent Edward Gedaria Binua
    Vincent Edward Gedaria Binua over 8 years
    @Konerak, I'd get back to this after 20 years. :) But yep SHA256 is indeed available. If you want to know how secure SHA256 is, you might want to check this out: security.stackexchange.com/questions/90064/…
  • BRoebie
    BRoebie over 8 years
    @ImanMarashi the way I would do it is(and please do correct me if I am a dumbass:P): make a forgot password page and let him fill in a field with his email address. When the user clicks on send you generate a random password maybe this will help (which ofcourse should be hashed again) and send an email to him with the random password inside and a link the page of his account and tell him to change his password. That's how I would do it maybe I am totally wrong but then I'm interested to see how it should be done
  • Robert K
    Robert K over 8 years
    @BRoebie I don't advise changing the user's password, because someone fishing for users/emails could then lock users out. Instead, generate a token with a short expiry time (like < 15 minutes) and use that token in the email's link to a reset page. That's more secure. But reseting passwords via email is never particularly secure (IMO).
  • BRoebie
    BRoebie over 8 years
    Thank you for your reply. I will definitely use that method. I will look around the internet for some examples. Can you give me a timestamp I should use before it expires. For example would an hour be acceptable too? I know that it would be less secure but some mail services are quite slow
  • Hugo Zink
    Hugo Zink over 8 years
    I have to disagree with requiring an uppercase letter, lowercase letter, a number, and a symbol all at once. All that's going to do, is make people enter "Password1!" instead of "password". Or worse, they'd write it down on post-its. Such restrictions are irrelevant for password manager users, but even then, don't implement such harsh restrictions unless you're a bank or payment service.
  • Thom Wiggers
    Thom Wiggers about 8 years
    In place of scrypt and bcrypt you should nowadays probably be looking at argon2, which won the password hashing competition.
  • Michael
    Michael almost 8 years
    You give us solution without no usage no usage
  • Nick T
    Nick T over 5 years
    Limiting a password to <200 characters is fine IMHO; if the user only entered 0s and 1s they'd still have basically unbreakable entropy, or for the sake of argument, 1000 chars. There's no point to going way, way over 256 bits of entropy just to say there's "no limit". Are you happy to hash a multi-GB password I give you? An alternative workaround: make the user hash their 50 GB password with SHA-2 or whatever and pretend that's the password. Bam, all 'passwords' you receive are 32 bytes long (still need to use a password hash to actually store it though).
  • Robert K
    Robert K over 5 years
    @NickT Most web servers would reject a 50GB password due to exceeding upload limits and timeout on input, so I feel that that point is moot. So long as your limit is 64+, it'd be find in my opinion. (You might want to check the age of this answer, though.) 😉