REGEXVAULTv2.0
Security/Password Formats
Verified Safe

bcrypt Hash Regex for Python

/^\$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 Python. 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 Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.

Python Implementation

Python
# bcrypt Hash
# ReDoS-safe | RegexVault — Security > Password Formats

import re

bcrypt_hash_pattern = re.compile(r'^\$2[ayb]\$([0-2][0-9]|3[0-1])\$[./A-Za-z0-9]{53}$')

def validate_bcrypt_hash(value: str) -> bool:
    return bool(bcrypt_hash_pattern.fullmatch(value))

# Example
print(validate_bcrypt_hash("$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 Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. 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