How do you use bcrypt for hashing passwords in PHP? (ok)
https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php
Last updated
https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php
Last updated
Ask QuestionAsked 9 years agoActive 2 months agoViewed 384k times1238612
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?php passwords cryptography password-protection bcryptshareimprove this questionedited Apr 13 '14 at 17:01Peter Mortensen24.8k2020 gold badges8989 silver badges118118 bronze badgesasked Jan 25 '11 at 15:34Vilx-91k7575 gold badges247247 silver badges385385 bronze badges
13This question has been addressed previously, and their suggestion of using a standard library is excellent. Security is a complicated matter, and by using a package designed by someone who knows what the hell they're doing you're only helping yourself. – eykanal May 23 '11 at 1:44
57@eykanal - that page doesn't even mention bcrypt, much less explain what it is. – Vilx- May 23 '11 at 8:18
8@eykanal - I don't ask an explanation of how it works. I just want to know what it is. Because whatever I can dig up on the net under the keyword "bcrypt", can be in no way used for hashing passwords. Not directly anyway, and not in PHP. OK, by now I understand that it's really the "phpass" package which uses blowfish to encrypt your password with a key that is derived from your password (in essence encrypting the password with itself). But referencing it as "bcrypt" is severely misleading, and that is what I wanted to clarify in this question. – Vilx- May 23 '11 at 14:44
3@Vilx: I've added more information as to why bcrypt
is a one-way hashing algorithm versus an encryption scheme in my answer. There is this whole misconception that bcrypt
is just Blowfish when in fact it has a totally different key schedule which ensures that plain text cannot be recovered from the cipher text without knowing the initial state of the cipher (salt, rounds, key). – Andrew Moore Sep 8 '11 at 22:00
1Also see Openwall's Portable PHP password hashing framework (PHPass). Its hardened against a number of common attacks on user passwords. – jww Oct 11 '14 at 23:25
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]
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:
To verify a user provided password against an existing hash, you may use the password_verify()
as such:
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).
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.
You can use this code like this:
Alternatively, you may also use the Portable PHP Hashing Framework.shareimprove this answeredited Apr 19 '18 at 19:10community wiki 24 revs, 13 users 77% Andrew Moore
7@The Wicked Flea: Sorry to disappoint you, but mt_rand()
is also seeded using the current time and the current process ID. Please see GENERATE_SEED()
in /ext/standard/php_rand.h
. – Andrew Moore Jul 8 '11 at 15:45
53@Mike: Go ahead, it's there for exactly that reason! – Andrew Moore Aug 12 '11 at 4:01
14For anyone thinking that they need to modify the beginning of the $salt string in the getSalt function, that is not necessary. The $2a$__ is part of the CRYPT_BLOWFISH salt. From the docs: "Blowfish hashing with a salt as follows: "$2a$", a two digit cost parameter, "$", and 22 digits from the alphabet". – jwinn Aug 21 '11 at 9:18
18@MichaelLang: Good thing crypt()
is peer-reviewed and verified then. The code above calls PHP's crypt()
, which calls the POSIX crypt()
function. All the code above does more is generating a random salt (which doesn't have to be cryptographically secure, the salt isn't considered a secret) before calling crypt()
. Maybe you should do a little research yourself before calling wolf. – Andrew Moore Aug 4 '12 at 17:03
31Please note that this answer, while good, is starting to show its age. This code (like any PHP implementation relying on crypt()
) is subject to a security vulnerability pre-5.3.7, and is (very slightly) inefficient post-5.3.7 - details of the relevant issue can be found here. Please also note that the new password hashing API (backwards compat lib) is now the preferred method of implementing bcrypt password hashing in your application. – DaveRandom Dec 19 '12 at 14:48
show 71 more comments292+50
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.
Leave it for the experts. Leave it for people who's 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.
Here is a breakdown of some of the more common APIs.
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.
Really, it's aimed to be extremely simple.
Resources:
Documentation: on PHP.net
Compatibility Library: on GitHub
PHP's RFC: on wiki.php.net
This is another API that's similar to the PHP 5.5 one, and does a similar purpose.
Resources:
Documentation: on Zend
Blog Post: Password Hashing With Zend Crypt
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+
References:
Source Code / Documentation: GitHub
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).
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!!!
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.
Best practices of salting and peppering passwords - Basically, don't use a "pepper"
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.
7The salt has to be randomly generated, however it doesn't need to come from a secure random source. The salt is not a secret. Being able to guess the next salt has no real security impact; as long as they come from a sufficiently large pool of data to generate different salts for each password encoded, you are fine. Remember, the salt is there to prevent the use of rainbow tables if your hashes come into bad hands. They are not secret. – Andrew Moore Jun 21 '13 at 14:00
7@AndrewMoore absolutely correct! However, the salt has to have enough entropy to be statistically unique. Not just in your application, but in all applications. So mt_rand()
has a high enough period, but the seed value is only 32 bits. So using mt_rand()
effectively limits you to only 32 bits of entropy. Which thanks to the Birthday Problem means that you have a 50% chance of collision at only 7k generated salts (globally). Since bcrypt
accepts 128 bits of salt, it's better to use a source that can supply all 128 bits ;-). (at 128 bits, 50% chance of collision happens at 2e19 hashes)... – ircmaxell Jun 21 '13 at 14:09
1@ircmaxell: Hense the "sufficiently large pool of data". However your source doesn't have to be a VERY HIGH entropy source, just high enough for the 128 bits. However, if you have exhausted all your available sources (don't have OpenSSL, etc...) and your only fallback is mt_rand(), it is still better than the alternative (which is rand()). – Andrew Moore Jun 23 '13 at 1:08
4@AndrewMoore: absolutely. Not arguing that. Just that mt_rand
and uniqid
(and hence lcg_value
and rand
) are not first choices... – ircmaxell Jun 23 '13 at 23:28
1ircmaxell, thank you very much for the the password_compat library for 5.3.xx, we haven't needed this before but now we do, on a 5.3.xx php server, and thank you for your clear advice to not try to do this logic oneself. – Lizardx Dec 8 '15 at 23:23
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.
7Enforce whatever you want, users will manage to screw up and use the same password on multiple things. So you have to protect it as much as possible or implement something which let you not have to store any password (SSO, openID etc.). – Arkh Jan 25 '11 at 15:49
41No. Password hashing is used to protect against one attack : someone stole your database and want to get cleartext login + passwords. – Arkh Jan 25 '11 at 15:54
4@Josh K. I encourage you to try to crack some simple passwords after getting them through phpass tuned so it takes between 1ms and 10ms to compute it on your webserver. – Arkh Jan 25 '11 at 16:02
3Agreed. But the kind of user who will use qwerty as a password is also the kind of user who will mark down any complicated one somewhere he (and attackers) can easily read it. What using bcrypt accomplishes is that when your db goes public against your will, it'll be harder to get to those user who have some password like ^|$$&ZL6-£ than if you used sha512 in one pass. – Arkh Jan 25 '11 at 16:12
4@coreyward worth noting that doing that is more harmful than not blocking at all; that is easily considered a "denial of service" vector. Just start spamming bad logins on any known accounts and you can disrupt many users very, very easily. It's better to tarpit (delay) the attacker than outright deny access, especially if it's a paying customer. – damianb May 21 '12 at 0:17
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.
4This is the right approach - use PHP's crypt()
function, which supports several different password hashing functions. Make sure you are not using CRYPT_STD_DES
or CRYPT_EXT_DES
- any of the other supported types are fine (and includes bcrypt, under the name CRYPT_BLOWFISH
). – caf Jan 27 '11 at 5:41
4SHA indeed has a cost parameter as well, via the 'rounds' option. When using that, I also see no reason to favour bcrypt. – Pieter Ennes Jul 7 '11 at 12:03
3Actually, a single SHA-1 (or MD5) of a password is still easily brute-force-able, with or without salt (salt helps against rainbow tables, not against brute-forcing). Use bcrypt. – Paŭlo Ebermann Sep 9 '11 at 14:46
I find it disturbing that everybody seems to say "bcrypt" when they mean php's crypt(). – Sliq May 11 '13 at 20:28
3@Panique Why? The algorithm is called bcrypt. crypt
exposes several password hashes, with bcrypt corresponding to the CRYPT_BLOWFISH
constant. Bcrypt is currently the strongest algorithm supported by crypt
and several others it supports are quite weak. – CodesInChaos Jun 22 '13 at 16:49
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.
Example:
3The creation of the salt could be improved (use the random source of the OS), otherwise it looks good to me. For newer PHP versions it is better to use 2y
instead of 2a
. – martinstoeckli Jan 10 '13 at 14:45
use mcrypt_create_iv($size, MCRYPT_DEV_URANDOM)
as source for the salt. – CodesInChaos Jan 10 '13 at 21:00
I'll take a closer look at mcrypt_create_iv() when I get a moment, if nothing else it should improve performance slightly. – Jon Hulka Jan 11 '13 at 2:04
2Add Base64 encoding and translate to the custom alphabet bcrypt
uses. mcrypt_create_iv(17, MCRYPT_DEV_URANDOM)
, str_replace('+', '.', base64_encode($rawSalt))
, $salt = substr($salt, 0, 22);
– CodesInChaos Jan 12 '13 at 8:22
1@JonHulka - Have a look at PHP's compatibility pack [Line 127], this is a straightforward implementation. – martinstoeckli Jan 12 '13 at 10:24
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:
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:
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.
3After I read this, my first thought was "how do you store the salt that is generated"? After poking through the docs, the password_hash() function ends up generating a string that stores the encryption method, the salt, and the generated hash. So, it just stores everything it needs in one string for the password_verify() function to work. Just wanted to mention this as it may help others when they view this. – jzimmerman2011 Aug 29 '14 at 13:20
@jzimmerman2011 - Exactly, in an other answer i tried to explain this storage format with an example. – martinstoeckli Aug 29 '14 at 13:40
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.
I think they assume that the attacker has already managed to steal my DB through some other means, and is now trying to get the passwords out in order to try them on paypal or something. – Vilx- Dec 7 '11 at 22:35
4Half way through 2012 and this answer is still wonky, how does a slow hashing algorithm prevent rainbow table attacks? I thought a random byte range salt did? I always thought the speed of the hashing algorithm dictates how many iterations they can send against the hash they got form you in a specific amount of time. Also NEVER EVER BLOCK A USER ON FAILED LOGIN ATTEMPTS trust me your users will get fed up, often on some sites I need to login near 5 times sometimes more before I remember my password for it. Also second pass tier doesn't work, two step auth with mobile phone code could though. – Sammaye Aug 14 '12 at 15:02
1@Sammaye I would agree with this to a point. I setup a block on 5 failed login attempts, before raising it quickly to 7, then 10 now its sitting on 20. No normal user should have 20 failed login attempts but its low enough to easily stop brute force attacks – Bruce Aldridge Sep 1 '12 at 9:37
@BruceAldridge I personally would think it would be better to make your script pause for a random time after say, 7 failed logins and show a captcha rather than block. Blocking is a very aggresive move to take. – Sammaye Sep 1 '12 at 10:36
1@Sammaye I agree permanent blocks are bad. I'm referring to a temporary block that increases with the number of failed attempts. – Bruce Aldridge Sep 14 '12 at 9:34
For OAuth 2 passwords:
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
Just use a library...shareimprove this answeredited Oct 17 '17 at 16:53Yann Chabot3,99533 gold badges2828 silver badges4545 bronze badgesanswered Jun 12 '13 at 19:23ircmaxell147k3232 gold badges248248 silver badges303303 bronze badges
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.shareimprove this answeredited May 23 '16 at 18:12Peter Mortensen24.8k2020 gold badges8989 silver badges118118 bronze badgesanswered Jan 25 '11 at 15:46Arkh8,0263434 silver badges4141 bronze badges
PHP - Crypt Functionshareimprove this answeredited Jan 11 '13 at 8:21onkar3,90766 gold badges3838 silver badges7676 bronze badgesanswered Jan 25 '11 at 15:48coreyward58.3k1515 gold badges109109 silver badges131131 bronze badges
I know it should be obvious, but please don't use 'password' as your password.shareimprove this answeredited May 23 '17 at 12:02Community♦111 silver badgeanswered Oct 31 '12 at 8:25Jon Hulka1,14799 silver badges1313 bronze badges
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.shareimprove this answeredited Apr 16 '13 at 19:34answered Jan 11 '13 at 8:07martinstoeckli19.4k44 gold badges4242 silver badges7070 bronze badges
An alternative is to use scrypt, specifically designed to be superior to bcrypt by Colin Percival in his paper. There is an scrypt PHP extension in PECL. Ideally this algorithm would be rolled into PHP so that it could be specified for the password_* functions (ideally as "PASSWORD_SCRYPT"), but that's not there yet.shareimprove this answeranswered Feb 19 '14 at 14:17Synchro23.4k1212 gold badges6363 silver badges7777 bronze badgesadd a comment6
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.shareimprove this answeredited Apr 13 '14 at 17:10Peter Mortensen24.8k2020 gold badges8989 silver badges118118 bronze badgesanswered Dec 7 '11 at 20:56FYA38233 silver badges55 bronze badges
shareimprove this answeredited May 23 '16 at 18:16Peter Mortensen24.8k2020 gold badges8989 silver badges118118 bronze badgesanswered Mar 25 '16 at 16:55Shemeer M Ali8961010 silver badges3434 bronze badgesadd a comment1
shareimprove this answeranswered Nov 11 '19 at 15:54Nayab Muhammad14266 bronze badgesadd a commentHighly active question. Earn 10 reputation in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.