4

Which are the most secure password hash algorithm(s) in PHP?

Speed is irrelevant because I'm iterating the hash over a fixed time (rather than a fixed number of iterations). What I'm interested in is the mathematical strength.

My intuition tells me it's whirlpool, being the largest and slowest of the bunch. That or SHA-512. Which is recommended by experts?

Are there any other algorithms which provide more than 512 bit hashes?

Inderpartap Cheema
  • 463
  • 1
  • 7
  • 17
  • 4
    Use [`password_hash()`](http://php.net/manual/en/function.password-hash.php). That's all you need to know. Do *not* reinvent the wheel. – John Conde Jun 23 '15 at 17:55

2 Answers2

8

Use the function password_hash(). If you let it (by specifying PASSWORD_DEFAULT), it will choose the recommended algorithm, which currently is BCrypt. If the algorithm changes, you don't have to change the code. If you like, you can also explicitly choose this algorithm using the constant PASSWORD_BCRYPT, but that opposes the intention of automatically updating to better algorithms when they become available in future versions.

You can use password_verify() to verify the password.

PHP will add the used algorithm to the hash, as well as a salt, so it will know everything it needs to know for the verification. That way, when new algorithms become available in newer versions of PHP, they will be used automatically, and those passwords will have a stronger hash.

You can use password_needs_rehash() to check if a password needs to be rehashed, should the default ever change.

If a password validates, you can rehash it and store it. That way you will update old passwords with weaker hashes automatically when a user logs in.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • 2
    To follow up with this, the reason you use an algorithm such as BCrypt is that it's designed for password protection, unlike the SHA algorithms. It's specifically designed to be slow to calculate. It's not an issue for user logins, but it's significantly slower than brute-forcing SHA's. – haxim Jun 24 '15 at 03:16
4

scrypt is debateably the most secure hashing algorithm because it is RAM-limited and therefore difficult to parallelize. However, it is not natively supported by many, if any, current systems.

bcrypt is next. It has no current known cryptographic weaknesses, is widely supported, and has a broadly adjustable work factor. It is also the current default algorithm for password_hash().

Everything else is sub-par.

Unless you have a degree in cryptography do not roll your own hashing or cryptography scheme.


2023 Update

Worth noting that since PHP7.2 [Released Nov 2017] Argon2 hashing has been available to password_hash(), provided PHP was built with the relevant options. Specifically Argon2id allows the specification of both time and memory cost parameters, making potentially better than both bcrypt and scrypt.

Sammitch
  • 30,782
  • 7
  • 50
  • 77