I know PHP 5.5 is in alpha but this class I am making is just being made in advance to utilize it's hashing feature by using function_exists().
I checked out the password_hash documentation. The 3rd argument is for $options which currently supports two options, 'salt' and 'cost'.
It states the following:
cost, which denotes the algorithmic cost that should be used. Examples
of these values can be found on the crypt() page.
When I go to the crypt() page the documentation it gives is:
Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a
two digit cost parameter, "$", and 22 digits from the alphabet
"./0-9A-Za-z". Using characters outside of this range in the salt will
cause crypt() to return a zero-length string. The two digit cost
parameter is the base-2 logarithm of the iteration count for the
underlying Blowfish-based hashing algorithmeter and must be in range
04-31, values outside this range will cause crypt() to fail. Versions
of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7
introduced the new prefixes to fix a security weakness in the Blowfish
implementation. Please refer to ยป this document for full details of
the security fix, but to summarise, developers targeting only PHP
5.3.7 and later should use "$2y$" in preference to "$2a$".
I can't seem to get my head wrapped around this. It says PHP 5.3.7 and later should use $2y$, but what cost value do I use to get that one and is it the best value to choose? The example they provide uses a value of 7, but according to the above it can go up to 31, what difference does it make to use say 4 opposed to say 31?
The function password_hash() is just a wrapper 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 function would be:
$hash = password_hash($password, PASSWORD_DEFAULT);
That means, the function will hash the password with BCrypt (algorithm 2y), generates a random salt, and uses the default cost (at the moment this is 10). These are good default values, particularly i would not recommend generating the salt of your own, it is easy to make mistakes there.
Should you want to change the cost parameter, you can do it like this:
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 11]);
Increasing the cost parameter by 1, doubles the needed time to calculate the hash value. The cost parameter is the logarithm (base-2) of the iteration count, which means:
$iterations = 2 ^ $cost;
Edit:
I missed the point, that you want to generate your own class. For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash() function. You can either use this code directly, or look at the well crafted implementation. For PHP versions before 5.3.7 there is no support for crypt with 2y, the unicode aware BCrypt algorithm. You can instead use 2a, which is the best alternative for earlier PHP versions. I did an example with a lot of comments, maybe you want to have a look at it too.
P.S. The expressions "salt" and "cost factor" are used correctly in password_hash(), the crypt() function though, uses the word salt for all crypt parameters together, that's a bit misleading.
Disclaimer: this is with PHP 5.3.10, but it seems not really different from your description.
The cost applies to the cost of computation. When you increase the cost value, it takes longer to hash the password
function blowfish_salt($cost)
{
$chars = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$salt = sprintf('$2y$%02d$', $cost);
for ($i = 0; $i < 22; ++$i)
$salt .= $chars[rand(0,63)];
return $salt;
}
$password = 'My perfect password';
$cost = $argv[1];
$salt = blowfish_salt($cost);
$hash = crypt($password, $salt);
When I run this on my (old) machine as
php mycrypt.php 10
it returns immediately (~0.2 sec), whereas with
php mycrypt.php 16
it takes about 5.2 seconds.
Related
Just before using password_hash(), I check if PASSWORD_DEFAULT === PASSWORD_BCRYPT to see if I need to do some cleanup on the password before it's hashed (Argon2 won't need this).
I'm simply passing it though a quick hash first, because bcrypt has an issue with NULL characters, and passwords longer than 72 characters (more info, and a different example).
But in PHP 7.4, the constant PASSWORD_DEFAULT is now set to NULL.
So how can I tell what algorithm password_hash() will use?
This is an interesting problem, for which I believe there is no standard function yet. This is not a huge problem because the hash itself contains an identifier telling us which hash algorithm was used. The important thing to note here is that PASSWORD_DEFAULT is a constant. Constants do not change.
To figure out which algorithm is used when using the default constant (which was and still is bcrypt), you need to generate some dummy hash and look at the beginning of it. We can even use a nice helper function password_get_info()
$hashInfo = password_get_info(password_hash('pass', PASSWORD_DEFAULT, [ 'cost' => 4 ] ));
echo $hashInfo['algo']; // should return either 1 or 2y
if($hashInfo['algo'] === PASSWORD_BCRYPT) {
// will be true for PHP <= 7.4
}
Edit
As of PHP 7.4.3 you can continue using PASSWORD_DEFAULT === PASSWORD_BCRYPT
https://3v4l.org/nN4Qi
You don't actually have to use password_hash twice. A better and faster way is to provide an already hashed value with Bcrypt and check it against PASSWORD_DEFAULT with
password_needs_rehash function to see if the default algo has changed or not.
bcrypt algorithm is the default as of PHP 5.5.0
So for example:
$hash = '$2y$10$ra4VedcLU8bv3jR0AlpEau3AZevkQz4Utm7F8EqUNE0Jqx0s772NG'; // Bcrypt hash
// if it doesn't need rehash then the default algo is absolutely Bcrypt
if (! password_needs_rehash($hash, PASSWORD_DEFAULT)) {
// do some clean up
}
Note: make sure that the hash value($hash) has the same cost provided in password_needs_rehash's third parameter, otherwise it will consider the hash outdated and need rehash since the cost has changed.
So I heard that PHP 7.2 introduced the new Argon2 algorithm. But I'm confused on how I can use it with my existing code. For instance, I have this
$password = password_hash('somepassword', PASSWORD_DEFAULT, ['cost' => 12]);
Does PASSWORD_DEFAULT now use Argon2? What, if anything, do I need to change with password_verify? Is bcrypt considered insecure now?
What is Argon2? Is bcrypt bad now?
Prior to PHP 7.2, the only hashing algorithm password_hash used was bcrypt. As of this writing, bcrypt is still considered a strong hash, especially compared to its predecessors, md5 and sha1 (both of which are insecure because they are fast). Argon2 is simply a costlier algorithm to brute force
Argon2i uses data-independent memory access. It is slower because it makes more passes over the memory to protect from trade off attacks. It is highly recommended for password hashing and password-based key derivation.
Bcrypt is still an acceptable hash for passwords. There's no need to switch if you don't want to (as of the 7.2.0 release). Also, PASSWORD_DEFAULT should only change (per PHP Internals policy) on the next full release (7.3.0 or higher). If you want to ensure you continue with only bcrypt, you can use PASSWORD_BCRYPT instead. This is unnecessary, however, as we'll discuss below.
How do you use Argon2?
First, we'll switch the second argument of password_hash over to one of these to constants
PASSWORD_ARGON2I - PHP 7.2.0+
PASSWORD_ARGON2ID - PHP 7.3.0+ (preferred if available, see notes below)
and then we'll need to change our options. bcrypt uses cost as the parameter for how many times it iterates over the password (higher cost = longer hashing time). There's different cost factors, however
password_hash('somepassword', PASSWORD_ARGON2I, ['memory_cost' => 2048, 'time_cost' => 4, 'threads' => 3]);
From the manual we see what these options do
memory_cost - Maximum memory (in kibibytes) that may be used to compute the Argon2 hash (default 1024)
time_cost - Maximum amount of time it may take to compute the Argon2 hash (default 2)
threads - Number of threads to use for computing the Argon2 hash (default 2)
Understand, before you go changing these, that a higher cost here will slow down your script. You'll want to run a test on your server to find a setting that works best for you. This is typically by looping over several iterations of a given cost. The PHP manual gives an example of this if you need one.
Also note that, while bcrypt stores 60 characters, Argon2 can require more than that. You should, ideally, make your password field store 255 characters.
What do we change in password_verify?
The answer here is... nothing. Understand that password_verify is smart enough to figure out what algorithm was used and handle it appropriately. As mentioned above, this means that if you are using PASSWORD_DEFAULT, the default can change and not negatively affect you (although you may need to adjust the cost parameters). password_verify simply requires an algorithm it supports. If you switch from bcrypt to Argon2, both will verify the same way, as all the necessary data (salt, hash and cost) are stored for you.
//Works for both bcrypt and Argon2
if(password_verify($user_password, $stored_hash)) {
// password validated
}
If you want to upgrade the hashes from bcrypt, you can do this when a user successfully logs in (and thus supplied you with the un-hashed password). Simply check if your hash starts with $2y$ (the bcrypt marker). If it does, pass the supplied password to password_hash again, but with the Argon2 arguments, and save it to the password field of the logged-in user.
What is Argon2ID?
Introduced in PHP 7.3, Argon2ID makes some improvements over Argon2I as noted in this Crypto.SE question
The best tradeoff attack on 1-pass Argon2id is the combined low-storage attack (for the first half of the memory) and the ranking attack (for the second half), which bring together the factor of about 2.1.
Argon2ID works with the same arguments that Argon2I works with.
Only if you use PHP 7.3:
I've created 2 simple and slim functions to use Argon2ID with PHP:
function argon2idHash($plaintext, $password, $encoding = null) {
$plaintextsecured = hash_hmac("sha256", $plaintext, $password);
return $encoding == "hex" ? bin2hex(password_hash($plaintextsecured, PASSWORD_ARGON2ID)) : ($encoding == "base64" ? base64_encode(password_hash($plaintextsecured, PASSWORD_ARGON2ID)) : password_hash($plaintextsecured, PASSWORD_ARGON2ID));
}
function argon2idHashVerify($plaintext, $password, $hash, $encoding = null) {
$plaintextsecured = hash_hmac("sha256", $plaintext, $password);
return password_verify($plaintextsecured, $encoding == "hex" ? hex2bin($hash) : ($encoding == "base64" ? base64_decode($hash) : $hash)) ? true : false;
}
To get an hashed value use (the last parameter is optional, you can choose hex, base64 or nothing) [return => string]:
$salt = "LALALA";
argon2idHash($clearvalue, $salt, "hex"); // with encoding
argon2idHash($clearvalue, $salt); // without encoding
To verify an hashed value use (parameter $salt must match the salt set at the time of hashing also the same rule applies to encoding if used) [return => bool]:
$salt = "LALALA";
argon2idHashVerify($clearvalue, $salt, $hashtoverify, "hex") ? "match" : "dont match"; // with encoding
argon2idHashVerify($clearvalue, $salt, $hashtoverify) ? "match" : "dont match"; // without encoding
Finally, if you know PHP you can modify these functions to your liking, but for now it's the best way I know to securely store passwords in databases.
Using the password "testtest" and the hash "KFtIFW1vulG5nUH3a0Mv" with the following code results in different hashes depending on the PHP version (as shown in the image below):
$salt = "KFtIFW1vulG5nUH3a0Mv";
$password = "testtest";
$key = '$2a$07$';
$key = $key.$salt."$";
echo crypt($password, $key);
Output 1 (PHP v.5.3.0 - 5.4.41, 5.5.21 - 5.5.25, 5.6.5 - 5.6.9): $2a$07$KFtIFW1vulG5nUH3a0Mv$.0imhrNa/laTsN0Ioj5m357/a8AxxF2q
Output 2 (PHP v.5.5.0 - 5.5.20, 5.6.0 - 5.6.4): $2a$07$KFtIFW1vulG5nUH3a0Mv$e0imhrNa/laTsN0Ioj5m357/a8AxxF2q
Here is an example of the problem:
http://3v4l.org/dikci
This is a massive issue if crypt is being used to hash passwords for a login, as depending on PHP version the hash will be different. Anybody understand what this issue is from and how to deal with it?
This is not so much an issue as you may think.
First you should note, that your code is not absolutely correct, BCrypt requires a 22 character salt, but you provided a 20 character salt. This means that the terminating '$' (which is not necessary btw) will be seen as part of the salt, as well as the first letter of your password. The $ is not a valid character for a BCrypt salt though.
Another thing to consider is that not all bits of character 22 are used, this is due to the encoding, ircmaxell gave a good explanation about this. So different salts can result in the same hash, you can see this well in this answer. How different implementations handle this last bits of the character 22 could theoretically change. As long as the crypt function can verify the password with both hashes there is no problem.
The generation of the salt with its pitfalls is one of the reasons, why the functions password_hash() and password_verify() where written, they make the password handling much easier.
I understand that PHP's crypt() function works like so:
crypt($password,$salt);
And that to create a bcrypt hash(which is considered very secure) the format is:
crypt("$2y$15$password",$salt);
Where $2y specifies the use of bcrypt, and 15 is the number of rounds, and it should be above 10.
Here's my question. Running:
crypt("$2y$15$password");
in my understanding, generates a nice big random salt and adds it to the hash, and when comparing passwords, this is extracted automatically. This would mean that I wouldn't have to have a salt field in my table, or generate a salt independently. Is this secure and correct?
For example, when I run:
$test = "Hello";
echo crypt("$2y$15$test") . "\n";
I get:
$6$R59d/nemygl0$/Gk6s57K2eFAkH4BWDGYhfdhbYGcqz.GRbD7qGDKOlhE5Lk.kgCoGQo/sDCCf1VDffdh7jtXPn/9rsexwrpFk1
Where the first 6 refers to some algorithm number, the next bit between the two $ is the salt, and the bit after that is the hash. Is this correct?
Also, what is the syntax for comparing this hash to another for verification?
Thanks.
I think crypt as you're using it uses SHA-512.
You probably forgot to pass $test as parameter in your crypt().
According to php docs you should pass the password as first argument (without any prefix) and then pass the salt as second argument with the $2y$15 prefix and a 22 characters salt. E.g.
crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$');
The function crypt() should be used like this:
$hashvalue = crypt($password, $cryptParams);
whereas the salt must be generated by yourself and is part of $cryptParams.
$bcryptAlgo = '$2y';
$cost = '$15';
$salt = '$' . functionThatGenerates22CharRandomSalt();
$cryptParams = $bcryptAlgo . $cost . $salt;
One of the difficulties is to generate a valid, unique and unpredictable salt. The best you can do is to read from the operating systems random source.
PHP 5.5 will have it's own functions password_hash() and password_verify() ready, to simplify this task. I strongly recommend to use this excellent api, there is also a compatibility pack available for earlier PHP versions. If you want to know more about how to use crypt, have a look at this article.
Your cost parameter of 15 is quite high, use it if you can afford this much of time, but today a number of 10 is ok.
At the moment I have a database with md5 passwords stored, a few years back this was considered a little more secure than it is now and it's got to the point where the passwords need to be more secure.
I've read a lot of posts on here about crypt, md5, hash, bcrypt, etc and have come to consider using something along the lines of the following to 'secure' the passwords better than they are now.
I will use a combination of hash("sha512" and two salts, the first salt will be a site wide salt stored in a file such as .htaccess and the second salt will be created for each user.
Here's an example along the lines of what I'm testing at the moment:
.htaccess
SetEnv SITEWIDE_SALT NeZa5Edabex?26Y#j5pr7VASpu$8UheVaREj$yA*59t*A$EdRUqer_prazepreTr
example.php
$currentpassword = //get password
$pepper = getenv('SITEWIDE_SALT');
$salt = microtime().ip2long($_SERVER['REMOTE_ADDR']);
$saltpepper = $salt.$pepper;
$password = hash("sha512", md5($currentpassword).$saltpepper);
The salt would obviously need to be stored in a separate table to allow checking of future inserted login passwords but it would never be possible for a user to see. Do you think this is a sufficient way to go about this?
Ok, let's go over a few points here
What you have in $salt is not a salt. It's deterministic (meaning that there is no randomness in there at all). If you want a salt, use either mcrypt_create_iv($size, MCRYPT_DEV_URANDOM) or some other source of actual random entropy. The point is that it should be both unique and random. Note that it doesn't need to be cryptographically secure random... At absolute worst, I'd do something like this:
function getRandomBytes($length) {
$bytes = '';
for ($i = 0; $i < $length; $i++) {
$bytes .= chr(mt_rand(0, 255));
}
return $bytes;
}
As #Anony-Mousse indicated, never feed the output of one hash function into another without re-appending the original data back to it. Instead, use a proper iterative algorithm such as PBKDF2, PHPASS or CRYPT_BLOWFISH ($2a$).
My suggestion would be to use crypt with blowfish, as it's the best available for PHP at this time:
function createBlowfishHash($password) {
$salt = to64(getRandomBytes(16));
$salt = '$2a$10$' . $salt;
$result = crypt($password, $salt);
}
And then verify using a method like this:
function verifyBlowfishHash($password, $hash) {
return $hash == crypt($password, $hash);
}
(note that to64 is a good method defined here). You could also use str_replace('+', '.', base64_encode($salt));...
I'd also suggest you read the following two:
Fundamental difference between hashing and encrypting
Many hash iterations, append salt every time?
Edit: To Answer the Migration Question
Ok, so I realize that my answer did not address the migration aspect of the original question. So here's how I would solve it.
First, build a temporary function to create a new blowfish hash from the original md5 hash, with a random salt and a prefix so that we can detect this later:
function migrateMD5Password($md5Hash) {
$salt = to64(getRandomBytes(16));
$salt = '$2a$10$' . $salt;
$hash = crypt($md5Hash, $salt);
return '$md5' . $hash;
}
Now, run all the existing md5 hashes through this function and save the result in the database. We put our own prefix in so that we can detect the original password and add the additional md5 step. So now we're all migrated.
Next, create another function to verify passwords, and if necessary update the database with a new hash:
function checkAndMigrateHash($password, $hash) {
if (substr($hash, 0, 4) == '$md5') {
// Migrate!
$hash = substr($hash, 4);
if (!verifyBlowfishHash(md5($password), $hash) {
return false;
}
// valid hash, so let's generate a new one
$newHash = createBlowfishHash($password);
saveUpdatedPasswordHash($newHash);
return true;
} else {
return verifyBlowfishHash($password, $hash);
}
}
This is what I would suggest for a few reasons:
It gets the md5() hashes out of your database immediately.
It eventually (next login for each user) updates the hash to a better alternative (one that's well understood).
It's pretty easy to follow in code.
To answer the comments:
A salt doesn't need to be random - I direct you to RFC 2898 - Password Based Cryptography. Namely, Section 4.1. And I quote:
If there is no concern about interactions between multiple uses
of the same key (or a prefix of that key) with the password-
based encryption and authentication techniques supported for a
given password, then the salt may be generated at random and
need not be checked for a particular format by the party
receiving the salt. It should be at least eight octets (64
bits) long.
Additionally,
Note. If a random number generator or pseudorandom generator is not
available, a deterministic alternative for generating the salt (or
the random part of it) is to apply a password-based key derivation
function to the password and the message M to be processed.
A PseudoRandom Generator is available, so why not use it?
Is your solution the same as bcrypt? I can't find much documentation on what bcrypt actually is? - I'll assume that you already read the bcrypt Wikipedia Article, and try to explain it better.
BCrypt is based off the Blowfish block cipher. It takes the key schedule setup algorithm from the cipher, and uses that to hash the passwords. The reason that it is good, is that the setup algorithm for Blowfish is designed to be very expensive (which is part of what makes blowfish so strong of a cypher). The basic process is as follows:
A 18 element array (called P boxes, 32 bits in size) and 4 2-dimensional arrays (called S boxes, each with 256 entries of 8 bits each) are used to setup the schedule by initializing the arrays with predetermined static values. Additionally, a 64 bit state is initialized to all 0's.
The key passed in is XOred with all 18 P boxes in order (rotating the key if it's too short).
The P boxes are then used to encrypt the state that was previously initialized.
The ciphertext produced by step 3 is used to replace P1 and P2 (the first 2 elements of the P array).
Step 3 is repeated, and the result is put in P3 and P4. This continues until P17 and P18 are populated.
That's the key derivation from the Blowfish Cipher. BCrypt modifies that to this:
The 64 bit state is initialized to an encrypted version of the salt.
Same
The P boxes are then used to encrypt the (state xor part of the salt) that was previously initialized.
Same
Same
The resulting setup is then used to encrypt the password 64 times. That's what's returned by BCrypt.
The point is simple: It's a very expensive algorithm that takes a lot of CPU time. That's the real reason that it should be used.
I hope that clears things up.
Implementation of your new, more secure, password storage should use bcrypt or PBKDF2, as that's really the best solution out there right now.
Don't nest things, as you don't get any real security out of this due to collisions as #Anony-Mousse describes.
What you may want to do it implement a "transition routine" where your app transitions users over from the old MD5-based system to the new more secure system as they log in. When a login request comes in, see if the user is in the new, more secure, system. If so, bcrypt/PBKDF2 the password, compare, and you're good to go. If they are not (no one will be at first), check them using the older MD5-based system. If it matches (password is correct), perform the bcrypt/PBKDF2 transformation of the password (since you now have it), store it in the new system, and delete the old MD5 record. Next time they log in, they have an entry in the new system so you're good to go. Once all of the users have logged in once you implement this, you can remove this transition functionality and just authenticate against the new system.
Do not nest md5 inside your sha512 hash. An md5 collision then implies a hash collision in the outer hash, too (because you are hashing the same values!)
The common way of storing passwords is to use a scheme such as
<method><separator><salt><separator><hash>
When validating the password, you read <method> and <salt> from this field, reapply them to the password, and then check that it produces the same <hash>.
Check the crypt functions you have available. On a modern Linux system, crypt should be able to use sha512 password hashing in a sane way: PHP crypt manual. Do not reinvent the wheel, you probably just screw up more badly than md5, unless you are an expert on cryptographic hashing. It will even take care of above scheme: the Linux standard is to use $ as separator, and $6$ is the method ID for sha512, while $2a$ indicates you want to use blowfish. So you can even have multiple hashes in use in your database. md5 hashes are prefixed with $1$<salt>$ (unless you reinvented md5 hashing, then your hashes may be incompatible).
Seriously, reuse the existing crypt function. It is well checked by experts, extensible, and compatible across many applications.
I looked into this subject a while back and found the following link of great use:
Secure hash and salt for PHP passwords
I also use the following to create a random salt:
public static function getRandomString($length = 20) {
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= substr($characters, (mt_rand() % strlen($characters)), 1);
}
return $string;
}