REGEXVAULTv2.0
Security/Password Formats
Verified Safe

bcrypt Hash Regex for Java

/^\$2[ayb]\$([0-2][0-9]|3[0-1])\$[./A-Za-z0-9]{53}$/

What this pattern does

This page provides a well-structured, multi-part regular expression for matching bcrypt hash, ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.

Java Implementation

Java
// bcrypt Hash
// ReDoS-safe | RegexVault — Security > Password Formats

import java.util.regex.Pattern;

public class BcryptHashValidator {
    private static final Pattern PATTERN =
        Pattern.compile("^\\$2[ayb]\\$([0-2][0-9]|3[0-1])\\$[./A-Za-z0-9]{53}$");

    public static boolean validate(String input) {
        return PATTERN.matcher(input).matches();
    }

    // Example
    public static void main(String[] args) {
        System.out.println(validate("$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW")); // true
    }
}

Test Cases

Matches (Valid)
Rejects (Invalid)
$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW$2b$12$short
$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy$2c$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31l
$1$N9qo8uLO$ickgx2ZMRZoMyeIjZAgcfl

When to use this pattern

This pattern is drawn from the Security > Password Formats category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

bcrypt truncates passwords at 72 bytes — passwords longer than 72 characters are equally secure but this surprises developers. Use a pre-hashing step (HMAC) if you need to support passwords longer than 72 bytes.

Technical Notes

Structure: $2a/2b/2y$ + cost (4-31) + $ + 22-char salt + 31-char hash (in a modified base64 alphabet using ./A-Za-z0-9). $2b is the canonical prefix; $2a is legacy (PHP), $2y is PHP 5.3.7+. Cost of 10-12 is standard; use 12+ for new systems.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern