The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Security
Hashing
What is a hash, and why do we store passwords as hashes?
Why it exists — If you store passwords as they are, then the moment the database leaks or an administrator looks inside it, the passwords of all members are exposed, and other sites where the same password is used are put at risk too. If you store a hash of the password, the server can check only "is what was entered correct?" without keeping the original password, and even if someone steals the stored value, they cannot log in with that value right away.
Where it's used today — For a service with sign-up and login, storing a hash of the password is the basic practice. A service built with Spring makes the value to store with encode of PasswordEncoder (often BCryptPasswordEncoder), which Spring Security provides, and checks it with matches at login. A hash that is calculated fast, such as SHA-256, is calculated with MessageDigest, which Java provides, and it is used to check that a downloaded file was not changed on the way.
A hash function is a calculation that gives a mixed-up value of a fixed length, whatever text you put in. The same text gives the same value, a change of even one character gives a completely different value, and you cannot calculate the original text backwards from the value that came out. So at sign-up the server stores not the password itself but the hashed value, and at login it only checks whether the text that was entered matches that value. In a service built with Spring, PasswordEncoder, which Spring Security provides, does this work. In the code, encoder.encode("pass1234") makes the value to store, and encoder.matches(input, saved) checks whether the input is correct. PasswordEncoder is an interface, and here we use BCryptPasswordEncoder, which implements it with a password-only hash called BCrypt. Each time encode runs, it makes a new random value (a salt) and calculates it together with the password, so even the same pass1234 gives a different value each time you call encode. For comparison, the lab also has code that calculates SHA-256 itself with MessageDigest, which Java provides, and stores that, and code that stores the password as it is. With the three ways of storing, you enter the correct password, a password that differs by one character, and the stored value itself, and see how login goes. (saved, input, and ok are variable names chosen for this lab.)
Checked against real execution · Ten combinations were compiled with javax.tools and run on JDK 21 and Spring Security 7.1.1 (BCryptPasswordEncoder) and checked against the model. The form of the encode value, the result of matches, the example BCrypt values, and the SHA-256 values were also checked against the standard examples, Node.js, and openssl
Concepts in this lab
- Hash function
- Why it exists — To see whether two pieces of data are the same, you would normally have to put all of both side by side and compare them. A hash function lets you compare only a short value, so you can tell whether your copy has changed without downloading the original again.
- Where it's used today — Compare the SHA-256 value of a downloaded file with the value written on the site to check that the file was not changed or damaged during the download. The 40-character name that Git gives each commit is also a value made by a hash function.
- A hash function is a calculation that gives a mixed-up value of a fixed length, whatever length of text (data) you put in, and that value is called a hash value or a digest. SHA-256 gives a 256-bit value, that is, 64 hexadecimal characters, whether the input is 1 character or 100 characters. The same input always gives the same value, and if the input changes even a little, a completely different value comes out with very high probability. This term means a cryptographic hash function such as SHA-256, which is used for a different purpose from the hash code used in the data structure HashMap.
- One-way function
- A hash function being one-way means that it is easy to calculate the value from the input, but it is made so that finding the original input backwards from the value that came out is not practically possible. The NIST standard explains that it calls these functions secure because finding an input that matches a given hash value, and finding two different inputs that give the same hash value, is computationally infeasible. This is not proven mathematically; it means no method is known. One-way is different from encryption. With encryption you can turn the value back if you have the key, but a hash has no key to turn it back. Also, a short and common input can be found by hashing the candidates one by one and comparing them.
- PasswordEncoder
- Why it exists — If each developer writes the code that stores passwords by hand, it is easy to use a fast hash or to forget the salt. If making the value to store and checking it are put together in one interface, you can use a well-tested method as it is and change the method later more easily.
- Where it's used today — In a sign-up service, you store the value from encode in the database, and Spring Security checks it with matches at login. In a Spring Boot application, you register PasswordEncoder as a bean and use it, and the one that PasswordEncoderFactories.createDelegatingPasswordEncoder() makes puts the name of the method at the front of the value, as in {bcrypt}.
- PasswordEncoder is an interface that Spring Security provides, and it fixes encode, which turns a password into the value to store, and matches, which checks whether an entered password matches the stored value. The implementation classes are also provided by Spring Security, and if you create the commonly used BCryptPasswordEncoder without arguments, encode makes a new salt and gives a 60-character value that starts with $2a$10$. Because of the salt, even the same password gives a different value each time you call encode, so you compare with the stored value using matches(input, stored value), not equals. matches reads the salt from the stored value, calculates the input in the same way, and returns only whether it matched (true or false).
- bcrypt
- Where it's used today — It is used when storing member passwords. The default encoder created by Spring Security's PasswordEncoderFactories also stores new passwords with bcrypt, and other choices for the same purpose include Argon2, scrypt, and PBKDF2.
- A hash function designed for storing passwords. It generates a salt automatically and includes it in the result, and it lets you set a work factor (cost) that makes the computation slow on purpose. A slow computation greatly increases the time an attacker needs to try a huge number of candidates. Spring Security's BCryptPasswordEncoder uses it.
- Salt
- Why it exists — If you hash without a salt, the same password always gives the same value, so just by matching against a list of hash values of common passwords calculated in advance, many passwords are exposed at once. If a different value is mixed in each time you store, that list cannot be used.
- Where it's used today — BCryptPasswordEncoder of Spring Security makes a new salt each time encode runs and writes it at the front of the value to store, and matches reads that salt and calculates again. The developer does not have to make or store a salt separately.
- A salt is a random value that is mixed in when a password is hashed. It is made new for each password (and each time the same password is stored), so two members who use the same password have different stored values. The same salt is needed when checking, so it is kept together with the stored value, and BCrypt writes the salt at the front of the stored 60-character value (the 22 characters after the cost). A salt is not a secret, and it is used to prevent many passwords from being found at once with a list of hashes calculated in advance.
- MessageDigest
- Why it exists — If you implement a hash algorithm yourself, it is easy to get it wrong and hard to verify. Java lets you take out the implementation of a standard algorithm by name, so you get the same result in any environment.
- Where it's used today — Calculate the SHA-256 value of a downloaded file or of data that was exchanged, and compare it with the written value to check that it was not changed or damaged on the way. It is not suitable for storing passwords because it is fast and has no salt, so use PasswordEncoder for that.
- MessageDigest is a class that Java provides for hash calculation (java.security.MessageDigest). You get an object by the name of the algorithm, as in MessageDigest.getInstance("SHA-256"), and when you call digest(byte array), it returns the hash result as a byte array. For SHA-256 this is 32 bytes, and if you turn it into text with HexFormat.of().formatHex, it becomes 64 characters of 0-9 and a-f. It does not mix in a salt, so the same input always gives the same value.
- Password hashing
- Password hashing is the method of storing the hash value of a password at sign-up, not the password itself. At login, you calculate the entered text in the same way, and if it matches the stored value, the input is taken to be the same as the password at sign-up. The server can check that a password is right without knowing the original password. Even if the stored value leaks, the original password is not revealed right away, and even if you put that value in the password field, it is calculated once more and becomes a different value, so you cannot log in. In Spring, you do it with PasswordEncoder of Spring Security: encode makes the value to store, and matches checks it. OWASP says not to use a fast hash function such as SHA-256 as it is, but to use a slow password-only function such as Argon2id or bcrypt with a salt that is unique to each user.
Try these
- Default settings — encode makes a 60-character value that starts with $2a$10$ and stores it, and at login matches checks whether the input matches that value. The password is correct, so it is true.
- Enter a password that differs by one character — matches returns false, and login fails.
- Encode again and compare with equals — encode makes a new salt each time and gives a different value, so you get false even though the password is correct. To compare with a stored value, use matches.
- Enter the stored value — matches calculates the input as a password, so it differs from the stored value, and login fails.
- Calculate SHA-256 directly and store it — There is no salt, so the same text always gives the same 64-character value however many times you calculate it. So you can calculate again and compare with equals, but members who use the same password also have the same stored value.
- Enter a password that differs by one character into SHA-256 — The value of pass1235 differs from the value of pass1234 in 61 of the 64 characters.
- Enter a value that was stored as it is — The stored value is the password itself, so you log in as it is.
Running with the default settings
- The line PasswordEncoder encoder = new BCryptPasswordEncoder(); runs. The type of the variable encoder is PasswordEncoder, and its value is a BCryptPasswordEncoder object. PasswordEncoder is an interface that Spring Security provides, and BCryptPasswordEncoder is a class, also provided by Spring Security, that implements it with a password-only hash called BCrypt.
- The line String saved = encoder.encode("pass1234"); runs. At the moment of sign-up, encode receives the password pass1234 that the user chose. encode first makes a new random value (a salt), and calculates that salt and the password together with BCrypt. BCrypt is a hash that is deliberately made slow by repeating the calculation many times.
- The value that comes out is 60 characters long and starts with $2a$10$. $2a$ is the marker that the value was made with BCrypt, 10 is the cost value that decides how many times the calculation is repeated, and after that the next 22 characters are the salt and the remaining 31 are the hash result. The value that came out in this run is $2a$10$rlL85YF/J1.aZXD3Bv0GWekFKyqt/OrhKPdwFShdqxkvr3HaDO/4a. The salt is made new each time, so a different value comes out every run.
- The server stores only this 60-character value in saved. It does not store the original password pass1234. The salt is written at the front of this value, so it is not stored separately.
- The line String input = "pass1234"; runs. Now it is login. The user enters pass1234 in the password field.
- encoder.matches(input, saved) runs. matches reads the cost and the salt from the front of saved, and calculates the entered text with BCrypt using the same salt as at sign-up. It differs from encode in that it does not make a new salt.
- The value it calculated is the same 60 characters as saved. This is because the same password was calculated with the same salt.
- matches compares the value it calculated with saved, and they are the same, so it returns true and ok is true. Login succeeds. matches does not return the value it calculated; it returns only whether it matched (true or false). The server did not keep the original password, but it still checked whether it matched.
- System.out.println(saved) prints the 60-character stored value, and System.out.println(ok) prints true. If you run it again, saved is printed as a different 60 characters, but ok stays the same.
Result of this run
- encode of PasswordEncoder turns the password into a 60-character value that starts with $2a$10$, and the server stores only that value. At login, matches(input, saved value) calculated the input again with the salt of the stored value and checked whether it matched, and it was the same pass1234, so it returned true and login succeeded.
- The server did not store the original password, and it did not need to in order to check. Even if the stored value leaks, no method is known to calculate pass1234 backwards from that value. A common password can be found by calculating the candidates one by one and comparing, but BCrypt is deliberately slow to calculate, so that work takes a lot of time.
Code
// Only the lines inside the main method are shown (the import lines and the class and main declarations are omitted)
PasswordEncoder encoder = new BCryptPasswordEncoder();
// At sign-up: encode stores the hash of the password
String saved = encoder.encode("pass1234");
// At login: pass the entered text and the stored value to matches to compare
String input = "pass1234";
boolean ok = encoder.matches(input, saved);
System.out.println(saved);
System.out.println(ok);
Assumptions of this model
The compiler and runtime are JDK 21.0.12.1 (javac 21), and PasswordEncoder and BCryptPasswordEncoder are from Spring Security 7.1.1 (spring-security-crypto 7.1.1). For all ten combinations (4 for storing with PasswordEncoder, 3 for storing with SHA-256, and 3 for storing as it is), the code on the screen was wrapped in the frame of the import lines, a class, and a main method (throws Exception) to make the source, which was compiled with javax.tools, loaded with a new class loader, and main was run (verify/spring/src/HashBasicProbe.java). What was checked is whether the code on the screen is the same text as that part of the source that was run, and the saved and ok that the program printed. The saved of BCrypt is different every run, so what was checked is whether the saved from the run has the form of $2a$10$ followed by 53 characters and whether ok is the same as the login in the result table. The two BCrypt values (B1 and B2) shown on the screen and in the result table are examples copied from the values that came out when encode("pass1234") was actually called twice, and for both values it was confirmed that matches("pass1234", value) is true and that the two values differ from each other. The value that matches calculates is not returned by matches, so it was shown by calculating it with BCrypt.hashpw(input, stored value) of Spring Security. Looking with javap, matches of BCryptPasswordEncoder calls BCrypt.checkpw, and checkpw calculates the input with the cost and salt of the stored value and compares it with the stored value. For each combination that was run, the value calculated with hashpw was the same as saved, and the result of matches was the same. When the same password was encoded 20 times, all 20 values and salts were different and matches was true for all of them, and when the values encoded again were compared with equals, it was false. The measured time was tens of ms for one matches (about 59ms and 78ms in two runs) and less than 0.1ms for one SHA-256 (it depends on the CPU). If you create BCryptPasswordEncoder without arguments, the cost is 10 and the value starts with $2a$. The Spring Security documentation (Password Storage) explains that PasswordEncoder lets you transform a password one way so that it is stored safely, and introduces DelegatingPasswordEncoder, made with PasswordEncoderFactories.createDelegatingPasswordEncoder(), so that you can change the storage method later. The value this makes is a BCrypt value with {bcrypt} at the front (it was confirmed by running that it starts with {bcrypt}$2a$10$). This lab created BCryptPasswordEncoder directly to show what PasswordEncoder does. In a Spring Boot application, you usually register PasswordEncoder as a bean and use it. For the SHA-256 side, to check that the calculation follows the standard, two standard examples of SHA-256 (the message "abc" and a 56-character message) were calculated with MessageDigest and compared with the NIST example document and the values in RFC 6234, and 7 inputs (including an empty text, 1 character, and 100 characters) were also calculated with Node.js crypto and openssl dgst -sha256, and the values of the three implementations were confirmed to be the same. The SHA-256 values of pass1234 and pass1235 differ in 61 of the 64 characters (this is the value observed with these inputs), and the result is 64 characters whether the input is 0, 1, or 100 characters. NIST FIPS 180-4 (Secure Hash Standard) defines SHA-256 as a one-way hash function that makes a value called a digest from a message, and says that if the message changes even a little, a different digest comes out with very high probability. The OWASP Password Storage Cheat Sheet says not to store passwords in plaintext but to hash them, says that a fast hash such as SHA-256 is not suitable for storing passwords, and says to add a salt that is unique to each user and to use a slow password-only function such as Argon2id, scrypt, bcrypt, or PBKDF2. In this lab, "you cannot calculate it backwards" does not mean that it has been proven mathematically, but that no practical method is known, and a short and common password can be found by calculating the candidates one by one and comparing them with the stored value. The code on the screen writes sign-up and login one after the other in a single run. In a real service, sign-up and login are different requests, saved is kept in the database, and it is assumed that the server receives the password text that the user entered and calculates it. The fact that BCrypt uses only the first 72 bytes of the password, how to choose the cost, changing a stored value to a stronger method, and hash collisions are not covered (the detailed behavior of BCrypt is covered in the "In-depth lab: Password hashing"). The hash function in this lab is a cryptographic hash function, and its use is different from the hash code of HashMap.
Previous lab: Tokens · Next lab: Encryption