Related
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
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.
As php.net states here:
It is not recommended to use this function to secure passwords, due to
the fast nature of this hashing algorithm.
I have used the md5 function since I started programming with PHP, but after researching, it is clear that md5 is discouraged and an alternative should be used.
I am aware of a possible alternative, sha1. Are there any others as well?
What are the benefits of these other ones, and sha1 (excluding higher security)?
And most importantly, can a sha1 hash or any of the other hashing algorithms be replicated in javascript?
I have an md5 plugin in javascript and it is key to some of my secure applications. Therefore, having a hashing algorithm that has a javascript plugin is absolutely essential.
SHA1 and MD5 have pretty much the same weakness: Their collision resistance is broken. So when MD5 is wrong, so is SHA1. Their output is also a bit short. If collision resistance is required, I recommend at least 256 bit hashes. More than 256 bits are rarely necessary.
For normal hashing applications SHA-256 (part of the SHA-2 family) is a good choice. While it's performance isn't too great, nobody has broken its collision resistance so far. You can also go with SHA-3-256, but the library support isn't that great yet.
For password hashing you need a specialized construction, such as scrypt, bcrypt or PBKDF2. Use a unique salt and a sufficient iteration count. Do not use a plain hash, they're too fast.
For MAC(Message Authentication) use a specialized construction, such as HMAC-SHA-256 and not plain SHA-256.
The upcoming WebCryptoAPI will contain functions for most of these operations.
Until it gets deployed, you can use crypto-js which offers both PBKDF2 and SHA-256.
But I'm a bit doubtful about your architecture. Hashing passwords in javascript is rarely the right choice. Standard procedure is using SSL/TLS and sending the plaintext password over it. You cannot achieve security with in browser javascript unless you use TLS.
Yes, there are many other hashing algorithms as well, much stronger than SHA1. Check SHA512, for example: it has 512 bits against, for example, 128 bits for MD5.
Anyway, if you're looking for real safety, you should apply one of the following:
1) "Fixed salt": instead of md5($pass), you use:
$salt="NaCl";
$hash=md5($salt);
2) "Random salt": instead of md5($pass)', you generate a random salt (use the function rand($minValue, $maxValue)) with a great range (say rand(0, pow(10, 100)) and use md5($pass, $salt). Don't forget to store BOTH the hash and the salt!
3) Encryption: you use either a fixed or a random key (see the precedent method), and use it to encrypt the password. I'd really suggest the Blowfish algorithm.
From the page on PHP.net:
<?php
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "This is a very secret key";
$text = "Meet me at 11 o'clock behind the monument.";
echo strlen($text) . "\n";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
echo strlen($crypttext) . "\n";
?>
Implementing SHA512 in JavaScript (without the salt generation) (from the CryptoJS library):
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/sha512.js"></script>
<script> var hash = CryptoJS.SHA512("Message"); </script>
Implementing bcrypt in JavaScript: see this example.
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;
}
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