|
| 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 | +} |
0 commit comments