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 30)) { throw new IllegalArgumentException("cost: " + cost); } return 1 <p>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.</p>
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!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
