Skip to content

Commit 4d27803

Browse files
sjmillingtonjzheaux
authored andcommitted
Password Hashing, PBKDF2 and SHA-512
Issue: BAEL-2164
1 parent a5acc10 commit 4d27803

5 files changed

Lines changed: 313 additions & 0 deletions

File tree

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import java.security.NoSuchAlgorithmException;
4+
import java.security.SecureRandom;
5+
import java.security.spec.InvalidKeySpecException;
6+
import java.security.spec.KeySpec;
7+
import java.util.Arrays;
8+
import java.util.Base64;
9+
import java.util.regex.Matcher;
10+
import java.util.regex.Pattern;
11+
12+
import javax.crypto.SecretKeyFactory;
13+
import javax.crypto.spec.PBEKeySpec;
14+
15+
/**
16+
* Hash passwords for storage, and test passwords against password tokens.
17+
*
18+
* Instances of this class can be used concurrently by multiple threads.
19+
*
20+
* @author erickson
21+
* @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
22+
*/
23+
public final class PBKDF2Hasher
24+
{
25+
26+
/**
27+
* Each token produced by this class uses this identifier as a prefix.
28+
*/
29+
public static final String ID = "$31$";
30+
31+
/**
32+
* The minimum recommended cost, used by default
33+
*/
34+
public static final int DEFAULT_COST = 16;
35+
36+
private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
37+
38+
private static final int SIZE = 128;
39+
40+
private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
41+
42+
private final SecureRandom random;
43+
44+
private final int cost;
45+
46+
public PBKDF2Hasher()
47+
{
48+
this(DEFAULT_COST);
49+
}
50+
51+
/**
52+
* Create a password manager with a specified cost
53+
*
54+
* @param cost the exponential computational cost of hashing a password, 0 to 30
55+
*/
56+
public PBKDF2Hasher(int cost)
57+
{
58+
iterations(cost); /* Validate cost */
59+
this.cost = cost;
60+
this.random = new SecureRandom();
61+
}
62+
63+
private static int iterations(int cost)
64+
{
65+
if ((cost < 0) || (cost > 30))
66+
throw new IllegalArgumentException("cost: " + cost);
67+
return 1 << cost;
68+
}
69+
70+
/**
71+
* Hash a password for storage.
72+
*
73+
* @return a secure authentication token to be stored for later authentication
74+
*/
75+
public String hash(char[] password)
76+
{
77+
byte[] salt = new byte[SIZE / 8];
78+
random.nextBytes(salt);
79+
byte[] dk = pbkdf2(password, salt, 1 << cost);
80+
byte[] hash = new byte[salt.length + dk.length];
81+
System.arraycopy(salt, 0, hash, 0, salt.length);
82+
System.arraycopy(dk, 0, hash, salt.length, dk.length);
83+
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
84+
return ID + cost + '$' + enc.encodeToString(hash);
85+
}
86+
87+
/**
88+
* Authenticate with a password and a stored password token.
89+
*
90+
* @return true if the password and token match
91+
*/
92+
public boolean checkPassword(char[] password, String token)
93+
{
94+
Matcher m = layout.matcher(token);
95+
if (!m.matches())
96+
throw new IllegalArgumentException("Invalid token format");
97+
int iterations = iterations(Integer.parseInt(m.group(1)));
98+
byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
99+
byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
100+
byte[] check = pbkdf2(password, salt, iterations);
101+
int zero = 0;
102+
for (int idx = 0; idx < check.length; ++idx)
103+
zero |= hash[salt.length + idx] ^ check[idx];
104+
return zero == 0;
105+
}
106+
107+
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
108+
{
109+
KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
110+
try {
111+
SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
112+
return f.generateSecret(spec).getEncoded();
113+
}
114+
catch (NoSuchAlgorithmException ex) {
115+
throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
116+
}
117+
catch (InvalidKeySpecException ex) {
118+
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
119+
}
120+
}
121+
122+
/**
123+
* Hash a password in an immutable {@code String}.
124+
*
125+
* <p>Passwords should be stored in a {@code char[]} so that it can be filled
126+
* with zeros after use instead of lingering on the heap and elsewhere.
127+
*
128+
* @deprecated Use {@link #hash(char[])} instead
129+
*/
130+
@Deprecated
131+
public String hash(String password)
132+
{
133+
return hash(password.toCharArray());
134+
}
135+
136+
/**
137+
* Authenticate with a password in an immutable {@code String} and a stored
138+
* password token.
139+
*
140+
* @deprecated Use {@link #checkPassword(char[],String)} instead.
141+
* @see #hash(String)
142+
*/
143+
@Deprecated
144+
public boolean checkPassword(String password, String token)
145+
{
146+
return checkPassword(password.toCharArray(), token);
147+
}
148+
149+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import java.nio.charset.StandardCharsets;
4+
import java.security.MessageDigest;
5+
import java.security.NoSuchAlgorithmException;
6+
7+
8+
/** A really simple SHA_512 Encryption example.
9+
*
10+
*/
11+
public class SHA512Hasher {
12+
13+
public String hash(String passwordToHash, byte[] salt){
14+
String generatedPassword = null;
15+
try {
16+
MessageDigest md = MessageDigest.getInstance("SHA-512");
17+
md.update(salt);
18+
byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
19+
StringBuilder sb = new StringBuilder();
20+
for(int i=0; i< bytes.length ;i++){
21+
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
22+
}
23+
generatedPassword = sb.toString();
24+
}
25+
catch (NoSuchAlgorithmException e){
26+
e.printStackTrace();
27+
}
28+
return generatedPassword;
29+
}
30+
31+
public boolean checkPassword(String hash, String attempt, byte[] salt){
32+
String generatedHash = hash(attempt, salt);
33+
return hash.equals(generatedHash);
34+
}
35+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import javax.crypto.SecretKeyFactory;
4+
import javax.crypto.spec.PBEKeySpec;
5+
import java.security.spec.KeySpec;
6+
7+
/** A really simple SimplePBKDF2 Encryption example.
8+
*
9+
*/
10+
public class SimplePBKDF2Hasher {
11+
12+
public static String hashSimple(String password, byte[] salt) throws Exception{
13+
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
14+
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
15+
byte[] hash = f.generateSecret(spec).getEncoded();
16+
return String.valueOf(hash);
17+
}
18+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
8+
9+
public class PBKDF2HasherUnitTest {
10+
11+
private PBKDF2Hasher mPBKDF2Hasher;
12+
13+
@Before
14+
public void setUp() throws Exception {
15+
mPBKDF2Hasher = new PBKDF2Hasher();
16+
}
17+
18+
@Test
19+
public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception {
20+
String message1 = "password123";
21+
22+
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
23+
24+
assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1));
25+
26+
}
27+
28+
@Test
29+
public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception {
30+
String message1 = "password123";
31+
32+
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
33+
34+
String wrongPasswordAttempt = "IamWrong";
35+
36+
assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1));
37+
38+
}
39+
40+
41+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import java.security.SecureRandom;
7+
8+
import static org.junit.Assert.*;
9+
10+
/**
11+
* Created by PhysicsSam on 06-Sep-18.
12+
*/
13+
public class SHA512HasherUnitTest {
14+
15+
private SHA512Hasher hasher;
16+
private SecureRandom secureRandom;
17+
18+
@Before
19+
public void setUp() throws Exception {
20+
hasher = new SHA512Hasher();
21+
secureRandom = new SecureRandom();
22+
}
23+
24+
@Test
25+
public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception {
26+
27+
byte[] salt = new byte[16];
28+
secureRandom.nextBytes(salt);
29+
30+
String hash1 = hasher.hash("password", salt);
31+
String hash2 = hasher.hash("password", salt);
32+
33+
assertEquals(hash1, hash2);
34+
35+
}
36+
37+
@Test
38+
public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception {
39+
40+
byte[] salt = new byte[16];
41+
secureRandom.nextBytes(salt);
42+
String hash1 = hasher.hash("password", salt);
43+
//generate a second salt
44+
byte[] secondSalt = new byte[16];
45+
String hash2 = hasher.hash("password", secondSalt);
46+
47+
assertNotEquals(hash1, hash2);
48+
49+
}
50+
51+
@Test
52+
public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception {
53+
byte[] salt = new byte[16];
54+
secureRandom.nextBytes(salt);
55+
56+
String originalHash = hasher.hash("password123", salt);
57+
58+
assertTrue(hasher.checkPassword(originalHash, "password123", salt));
59+
}
60+
61+
@Test
62+
public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception {
63+
byte[] salt = new byte[16];
64+
secureRandom.nextBytes(salt);
65+
66+
String originalHash = hasher.hash("password123", salt);
67+
68+
assertFalse(hasher.checkPassword(originalHash, "password124", salt));
69+
}
70+
}

0 commit comments

Comments
 (0)