PBKDF2 Hash (Django / passlib format) Regex for Python
/^pbkdf2_sha(256|512)\$([0-9]+)\$([A-Za-z0-9+/=]{1,32})\$([A-Za-z0-9+/=]{43,86})$/What this pattern does
This page provides a well-structured, multi-part regular expression for matching pbkdf2 hash (django / passlib format), 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
# PBKDF2 Hash (Django / passlib format)
# ReDoS-safe | RegexVault — Security > Password Formats
import re
pbkdf2_hash_django_passlib_format_pattern = re.compile(r'^pbkdf2_sha(256|512)\$([0-9]+)\$([A-Za-z0-9+/=]{1,32})\$([A-Za-z0-9+/=]{43,86})$')
def validate_pbkdf2_hash_django_passlib_format(value: str) -> bool:
return bool(pbkdf2_hash_django_passlib_format_pattern.fullmatch(value))
# Example
print(validate_pbkdf2_hash_django_passlib_format("pbkdf2_sha256$390000$abcdefghijklmnop$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN01234567890=")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
pbkdf2_sha256$390000$abcdefghijklmnop$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN01234567890= | pbkdf2_sha256$390000$short$hash |
| — | pbkdf2_md5$390000$abcdefghijklmnop$hash |
| — | pbkdf2_sha256$ABC$abcdefghijklmnop$hash |
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
The iteration count is the key security parameter. Old hashes with iteration counts below 100000 are vulnerable to GPU cracking. Migrate hashes to higher iteration counts by rehashing on successful login.
Technical Notes
Format: algorithm + $ + iterations + $ + salt (base64) + $ + hash (base64). Django default uses sha256 with 390000 iterations (Django 4.2). NIST SP 800-63b recommends at least 10000 iterations — modern systems should use much higher. SHA-512 is preferred over SHA-256.
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