best algorithm to store passwords in 2016 - php

Actually I read many post related to the algorithm for use like md5, sha1 and so on. But I am still not sure which one is the secure and the best one to use nowadays. I am beginner with web development and I am asking all of the best programmers around the world to teach and show me. I hope you guys can give me the choice and example for using it. Thank You

Incidentally: How to safely store your users' passwords in 2016.
Your choices are:
Argon2 (requires PHP 7.2 or a PHP extension)
Scrypt (requires PHP extension)
Bcrypt
If you really need to, also feel free to consider PBKDF2.
The old standby: Bcrypt
Given that you're a beginner, you should be writing your password validation like this:
// Creating your hashed password:
$hash = password_hash($userPassword, PASSWORD_DEFAULT);
// Checking a user-supplied password against a stored hash:
if (password_verify($userPassword, $hash)) {
// Login successful.
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
// Recalculate a new password_hash() and overwrite the one we stored previously
}
}
Downside to bcrypt:
Passwords over 72 characters are truncated.
Passwords with a NUL byte will truncate.
A stop-gap that works around these limitations is built into Password Lock: It pre-hashes passwords with SHA384 then base64-encodes the raw hash before passing to PHP's password API.
First, create an encryption key and store it outside your document root. (Otherwise, a hacker can just steal the key.)
$newKey = \Defuse\Crypto\Key::createNewRandomKey();
file_put_contents(
'/outside/document/root/enckey.txt',
$newKey->saveToAsciiSafeString()
);
Now, you can use this key in conjunction with your passwords:
$key = Key::loadFromAsciiSafeString(
file_get_contents('/outside/document/root/enckey.txt')
);
// Hashing a password with PasswordLock:
$storeMe = PasswordLock::hashAndEncrypt($_POST['password'], $key);
// Verifying a password with PasswordLock:
if (PasswordLock::decryptAndVerify($_POST['password'], $storeMe, $key)) {
// Success!
}
You can now use Argon2 with password_hash() in PHP 7.2
The new standard: Argon2 (via Libsodium)
Unless you're on PHP 7.2 or higher, you'll need to install libsodium and the PHP extension to use Argon2. Password hashing is one of the features that is not provided by sodium_compat.
// Password hashing:
$hash_str = sodium_crypto_pwhash_str(
$password,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);
// Password verification:
if (sodium_crypto_pwhash_str_verify($hash_str, $password)) {
// recommended: wipe the plaintext password from memory
sodium_memzero($password);
// Password was valid.
} else {
// recommended: wipe the plaintext password from memory
sodium_memzero($password);
// Password was invalid.
}
Intermediate: Scrypt
You'll need the scrypt extension which is available through PECL:
pecl install scrypt
echo "extension=scrypt.so" > /etc/php5/mods-available/scrypt.ini
php5enmod scrypt
Once that's installed, using it is fairly straightforward:
// Hashing:
$hash = \Password::hash($userProvidedPassword);
// Validation:
if (\Password::check($userProvidedPassword, $hash)) {
// Logged in successfully.
}
The only reason to really use scrypt is compatibility; at this point, go with either Argon2 or bcrypt.
Acceptable but not Great: PBKDF2
I highly recommend going with Defuse Security's cross-platform Password Hashing library if you need PBKDF2. (You should consider just using password_*, however!)
$hash = PasswordStorage::create_hash($password);
if (PasswordStorage::verify_password($password, $hash)) {
// Success
}
Any of the above choices are acceptable. Argon2 is probably the most secure, but it's not widely available in PHP yet. Anything absent from this list should be regarded with a healthy dose of skepticism.

Important is, that the algorithm offers a cost factor, which controls the necessary time to calculate a hash. The more time you can invest in calculating a single hash, the more expensive brute-forcing will become (e.g. 100 Giga MD5 per second vs 10 BCrypt per second).
Today recommended algorithms are BCrypt, PBKDF2 and SCrypt. The algorithm BCrypt is supported by PHP, a wrapper function takes care of the generation of a salt and is future proof.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

Related

After bcrypt the password in laravel i am not able to log in [duplicate]

This question already has answers here:
How to use PHP's password_hash to hash and verify passwords
(5 answers)
Closed 9 months ago.
Every now and then I hear the advice "Use bcrypt for storing passwords in PHP, bcrypt rules".
But what is bcrypt? PHP doesn't offer any such functions, Wikipedia babbles about a file-encryption utility and Web searches just reveal a few implementations of Blowfish in different languages. Now Blowfish is also available in PHP via mcrypt, but how does that help with storing passwords? Blowfish is a general purpose cipher, it works two ways. If it could be encrypted, it can be decrypted. Passwords need a one-way hashing function.
What is the explanation?
bcrypt is a hashing algorithm which is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensures that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password salts (bcrypt REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.
bcrypt uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. Because of this key difference, bcrypt is a one-way hashing algorithm. You cannot retrieve the plain text password without already knowing the salt, rounds and key (password). [Source]
How to use bcrypt:
Using PHP >= 5.5-DEV
Password hashing functions have now been built directly into PHP >= 5.5. You may now use password_hash() to create a bcrypt hash of any password:
<?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
// Usage 2:
$options = [
'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C
To verify a user provided password against an existing hash, you may use the password_verify() as such:
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
Using PHP >= 5.3.7, < 5.5-DEV (also RedHat PHP >= 5.3.3)
There is a compatibility library on GitHub created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).
Using PHP < 5.3.7 (DEPRECATED)
You can use crypt() function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library. This alternative is provided only for historical purposes.
class Bcrypt{
private $rounds;
public function __construct($rounds = 12) {
if (CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
$this->rounds = $rounds;
}
public function hash($input){
$hash = crypt($input, $this->getSalt());
if (strlen($hash) > 13)
return $hash;
return false;
}
public function verify($input, $existingHash){
$hash = crypt($input, $existingHash);
return $hash === $existingHash;
}
private function getSalt(){
$salt = sprintf('$2a$%02d$', $this->rounds);
$bytes = $this->getRandomBytes(16);
$salt .= $this->encodeBytes($bytes);
return $salt;
}
private $randomState;
private function getRandomBytes($count){
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
$bytes = openssl_random_pseudo_bytes($count);
}
if ($bytes === '' && is_readable('/dev/urandom') &&
($hRand = #fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if (strlen($bytes) < $count) {
$bytes = '';
if ($this->randomState === null) {
$this->randomState = microtime();
if (function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for ($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
private function encodeBytes($input){
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (true);
return $output;
}
}
You can use this code like this:
$bcrypt = new Bcrypt(15);
$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
Alternatively, you may also use the Portable PHP Hashing Framework.
So, you want to use bcrypt? Awesome! However, like other areas of cryptography, you shouldn't be doing it yourself. If you need to worry about anything like managing keys, or storing salts or generating random numbers, you're doing it wrong.
The reason is simple: it's so trivially easy to screw up bcrypt. In fact, if you look at almost every piece of code on this page, you'll notice that it's violating at least one of these common problems.
Face It, Cryptography is hard.
Leave it for the experts. Leave it for people whose job it is to maintain these libraries. If you need to make a decision, you're doing it wrong.
Instead, just use a library. Several exist depending on your requirements.
Libraries
Here is a breakdown of some of the more common APIs.
PHP 5.5 API - (Available for 5.3.7+)
Starting in PHP 5.5, a new API for hashing passwords is being introduced. There is also a shim compatibility library maintained (by me) for 5.3.7+. This has the benefit of being a peer-reviewed and simple to use implementation.
function register($username, $password) {
$hash = password_hash($password, PASSWORD_BCRYPT);
save($username, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
if (password_verify($password, $hash)) {
//login
} else {
// failure
}
}
Really, it's aimed to be extremely simple.
Resources:
Documentation: on PHP.net
Compatibility Library: on GitHub
PHP's RFC: on wiki.php.net
Zend\Crypt\Password\Bcrypt (5.3.2+)
This is another API that's similar to the PHP 5.5 one, and does a similar purpose.
function register($username, $password) {
$bcrypt = new Zend\Crypt\Password\Bcrypt();
$hash = $bcrypt->create($password);
save($user, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
$bcrypt = new Zend\Crypt\Password\Bcrypt();
if ($bcrypt->verify($password, $hash)) {
//login
} else {
// failure
}
}
Resources:
Documentation: on Zend
Blog Post: Password Hashing With Zend Crypt
PasswordLib
This is a slightly different approach to password hashing. Rather than simply supporting bcrypt, PasswordLib supports a large number of hashing algorithms. It's mainly useful in contexts where you need to support compatibility with legacy and disparate systems that may be outside of your control. It supports a large number of hashing algorithms. And is supported 5.3.2+
function register($username, $password) {
$lib = new PasswordLib\PasswordLib();
$hash = $lib->createPasswordHash($password, '$2y$', array('cost' => 12));
save($user, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
$lib = new PasswordLib\PasswordLib();
if ($lib->verifyPasswordHash($password, $hash)) {
//login
} else {
// failure
}
}
References:
Source Code / Documentation: GitHub
PHPASS
This is a layer that does support bcrypt, but also supports a fairly strong algorithm that's useful if you do not have access to PHP >= 5.3.2... It actually supports PHP 3.0+ (although not with bcrypt).
function register($username, $password) {
$phpass = new PasswordHash(12, false);
$hash = $phpass->HashPassword($password);
save($user, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
$phpass = new PasswordHash(12, false);
if ($phpass->CheckPassword($password, $hash)) {
//login
} else {
// failure
}
}
Resources
Code: cvsweb
Project Site: on OpenWall
A review of the < 5.3.0 algorithm: on StackOverflow
Note: Don't use the PHPASS alternatives that are not hosted on openwall, they are different projects!!!
About BCrypt
If you notice, every one of these libraries returns a single string. That's because of how BCrypt works internally. And there are a TON of answers about that. Here are a selection that I've written, that I won't copy/paste here, but link to:
Fundamental Difference Between Hashing And Encryption Algorithms - Explaining the terminology and some basic information about them.
About reversing hashes without rainbow tables - Basically why we should use bcrypt in the first place...
Storing bcrypt Hashes - basically why is the salt and algorithm included in the hash result.
How to update the cost of bcrypt hashes - basically how to choose and then maintain the cost of the bcrypt hash.
How to hash long passwords with bcrypt - explaining the 72 character password limit of bcrypt.
How bcrypt uses salts
Best practices of salting and peppering passwords - Basically, don't use a "pepper"
Migrating old md5 passwords to bcrypt
Wrap Up
There are many different choices. Which you choose is up to you. However, I would HIGHLY recommend that you use one of the above libraries for handling this for you.
Again, if you're using crypt() directly, you're probably doing something wrong. If your code is using hash() (or md5() or sha1()) directly, you're almost definitely doing something wrong.
Just use a library...
You'll get a lot of information in Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes or Portable PHP password hashing framework.
The goal is to hash the password with something slow, so someone getting your password database will die trying to brute force it (a 10 ms delay to check a password is nothing for you, a lot for someone trying to brute force it). Bcrypt is slow and can be used with a parameter to choose how slow it is.
You can create a one-way hash with bcrypt using PHP's crypt() function and passing in an appropriate Blowfish salt. The most important of the whole equation is that A) the algorithm hasn't been compromised and B) you properly salt each password. Don't use an application-wide salt; that opens up your entire application to attack from a single set of Rainbow tables.
PHP - Crypt Function
Edit: 2013.01.15 - If your server will support it, use martinstoeckli's solution instead.
Everyone wants to make this more complicated than it is. The crypt() function does most of the work.
function blowfishCrypt($password,$cost)
{
$chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$salt=sprintf('$2y$%02d$',$cost);
//For PHP < PHP 5.3.7 use this instead
// $salt=sprintf('$2a$%02d$',$cost);
//Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
mt_srand();
for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
return crypt($password,$salt);
}
Example:
$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password
I know it should be obvious, but please don't use 'password' as your password.
Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash() and password_verify(). Actually these are just wrappers around the function crypt(), and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.
The easiest way to use this functions will be:
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This code will hash the password with BCrypt (algorithm 2y), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.
Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
In contrast to the "cost" parameter, it is best to omit the "salt" parameter, because the function already does its best to create a cryptographically safe salt.
For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash() function. For PHP versions before 5.3.7 there is no support for crypt() with 2y, the unicode safe BCrypt algorithm. One could replace it instead with 2a, which is the best alternative for earlier PHP versions.
Current thinking: hashes should be the slowest available, not the fastest possible. This suppresses rainbow table attacks.
Also related, but precautionary: An attacker should never have unlimited access to your login screen. To prevent that: Set up an IP address tracking table that records every hit along with the URI. If more than 5 attempts to login come from the same IP address in any five minute period, block with explanation. A secondary approach is to have a two-tiered password scheme, like banks do. Putting a lock-out for failures on the second pass boosts security.
Summary: slow down the attacker by using time-consuming hash functions. Also, block on too many accesses to your login, and add a second password tier.
Here's an updated answer to this old question!
The right way to hash passwords in PHP since 5.5 is with password_hash(), and the right way to verify them is with password_verify(), and this is still true in PHP 8.0. These functions use bcrypt hashes by default, but other stronger algorithms have been added. You can alter the work factor (effectively how "strong" the encryption is) via the password_hash parameters.
However, while it's still plenty strong enough, bcrypt is no longer considered state-of-the-art; a better set of password hash algorithms has arrived called Argon2, with Argon2i, Argon2d, and Argon2id variants. The difference between them (as described here):
Argon2 has one primary variant: Argon2id, and two supplementary variants: Argon2d and Argon2i. Argon2d uses data-depending memory access, which makes it suitable for cryptocurrencies and proof-of-work applications with no threats from side-channel timing attacks. Argon2i uses data-independent memory access, which is preferred for password hashing and password-based key derivation. Argon2id works as Argon2i for the first half of the first iteration over the memory, and as Argon2d for the rest, thus providing both side-channel attack protection and brute-force cost savings due to time-memory tradeoffs.
Argon2i support was added in PHP 7.2, and you request it like this:
$hash = password_hash('mypassword', PASSWORD_ARGON2I);
and Argon2id support was added in PHP 7.3:
$hash = password_hash('mypassword', PASSWORD_ARGON2ID);
No changes are required for verifying passwords since the resulting hash string contains information about what algorithm, salt, and work factors were used when it was created.
Quite separately (and somewhat redundantly), libsodium (added in PHP 7.2) also provides Argon2 hashing via the sodium_crypto_pwhash_str () and sodium_crypto_pwhash_str_verify() functions, which work much the same way as the PHP built-ins. One possible reason for using these is that PHP may sometimes be compiled without libargon2, which makes the Argon2 algorithms unavailable to the password_hash function; PHP 7.2 and higher should always have libsodium enabled, but it may not - but at least there are two ways you can get at that algorithm. Here's how you can create an Argon2id hash with libsodium (even in PHP 7.2, which otherwise lacks Argon2id support)):
$hash = sodium_crypto_pwhash_str(
'mypassword',
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);
Note that it doesn't allow you to specify a salt manually; this is part of libsodium's ethos – don't allow users to set params to values that might compromise security – for example there is nothing preventing you from passing an empty salt string to PHP's password_hash function; libsodium doesn't let you do anything so silly!
For OAuth 2 passwords:
$bcrypt = new \Zend\Crypt\Password\Bcrypt;
$bcrypt->create("youpasswordhere", 10)
As we all know storing password in clear text in database is not secure.
the bcrypt is a hashing password technique.It is used to built password security. One of the amazing function of bcrypt is it save us from hackers it is used to protect the password from hacking attacks because the password is stored in bcrypted form.
The password_hash() function is used to create a new password hash. It uses a strong & robust hashing algorithm. The password_hash() function is very much compatible with the crypt() function. Therefore, password hashes created by crypt() may be used with password_hash() and vice-versa. The functions password_verify() and password_hash() just the wrappers around the function crypt(), and they make it much easier to use it accurately.
SYNTAX
string password_hash($password, $algo, $options)
The following algorithms are currently supported by password_hash() function:
PASSWORD_DEFAULT
PASSWORD_BCRYPT
PASSWORD_ARGON2I
PASSWORD_ARGON2ID
Parameters: This function accepts three parameters as mentioned above and described below:
$password: It stores the password of the user.
$algo: It is the password algorithm constant that is used continuously while denoting the algorithm which is to be used when the hashing of password takes place.
$options: It is an associative array, which contains the options. If this is removed and doesn’t include, a random salt is going to be used, and the utilization of a default cost will happen.
Return Value: It returns the hashed password on success or False on failure.
Example:
Input:
echo password_hash("GFG#123", PASSWORD_DEFAULT);
Output:
$2y$10$.vGA19Jh8YrwSJFDodbfoHJIOFH)DfhuofGv3Fykk1a
Below programs illustrate the password_hash() function in PHP:
<?php echo password_hash("GFG#123", PASSWORD_DEFAULT); ?>
OUTPUT
$2y$10$Z166W1fBdsLcXPVQVfPw/uRq1ueWMA6sLt9bmdUFz9AmOGLdM393G
The password_hash() function in PHP is a built-in function, used to create a new password hash with different algorithms and options. The function uses a strong hashing algorithm.
The function take 2 mandatory parameters: $password and $algorithm, and 1 optional parameter $options.
$strongPassword = password_hash( $password, $algorithm, $options );
Algorithms allowed right now for password_hash() are:
PASSWORD_DEFAULT
PASSWORD_BCRYPT
PASSWORD_ARGON2I
PASSWORD_ARGON2ID
Example:
echo password_hash("abcDEF", PASSWORD_DEFAULT);
Answer:
$2y$10$KwKceUaG84WInAif5ehdZOkE4kHPWTLp0ZK5a5OU2EbtdwQ9YIcGy
Example:
echo password_hash("abcDEF", PASSWORD_BCRYPT);
Answer:
$2y$10$SNly5bFzB/R6OVbBMq1bj.yiOZdsk6Mwgqi4BLR2sqdCvMyv/AyL2
To use the BCRYPT, set option cost=12 in an $options, also change first parameter $password to some strong password like "wgt167yuWBGY##1987__".
Example:
echo password_hash("wgt167yuWBGY##1987__", PASSWORD_BCRYPT, ['cost' => 12]);
Answer:
$2y$12$TjSggXiFSidD63E.QP8PJOds2texJfsk/82VaNU8XRZ/niZhzkJ6S

Using Md5 for password hash in Auth component of Cakephp 2.x

I have an existing website, built using CakePhp 1.3. In that website I have used MD5 algorithm for the password hash.
Now I want to upgrade my CakePhp version to 2.3.5, but I'm unable to use MD5 for the password hash.
I would like to know why I can't use MD5 in CakePhp 2.x. ?
Don't use md5 for passwords
md5 is not an appropriate hashing algorithm for hashing passwords, don't use it. There are many, many references which explain why - including the php manual:
Why are common hashing functions such as md5() and sha1() unsuitable for passwords?
Hashing algorithms such as MD5, SHA1 and SHA256 are designed to be very fast and efficient. With modern techniques and computer equipment, it has become trivial to "brute force" the output of these algorithms, in order to determine the original input.
Because of how quickly a modern computer can "reverse" these hashing algorithms, many security professionals strongly suggest against their use for password hashing.
How to change the default hash algorithm
You can change the default hashing algorithm using setHash, a recommended hash algorithm for passwords is blowfish:
Security::setHash('blowfish');
How to handle existing passwords
If you really want to, you can just change setHash to use md5.
But that's not a good idea.
Don't compromise the security of a new/updated application just to accommodate the poor security of the old one. Instead of using the same hash algoritm (and salt) as the previous application you can use logic such as the following (pseudo-ish code):
$username = $this->data['User']['username'];
$plainText = $this->data['User']['password'];
$user = current($this->User->findByUsername($username));
Security::setHash('blowfish');
$blowfished = Security::hash($plainText, 'blowfish', $user['password']);
if ($blowfished === $user['password']) {
return true; // user exists, password is correct
}
$oldSalt = Configure::read('configure.this');
$md5ed = Security::hash($plainText, 'md5', $oldSalt);
if ($md5ed === $user['password']) {
$this->User->id = $user['id'];
$blowfished = Security::hash($plainText);
$this->User->saveField('password', $blowfished);
return true; // user exists, password now updated to blowfish
}
return false; // user's password does not exist.
This kind of logic is not complex, and prevents the need to continue using a bad hash algorithm.
I do not recommend the use of this code in any scenario, ever. MD5 is a horrible hashing algorithm for security as it is too resource-light to discourage cracking. It also has known vulnerabilities. Use bcrypt or SHA-512.
To do this, you can edit AppController.php like this:
<?php
// AppController.php
public function beforeFilter()
{
Security::setHash('md5');
}
?>
However, this is not recommended as MD5 is a very poor password hashing algorithm. You're far better adding a function to allow users to login with existing md5 passwords, encouraging them to upgrade to the new hash, and not allowing any new users to set MD5 passwords.
If, instead you want to use a secure function like bcrypt, you can do the following:
<?php
// AppController.php
public function beforeFilter()
{
Security::setHash('blowfish');
}
?>
When comparing plaintext values to hashes, you have to pass the original hash as the salt value in order to retain cost parameters etc:
$newHash = Security::hash($newPassword, 'blowfish', $storedPassword);

Does a salt and pepper password count as 96-bit encryption?

I have created this code for a salt and pepper password encryption. I assume this is a good way to encrypt passwords, but what level of encryption is this?
I first thought the 'bit' part was the length of characters used but I know that is incorrect. How many bits of encryption would this be?
PHP
function _h() {
$result = "";
$charPool = '0123456789abcdefghijklmnopqrstuvwxyz';
for($p = 0; $p<32; $p++)
$result .= $charPool[mt_rand(0,strlen($charPool)-1)];
return md5(sha1(md5(sha1($result))));
}
$salt = _h();
$pepper = _h();
$pass = $salt.md5($salt.md5($_POST['password']).$pepper).$pepper;
UPDATE
I understand this is not encryption, so I would not be able to say this is encrypted, but instead hashed. Is a hashed password with a salt and pepper secure enough to save a password?
There are quite a lot of problems with your scheme to hash a password.
PHP 5.5 will have it's own functions password_hash() and password_verify() ready, to simplify generating BCrypt password hashes. I strongly recommend to use this excellent api, or it's compatibility pack for earlier PHP versions. The usage is very straightforward:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
These functions will solve following problems:
They use a slow adaptable hash function (BCrypt), MD5 is ways too fast for hashing passwords.
They generate a safe salt from the random source of the operating system.
A pepper is not just a second salt, in contrast to a salt, the pepper is secret and will not be stored together with the hash. The same pepper will normally be used for all passwords.
There is no use in complicating the computation of salt and $peppr too much. After all the task is not the retrieval of what was originally used to produce these spices but trather the value of $_POST('a'] and you give away the $saltand $pepper as prefix/suffix (otherwise you couldn't use the stored valuelater to verify an input password with this hash). That being said, do as #zneak commented and use an expert library function.

How do you use bcrypt for hashing passwords in PHP? [duplicate]

This question already has answers here:
How to use PHP's password_hash to hash and verify passwords
(5 answers)
Closed 9 months ago.
Every now and then I hear the advice "Use bcrypt for storing passwords in PHP, bcrypt rules".
But what is bcrypt? PHP doesn't offer any such functions, Wikipedia babbles about a file-encryption utility and Web searches just reveal a few implementations of Blowfish in different languages. Now Blowfish is also available in PHP via mcrypt, but how does that help with storing passwords? Blowfish is a general purpose cipher, it works two ways. If it could be encrypted, it can be decrypted. Passwords need a one-way hashing function.
What is the explanation?
bcrypt is a hashing algorithm which is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensures that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password salts (bcrypt REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.
bcrypt uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. Because of this key difference, bcrypt is a one-way hashing algorithm. You cannot retrieve the plain text password without already knowing the salt, rounds and key (password). [Source]
How to use bcrypt:
Using PHP >= 5.5-DEV
Password hashing functions have now been built directly into PHP >= 5.5. You may now use password_hash() to create a bcrypt hash of any password:
<?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
// Usage 2:
$options = [
'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C
To verify a user provided password against an existing hash, you may use the password_verify() as such:
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
Using PHP >= 5.3.7, < 5.5-DEV (also RedHat PHP >= 5.3.3)
There is a compatibility library on GitHub created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).
Using PHP < 5.3.7 (DEPRECATED)
You can use crypt() function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library. This alternative is provided only for historical purposes.
class Bcrypt{
private $rounds;
public function __construct($rounds = 12) {
if (CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
$this->rounds = $rounds;
}
public function hash($input){
$hash = crypt($input, $this->getSalt());
if (strlen($hash) > 13)
return $hash;
return false;
}
public function verify($input, $existingHash){
$hash = crypt($input, $existingHash);
return $hash === $existingHash;
}
private function getSalt(){
$salt = sprintf('$2a$%02d$', $this->rounds);
$bytes = $this->getRandomBytes(16);
$salt .= $this->encodeBytes($bytes);
return $salt;
}
private $randomState;
private function getRandomBytes($count){
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
$bytes = openssl_random_pseudo_bytes($count);
}
if ($bytes === '' && is_readable('/dev/urandom') &&
($hRand = #fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if (strlen($bytes) < $count) {
$bytes = '';
if ($this->randomState === null) {
$this->randomState = microtime();
if (function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for ($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
private function encodeBytes($input){
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (true);
return $output;
}
}
You can use this code like this:
$bcrypt = new Bcrypt(15);
$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
Alternatively, you may also use the Portable PHP Hashing Framework.
So, you want to use bcrypt? Awesome! However, like other areas of cryptography, you shouldn't be doing it yourself. If you need to worry about anything like managing keys, or storing salts or generating random numbers, you're doing it wrong.
The reason is simple: it's so trivially easy to screw up bcrypt. In fact, if you look at almost every piece of code on this page, you'll notice that it's violating at least one of these common problems.
Face It, Cryptography is hard.
Leave it for the experts. Leave it for people whose job it is to maintain these libraries. If you need to make a decision, you're doing it wrong.
Instead, just use a library. Several exist depending on your requirements.
Libraries
Here is a breakdown of some of the more common APIs.
PHP 5.5 API - (Available for 5.3.7+)
Starting in PHP 5.5, a new API for hashing passwords is being introduced. There is also a shim compatibility library maintained (by me) for 5.3.7+. This has the benefit of being a peer-reviewed and simple to use implementation.
function register($username, $password) {
$hash = password_hash($password, PASSWORD_BCRYPT);
save($username, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
if (password_verify($password, $hash)) {
//login
} else {
// failure
}
}
Really, it's aimed to be extremely simple.
Resources:
Documentation: on PHP.net
Compatibility Library: on GitHub
PHP's RFC: on wiki.php.net
Zend\Crypt\Password\Bcrypt (5.3.2+)
This is another API that's similar to the PHP 5.5 one, and does a similar purpose.
function register($username, $password) {
$bcrypt = new Zend\Crypt\Password\Bcrypt();
$hash = $bcrypt->create($password);
save($user, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
$bcrypt = new Zend\Crypt\Password\Bcrypt();
if ($bcrypt->verify($password, $hash)) {
//login
} else {
// failure
}
}
Resources:
Documentation: on Zend
Blog Post: Password Hashing With Zend Crypt
PasswordLib
This is a slightly different approach to password hashing. Rather than simply supporting bcrypt, PasswordLib supports a large number of hashing algorithms. It's mainly useful in contexts where you need to support compatibility with legacy and disparate systems that may be outside of your control. It supports a large number of hashing algorithms. And is supported 5.3.2+
function register($username, $password) {
$lib = new PasswordLib\PasswordLib();
$hash = $lib->createPasswordHash($password, '$2y$', array('cost' => 12));
save($user, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
$lib = new PasswordLib\PasswordLib();
if ($lib->verifyPasswordHash($password, $hash)) {
//login
} else {
// failure
}
}
References:
Source Code / Documentation: GitHub
PHPASS
This is a layer that does support bcrypt, but also supports a fairly strong algorithm that's useful if you do not have access to PHP >= 5.3.2... It actually supports PHP 3.0+ (although not with bcrypt).
function register($username, $password) {
$phpass = new PasswordHash(12, false);
$hash = $phpass->HashPassword($password);
save($user, $hash);
}
function login($username, $password) {
$hash = loadHashByUsername($username);
$phpass = new PasswordHash(12, false);
if ($phpass->CheckPassword($password, $hash)) {
//login
} else {
// failure
}
}
Resources
Code: cvsweb
Project Site: on OpenWall
A review of the < 5.3.0 algorithm: on StackOverflow
Note: Don't use the PHPASS alternatives that are not hosted on openwall, they are different projects!!!
About BCrypt
If you notice, every one of these libraries returns a single string. That's because of how BCrypt works internally. And there are a TON of answers about that. Here are a selection that I've written, that I won't copy/paste here, but link to:
Fundamental Difference Between Hashing And Encryption Algorithms - Explaining the terminology and some basic information about them.
About reversing hashes without rainbow tables - Basically why we should use bcrypt in the first place...
Storing bcrypt Hashes - basically why is the salt and algorithm included in the hash result.
How to update the cost of bcrypt hashes - basically how to choose and then maintain the cost of the bcrypt hash.
How to hash long passwords with bcrypt - explaining the 72 character password limit of bcrypt.
How bcrypt uses salts
Best practices of salting and peppering passwords - Basically, don't use a "pepper"
Migrating old md5 passwords to bcrypt
Wrap Up
There are many different choices. Which you choose is up to you. However, I would HIGHLY recommend that you use one of the above libraries for handling this for you.
Again, if you're using crypt() directly, you're probably doing something wrong. If your code is using hash() (or md5() or sha1()) directly, you're almost definitely doing something wrong.
Just use a library...
You'll get a lot of information in Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes or Portable PHP password hashing framework.
The goal is to hash the password with something slow, so someone getting your password database will die trying to brute force it (a 10 ms delay to check a password is nothing for you, a lot for someone trying to brute force it). Bcrypt is slow and can be used with a parameter to choose how slow it is.
You can create a one-way hash with bcrypt using PHP's crypt() function and passing in an appropriate Blowfish salt. The most important of the whole equation is that A) the algorithm hasn't been compromised and B) you properly salt each password. Don't use an application-wide salt; that opens up your entire application to attack from a single set of Rainbow tables.
PHP - Crypt Function
Edit: 2013.01.15 - If your server will support it, use martinstoeckli's solution instead.
Everyone wants to make this more complicated than it is. The crypt() function does most of the work.
function blowfishCrypt($password,$cost)
{
$chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$salt=sprintf('$2y$%02d$',$cost);
//For PHP < PHP 5.3.7 use this instead
// $salt=sprintf('$2a$%02d$',$cost);
//Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
mt_srand();
for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
return crypt($password,$salt);
}
Example:
$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password
I know it should be obvious, but please don't use 'password' as your password.
Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash() and password_verify(). Actually these are just wrappers around the function crypt(), and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.
The easiest way to use this functions will be:
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This code will hash the password with BCrypt (algorithm 2y), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.
Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
In contrast to the "cost" parameter, it is best to omit the "salt" parameter, because the function already does its best to create a cryptographically safe salt.
For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash() function. For PHP versions before 5.3.7 there is no support for crypt() with 2y, the unicode safe BCrypt algorithm. One could replace it instead with 2a, which is the best alternative for earlier PHP versions.
Current thinking: hashes should be the slowest available, not the fastest possible. This suppresses rainbow table attacks.
Also related, but precautionary: An attacker should never have unlimited access to your login screen. To prevent that: Set up an IP address tracking table that records every hit along with the URI. If more than 5 attempts to login come from the same IP address in any five minute period, block with explanation. A secondary approach is to have a two-tiered password scheme, like banks do. Putting a lock-out for failures on the second pass boosts security.
Summary: slow down the attacker by using time-consuming hash functions. Also, block on too many accesses to your login, and add a second password tier.
Here's an updated answer to this old question!
The right way to hash passwords in PHP since 5.5 is with password_hash(), and the right way to verify them is with password_verify(), and this is still true in PHP 8.0. These functions use bcrypt hashes by default, but other stronger algorithms have been added. You can alter the work factor (effectively how "strong" the encryption is) via the password_hash parameters.
However, while it's still plenty strong enough, bcrypt is no longer considered state-of-the-art; a better set of password hash algorithms has arrived called Argon2, with Argon2i, Argon2d, and Argon2id variants. The difference between them (as described here):
Argon2 has one primary variant: Argon2id, and two supplementary variants: Argon2d and Argon2i. Argon2d uses data-depending memory access, which makes it suitable for cryptocurrencies and proof-of-work applications with no threats from side-channel timing attacks. Argon2i uses data-independent memory access, which is preferred for password hashing and password-based key derivation. Argon2id works as Argon2i for the first half of the first iteration over the memory, and as Argon2d for the rest, thus providing both side-channel attack protection and brute-force cost savings due to time-memory tradeoffs.
Argon2i support was added in PHP 7.2, and you request it like this:
$hash = password_hash('mypassword', PASSWORD_ARGON2I);
and Argon2id support was added in PHP 7.3:
$hash = password_hash('mypassword', PASSWORD_ARGON2ID);
No changes are required for verifying passwords since the resulting hash string contains information about what algorithm, salt, and work factors were used when it was created.
Quite separately (and somewhat redundantly), libsodium (added in PHP 7.2) also provides Argon2 hashing via the sodium_crypto_pwhash_str () and sodium_crypto_pwhash_str_verify() functions, which work much the same way as the PHP built-ins. One possible reason for using these is that PHP may sometimes be compiled without libargon2, which makes the Argon2 algorithms unavailable to the password_hash function; PHP 7.2 and higher should always have libsodium enabled, but it may not - but at least there are two ways you can get at that algorithm. Here's how you can create an Argon2id hash with libsodium (even in PHP 7.2, which otherwise lacks Argon2id support)):
$hash = sodium_crypto_pwhash_str(
'mypassword',
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);
Note that it doesn't allow you to specify a salt manually; this is part of libsodium's ethos – don't allow users to set params to values that might compromise security – for example there is nothing preventing you from passing an empty salt string to PHP's password_hash function; libsodium doesn't let you do anything so silly!
For OAuth 2 passwords:
$bcrypt = new \Zend\Crypt\Password\Bcrypt;
$bcrypt->create("youpasswordhere", 10)
As we all know storing password in clear text in database is not secure.
the bcrypt is a hashing password technique.It is used to built password security. One of the amazing function of bcrypt is it save us from hackers it is used to protect the password from hacking attacks because the password is stored in bcrypted form.
The password_hash() function is used to create a new password hash. It uses a strong & robust hashing algorithm. The password_hash() function is very much compatible with the crypt() function. Therefore, password hashes created by crypt() may be used with password_hash() and vice-versa. The functions password_verify() and password_hash() just the wrappers around the function crypt(), and they make it much easier to use it accurately.
SYNTAX
string password_hash($password, $algo, $options)
The following algorithms are currently supported by password_hash() function:
PASSWORD_DEFAULT
PASSWORD_BCRYPT
PASSWORD_ARGON2I
PASSWORD_ARGON2ID
Parameters: This function accepts three parameters as mentioned above and described below:
$password: It stores the password of the user.
$algo: It is the password algorithm constant that is used continuously while denoting the algorithm which is to be used when the hashing of password takes place.
$options: It is an associative array, which contains the options. If this is removed and doesn’t include, a random salt is going to be used, and the utilization of a default cost will happen.
Return Value: It returns the hashed password on success or False on failure.
Example:
Input:
echo password_hash("GFG#123", PASSWORD_DEFAULT);
Output:
$2y$10$.vGA19Jh8YrwSJFDodbfoHJIOFH)DfhuofGv3Fykk1a
Below programs illustrate the password_hash() function in PHP:
<?php echo password_hash("GFG#123", PASSWORD_DEFAULT); ?>
OUTPUT
$2y$10$Z166W1fBdsLcXPVQVfPw/uRq1ueWMA6sLt9bmdUFz9AmOGLdM393G
The password_hash() function in PHP is a built-in function, used to create a new password hash with different algorithms and options. The function uses a strong hashing algorithm.
The function take 2 mandatory parameters: $password and $algorithm, and 1 optional parameter $options.
$strongPassword = password_hash( $password, $algorithm, $options );
Algorithms allowed right now for password_hash() are:
PASSWORD_DEFAULT
PASSWORD_BCRYPT
PASSWORD_ARGON2I
PASSWORD_ARGON2ID
Example:
echo password_hash("abcDEF", PASSWORD_DEFAULT);
Answer:
$2y$10$KwKceUaG84WInAif5ehdZOkE4kHPWTLp0ZK5a5OU2EbtdwQ9YIcGy
Example:
echo password_hash("abcDEF", PASSWORD_BCRYPT);
Answer:
$2y$10$SNly5bFzB/R6OVbBMq1bj.yiOZdsk6Mwgqi4BLR2sqdCvMyv/AyL2
To use the BCRYPT, set option cost=12 in an $options, also change first parameter $password to some strong password like "wgt167yuWBGY##1987__".
Example:
echo password_hash("wgt167yuWBGY##1987__", PASSWORD_BCRYPT, ['cost' => 12]);
Answer:
$2y$12$TjSggXiFSidD63E.QP8PJOds2texJfsk/82VaNU8XRZ/niZhzkJ6S

How can I store my users' passwords safely?

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]!";
}
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.
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.
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.
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
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.
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.
Here's a PHP + CouchDB.apache.org login system that doesn't store plaintext passwords.
According to the advice that I've read, it should be totally secure.
CMS login code : https://github.com/nicerapp/nicerapp/blob/24ff0ca317b28c1d91aee66041320976a6d76da7/nicerapp/boot.php#L56
calls
https://github.com/nicerapp/nicerapp/blob/24ff0ca317b28c1d91aee66041320976a6d76da7/nicerapp/functions.php#L171
app(s) specific business code :
https://github.com/nicerapp/nicerapp/blob/24ff0ca317b28c1d91aee66041320976a6d76da7/nicerapp/ajax_login.php#L87
calls
https://github.com/nicerapp/nicerapp/blob/24ff0ca317b28c1d91aee66041320976a6d76da7/nicerapp/functions.php#L230
which in turn calls :
https://github.com/nicerapp/nicerapp/blob/2d479b3e22dce9e7073525481b775f1bf7389634/nicerapp/apps/nicer.app/webmail/recrypt.php#L2
and to edit the webmail app config data into the database :
https://github.com/nicerapp/nicerapp/blob/main/nicerapp/apps/nicer.app/webmail/ajax_editConfig.php

Categories