How to Hash Passwords Securely in Java
Securing passwords is crucial in any application that handles sensitive user information. Hashing passwords provides a one-way encryption method that prevents passwords from being decrypted and stored in plain text.
Scenario:
You want to hash passwords for storage in a database, adding a random salt for additional security.
Solution:
The Java Runtime Environment (JRE) includes a built-in facility for password hashing using PBKDF2 (Password-Based Key Derivation Function 2). This method offers robust password protection, and here's how to implement it:
SecureRandom random = new SecureRandom(); byte[] salt = new byte[16]; random.nextBytes(salt); KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 128); SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] hash = f.generateSecret(spec).getEncoded(); Base64.Encoder enc = Base64.getEncoder(); System.out.printf("salt: %s%n", enc.encodeToString(salt)); System.out.printf("hash: %s%n", enc.encodeToString(hash));
PBKDF2 takes a password, a random salt, and a cost parameter to compute the hash. The cost parameter controls the computational intensity of hashing, with higher costs resulting in slower hashing but stronger security.
To further enhance security, consider using a utility class like this one:
import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Arrays; import java.util.Base64; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; /** * Utility class for PBKDF2 password authentication */ public final class PasswordAuthentication { // Constants public static final String ID = "$"; public static final int DEFAULT_COST = 16; private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; private static final int SIZE = 128; private static final Pattern layout = Pattern.compile("\\$(\d\d?)\$(.{43})"); // Instance variables private final SecureRandom random; private final int cost; /** * Constructor with default cost */ public PasswordAuthentication() { this(DEFAULT_COST); } /** * Constructor with specified cost * * @param cost the exponential computational cost of hashing a password, 0 to 30 */ public PasswordAuthentication(int cost) { iterations(cost); // Validate cost this.cost = cost; this.random = new SecureRandom(); } private static int iterations(int cost) { if ((cost < 0) || (cost > 30)) { throw new IllegalArgumentException("cost: " + cost); } return 1 << cost; } /** * Hash a password for storage * * @return a secure authentication token to be stored for later authentication */ public String hash(char[] password) { byte[] salt = new byte[SIZE / 8]; random.nextBytes(salt); byte[] dk = pbkdf2(password, salt, 1 << cost); byte[] hash = new byte[salt.length + dk.length]; System.arraycopy(salt, 0, hash, 0, salt.length); System.arraycopy(dk, 0, hash, salt.length, dk.length); Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); return ID + cost + '$' + enc.encodeToString(hash); } /** * Authenticate with a password and a stored password token * * @return true if the password and token match */ public boolean authenticate(char[] password, String token) { Matcher m = layout.matcher(token); if (!m.matches()) { throw new IllegalArgumentException("Invalid token format"); } int iterations = iterations(Integer.parseInt(m.group(1))); byte[] hash = Base64.getUrlDecoder().decode(m.group(2)); byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8); byte[] check = pbkdf2(password, salt, iterations); int zero = 0; for (int idx = 0; idx < check.length; ++idx) { zero |= hash[salt.length + idx] ^ check[idx]; } return zero == 0; } private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) { KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE); try { SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM); return f.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex); } catch (InvalidKeySpecException ex) { throw new IllegalStateException("Invalid SecretKeyFactory", ex); } } }
This utility class provides methods for hashing passwords (hash) and authenticating users (authenticate). It uses a customizable computational cost parameter and incorporates a random salt for added protection. By utilizing this utility, you can securely store and verify passwords in your Java application.
The above is the detailed content of How to Securely Hash Passwords in Java Using PBKDF2?. For more information, please follow other related articles on the PHP Chinese website!