How to Securely Hash Passwords in Java Using PBKDF2?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...
