Java Password Hashing

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 243 of 306

Java password hashing turns a password into a fixed value that you can store and check later, without ever storing the password itself. If your database leaks, attackers get only the hashes, and a good password hash makes guessing the original passwords slow and expensive.

In this lesson you will see why a plain SHA-256 hash is not enough, then build proper password storage with a random salt and PBKDF2 using only the standard JDK. The final example is a complete password service with registration, login and automatic hash upgrades. It uses ideas from Java Security and Java Secure Coding.


Hashing vs Encryption for Passwords

Encryption can be reversed with a key. Hashing cannot be reversed at all. For passwords you want hashing, because the server never needs the original password back; it only needs to check whether a login attempt produces the same hash.

ApproachReversible?Safe for passwords?Why
Plain textYesNoAnyone who reads the database sees every password
Encryption (AES)Yes, with the keyNoA stolen key reveals every password
Fast hash (SHA-256)NoNoToo fast; equal passwords give equal hashes
Salted fast hashNoWeakUnique per user, but still billions of guesses per second on a GPU
Password hash (PBKDF2, bcrypt, scrypt, Argon2)NoYesSalted and deliberately slow

Why a Plain SHA-256 Hash Is Not Enough

SHA-256 is a great general hash, but it was designed to be fast. That is exactly what an attacker wants when guessing passwords. It also gives the same output for the same input, so two users with the same password have the same stored value.

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;

public class PlainHashProblem {
    static String sha256(String text) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8)));
    }

    public static void main(String[] args) throws Exception {
        // Two users who picked the same password get the same stored value
        System.out.println("asha : " + sha256("password123"));
        System.out.println("ravi : " + sha256("password123"));

        // A plain hash is also extremely fast to compute
        long start = System.nanoTime();
        for (int attempt = 0; attempt < 1_000_000; attempt++) {
            sha256("guess" + attempt);
        }
        long millis = (System.nanoTime() - start) / 1_000_000;
        System.out.println("1,000,000 guesses took about " + (millis < 2000 ? "1-2 seconds" : millis / 1000 + " seconds"));
    }
}

Output (the timing depends on your computer):

asha : ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
ravi : ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
1,000,000 guesses took about 1-2 seconds

How it works:

  • sha256 hashes the UTF-8 bytes of the text and prints them as hex with HexFormat.
  • Both users get exactly the same 64-character value, so cracking one password cracks both. Precomputed tables of common password hashes (rainbow tables) also work directly against such values.
  • A single CPU core computes about a million SHA-256 hashes in a second or two. A GPU computes billions per second.

Adding a Random Salt

A salt is a random value created for each password and stored next to its hash. Because every user has a different salt, equal passwords produce different hashes, and precomputed tables become useless. The salt is not secret.

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

public class SaltDemo {
    private static final SecureRandom RANDOM = new SecureRandom();

    static byte[] newSalt() {
        byte[] salt = new byte[16];          // 128 bits
        RANDOM.nextBytes(salt);
        return salt;
    }

    static byte[] saltedSha256(String password, byte[] salt) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(salt);
        return digest.digest(password.getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args) throws Exception {
        byte[] ashaSalt = newSalt();
        byte[] raviSalt = newSalt();
        byte[] ashaHash = saltedSha256("password123", ashaSalt);
        byte[] raviHash = saltedSha256("password123", raviSalt);

        Base64.Encoder base64 = Base64.getEncoder();
        System.out.println("Salt length: " + ashaSalt.length + " bytes -> " + base64.encodeToString(ashaSalt).length() + " Base64 chars");
        System.out.println("Same password, same hash? " + MessageDigest.isEqual(ashaHash, raviHash));
        System.out.println("Recompute with the stored salt matches? "
                + MessageDigest.isEqual(ashaHash, saltedSha256("password123", ashaSalt)));
    }
}

Output:

Salt length: 16 bytes -> 24 Base64 chars
Same password, same hash? false
Recompute with the stored salt matches? true

How it works:

  • SecureRandom creates 16 unpredictable bytes for each user. Never use java.util.Random for this, because its output can be predicted.
  • digest.update(salt) feeds the salt in before the password, so the result depends on both.
  • Even with the same password, Asha and Ravi have different hashes. To check a login, the server reads the stored salt and repeats the calculation.
  • MessageDigest.isEqual compares two byte arrays in constant time, so the time taken does not reveal how many bytes matched.

Note: Salting fixes the "equal passwords" problem but not the speed problem. You still need a slow algorithm, which is what PBKDF2 adds.


Java Password Hashing With PBKDF2

PBKDF2 (Password-Based Key Derivation Function 2) repeats an HMAC thousands of times. The JDK includes it as PBKDF2WithHmacSHA256, available through SecretKeyFactory. You choose the salt, the number of iterations and the output length.

PBEKeySpec spec = new PBEKeySpec(char[] password, byte[] salt, int iterations, int keyLengthBits);
byte[] hash = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
ParameterRecommended valuePurpose
passwordchar[]Can be wiped after use, unlike String
salt16 random bytesUnique per password
iterations600,000 for PBKDF2-HMAC-SHA256 (OWASP guidance)Makes every guess slow
keyLengthBits256Matches the SHA-256 output size
import java.security.spec.KeySpec;
import java.util.HexFormat;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Pbkdf2Basics {
    public static void main(String[] args) throws Exception {
        char[] password = "password123".toCharArray();
        // A fixed salt is used ONLY so this demo prints the same hash every time
        byte[] salt = HexFormat.of().parseHex("8f3a1c5e7b9d2f4a6c8e0b1d3f5a7c9e");
        int iterations = 600_000;
        int keyLengthBits = 256;

        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLengthBits);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

        long start = System.nanoTime();
        byte[] hash = factory.generateSecret(spec).getEncoded();
        long millis = (System.nanoTime() - start) / 1_000_000;
        spec.clearPassword();                // wipe the copy held by the spec

        System.out.println("Hash bytes : " + hash.length);
        System.out.println("Hash (hex) : " + HexFormat.of().formatHex(hash));
        System.out.println("Slow enough: " + (millis >= 50 ? "yes" : "no") + " (one hash takes tens to hundreds of ms)");
    }
}

Output:

Hash bytes : 32
Hash (hex) : 86481430f88250c89715615655c1a59b2b863e40575bfe0882b02e3136ca2985
Slow enough: yes (one hash takes tens to hundreds of ms)

How it works:

  • PBEKeySpec bundles the password, salt, iteration count and desired length.
  • generateSecret runs HMAC-SHA256 600,000 times and returns a 32-byte (256-bit) result.
  • One hash now takes a noticeable fraction of a second. A real user logs in once and does not notice, but an attacker trying millions of guesses is slowed down by the same factor.
  • spec.clearPassword() wipes the spec's internal copy of the password.

Storing the Salt, Iterations and Hash Together

To verify a password later, you need the same salt and the same iteration count. Store everything in one string, in a format such as algorithm$iterations$salt$hash. This also lets you raise the iteration count in the future without breaking old accounts.

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class StoredFormat {
    private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
    private static final int ITERATIONS = 600_000;
    private static final SecureRandom RANDOM = new SecureRandom();

    static byte[] pbkdf2(char[] password, byte[] salt, int iterations) throws Exception {
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, 256);
        try {
            return SecretKeyFactory.getInstance(ALGORITHM).generateSecret(spec).getEncoded();
        } finally {
            spec.clearPassword();
        }
    }

    // Format: pbkdf2_sha256$<iterations>$<salt>$<hash>
    static String hashPassword(char[] password) throws Exception {
        byte[] salt = new byte[16];
        RANDOM.nextBytes(salt);
        byte[] hash = pbkdf2(password, salt, ITERATIONS);
        Base64.Encoder base64 = Base64.getEncoder().withoutPadding();
        return "pbkdf2_sha256$" + ITERATIONS + "$" + base64.encodeToString(salt) + "$" + base64.encodeToString(hash);
    }

    static boolean verifyPassword(char[] attempt, String stored) throws Exception {
        String[] parts = stored.split("\\$");
        int iterations = Integer.parseInt(parts[1]);
        byte[] salt = Base64.getDecoder().decode(parts[2]);
        byte[] expectedHash = Base64.getDecoder().decode(parts[3]);
        byte[] actualHash = pbkdf2(attempt, salt, iterations);
        return MessageDigest.isEqual(expectedHash, actualHash);   // constant-time comparison
    }

    public static void main(String[] args) throws Exception {
        String stored = hashPassword("Correct-Horse-42".toCharArray());
        String[] parts = stored.split("\\$");
        System.out.println("Stored parts: " + parts[0] + " | " + parts[1] + " | salt "
                + parts[2].length() + " chars | hash " + parts[3].length() + " chars");
        System.out.println("Correct password: " + verifyPassword("Correct-Horse-42".toCharArray(), stored));
        System.out.println("Wrong password  : " + verifyPassword("correct-horse-42".toCharArray(), stored));
        System.out.println("Hash again, same string? " + stored.equals(hashPassword("Correct-Horse-42".toCharArray())));
    }
}

Output:

Stored parts: pbkdf2_sha256 | 600000 | salt 22 chars | hash 43 chars
Correct password: true
Wrong password  : false
Hash again, same string? false

How it works:

  • hashPassword creates a fresh salt, runs PBKDF2 and joins the four parts with $. Base64 without padding keeps the string short: 16 salt bytes become 22 characters, and 32 hash bytes become 43 characters.
  • verifyPassword splits the stored string, decodes the salt and expected hash, and runs PBKDF2 again with the stored iteration count.
  • Passwords are case sensitive, so correct-horse-42 fails.
  • Hashing the same password twice gives two different strings because of the random salt. That is why you always verify with the stored salt instead of comparing two new hashes.

Note: Libraries offer other strong password hashes. Spring Security has BCryptPasswordEncoder and Argon2PasswordEncoder, and Argon2id is the first choice in current OWASP guidance. PBKDF2 is the best option when you must use only the JDK or need FIPS-approved algorithms.


Real-World Example: A Password Service With Hash Upgrades

This class works like the password part of a real login system. It enforces a minimum password length, wipes passwords after use, protects against username discovery through timing, and upgrades old hashes to a higher iteration count when users log in.

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class PasswordService {
    private static final String PREFIX = "pbkdf2_sha256";
    private static final int SALT_BYTES = 16;
    private static final int HASH_BITS = 256;
    private static final int MIN_LENGTH = 12;

    private final int currentIterations;
    private final SecureRandom random = new SecureRandom();
    private final Map<String, String> userStore = new HashMap<>();   // stands in for a database table
    // Hash of a random password, used to keep timing equal for unknown usernames
    private final String dummyHash;

    PasswordService(int currentIterations) throws Exception {
        this.currentIterations = currentIterations;
        this.dummyHash = hash("unused-dummy-password".toCharArray());
    }

    void register(String username, char[] password) throws Exception {
        try {
            if (password.length < MIN_LENGTH) {
                throw new IllegalArgumentException("Password must be at least " + MIN_LENGTH + " characters");
            }
            userStore.put(username, hash(password));
            System.out.println("Registered " + username);
        } finally {
            Arrays.fill(password, '\0');
        }
    }

    boolean login(String username, char[] password) throws Exception {
        try {
            String stored = userStore.get(username);
            // Always run one PBKDF2 calculation, even for unknown users
            boolean matches = verify(password, stored != null ? stored : dummyHash) && stored != null;
            if (matches && needsRehash(stored)) {
                userStore.put(username, hash(password));        // upgrade silently on login
                System.out.println("  (upgraded hash for " + username + " to " + currentIterations + " iterations)");
            }
            return matches;
        } finally {
            Arrays.fill(password, '\0');
        }
    }

    String storedHash(String username) {
        return userStore.get(username);
    }

    private String hash(char[] password) throws Exception {
        byte[] salt = new byte[SALT_BYTES];
        random.nextBytes(salt);
        byte[] hash = pbkdf2(password, salt, currentIterations);
        Base64.Encoder encoder = Base64.getEncoder().withoutPadding();
        return String.join("$", PREFIX, String.valueOf(currentIterations),
                encoder.encodeToString(salt), encoder.encodeToString(hash));
    }

    private boolean verify(char[] password, String stored) throws Exception {
        String[] parts = stored.split("\\$");
        if (parts.length != 4 || !parts[0].equals(PREFIX)) {
            return false;
        }
        byte[] salt = Base64.getDecoder().decode(parts[2]);
        byte[] expected = Base64.getDecoder().decode(parts[3]);
        return MessageDigest.isEqual(expected, pbkdf2(password, salt, Integer.parseInt(parts[1])));
    }

    private boolean needsRehash(String stored) {
        return Integer.parseInt(stored.split("\\$")[1]) < currentIterations;
    }

    private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) throws Exception {
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, HASH_BITS);
        try {
            return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
        } finally {
            spec.clearPassword();
        }
    }

    public static void main(String[] args) throws Exception {
        // Version 1 of the app used fewer iterations
        PasswordService oldService = new PasswordService(100_000);
        oldService.register("asha", "Lotus-Chennai-2026".toCharArray());
        String oldHash = oldService.storedHash("asha");

        // Version 2 raises the cost; existing hashes are carried over
        PasswordService service = new PasswordService(600_000);
        service.userStore.put("asha", oldHash);
        service.register("ravi", "Blue-Kettle-Morning".toCharArray());

        try {
            service.register("kumar", "short".toCharArray());
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected kumar: " + e.getMessage());
        }

        System.out.println("asha, old hash iterations: " + service.storedHash("asha").split("\\$")[1]);
        System.out.println("asha login (correct): " + service.login("asha", "Lotus-Chennai-2026".toCharArray()));
        System.out.println("asha, new hash iterations: " + service.storedHash("asha").split("\\$")[1]);
        System.out.println("ravi login (wrong)  : " + service.login("ravi", "blue-kettle-morning".toCharArray()));
        System.out.println("ghost login         : " + service.login("ghost", "anything-at-all".toCharArray()));
    }
}

Output:

Registered asha
Registered ravi
Rejected kumar: Password must be at least 12 characters
asha, old hash iterations: 100000
  (upgraded hash for asha to 600000 iterations)
asha login (correct): true
asha, new hash iterations: 600000
ravi login (wrong)  : false
ghost login         : false

How it works:

  1. Registration. register rejects passwords shorter than 12 characters, hashes the rest and stores the result. The finally block wipes the char[] even when an exception is thrown.
  2. Old hashes. Asha registered with an older version of the app that used 100,000 iterations. Her stored string still says 100000, so the service knows how to verify it.
  3. Login and upgrade. When Asha logs in with the correct password, needsRehash sees that 100,000 is lower than the current 600,000. The service hashes her password again with a new salt and saves the stronger hash. This is the only moment the server has the plain password, so upgrades can only happen at login.
  4. Wrong password. Ravi's attempt differs only in letter case, so PBKDF2 produces a different hash and MessageDigest.isEqual returns false.
  5. Unknown users. For ghost, there is no stored hash, but the service still runs PBKDF2 against dummyHash. Without this, a login for an unknown name would return instantly, and an attacker could time responses to find which usernames exist.
  6. Constant-time checks. Every comparison uses MessageDigest.isEqual, and the result for an unknown user is forced to false with && stored != null.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Password Hashing and get answers drawn from it.

Signed-in readers only.