jueves, 15 de agosto de 2013

Modern password hashing in PHP

Historically, password security in PHP has been a bit slippery, requiring a measure of knowledge and care. Aiming to change that, PHP 5.5 introduces a special password_hash() function which makes password security much easier, and with features such as automatic algorithm upgrading, even more robust. There's also a compatibility library for PHP >= 5.3.7.
If you've ever looked at login code, the chances are you've seen developers using hash('sha256', $password), or even md5($password) to "secure" user passwords. Password hashes generated this way are laughably easy to crack; with weak algorithms and no salting or stretching in place you're almost giving your passwords to an attacker who gains access.

Salting? Stretching?

To salt a password you add a few random characters to it before hashing so that the same password will result in a unique string each time it is hashed, negating rainbow table attacks and making it necessary to crack each password individually. Salts are usually stored alongside the hash and must be used when checking passwords against the hash.
Stretching a password just involves hashing the resulting hash multiple times. This means that in order to check a password against a stolen hash, an attacker has to hash each guess multiple times, lengthening the time it takes to check each password hash. The effect is negligible for a single password check, but over thousands of iterations it soon adds up.


Enter password_hash()

The password_hash() function salts, stretches, and by default chooses the best hashing algorithm to use at the time of execution, meaning that you never have to worry about choosing an algorithm, or even updating your code to use to stronger algorithms as time moves on - if a better algorithm becomes available, the function will start using it for new hashes.
This last point is something I think will really help boost the security of PHP applications. It is made possible by a companion function, password_verify(), which is able to auto-detect the algorithm used when the password was hashed. Using this family of functions, it's trivial to run several different algorithms and password strength schemes in one place.
Here's an example of how to use the new fuction:
php
$hash = password_hash('ub3rs3cur3', PASSWORD_DEFAULT);
echo password_verify('ub3rs3cur3', $hash) ? 'Correct password!' : 'Incorrect password!';
?>
 
 
Más...
 
 
Fuente:  bitquark.co.uk