scrypt Hash (passlib format) Regex for Python
/^\$scrypt\$ln=([0-9]+),r=([0-9]+),p=([0-9]+)\$([A-Za-z0-9+/]{16,64}(?:={0,2}))\$([A-Za-z0-9+/]{30,64}(?:={0,1}))$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching scrypt hash (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
# scrypt Hash (passlib format)
# ReDoS-safe | RegexVault — Security > Password Formats
import re
scrypt_hash_passlib_format_pattern = re.compile(r'^\$scrypt\$ln=([0-9]+),r=([0-9]+),p=([0-9]+)\$([A-Za-z0-9+/]{16,64}(?:={0,2}))\$([A-Za-z0-9+/]{30,64}(?:={0,1}))$')
def validate_scrypt_hash_passlib_format(value: str) -> bool:
return bool(scrypt_hash_passlib_format_pattern.fullmatch(value))
# Example
print(validate_scrypt_hash_passlib_format("$scrypt$ln=14,r=8,p=1$aM15816PilIJep0o$nFNh2CVHVjNldFVKDHDlm0248RZvVaR8")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
$scrypt$ln=14,r=8,p=1$aM15816PilIJep0o$nFNh2CVHVjNldFVKDHDlm0248RZvVaR8 | $scrypt$n=16384,r=8,p=1$aM15816PilIJep0o$nFNh2CVHVjNldFVKDHDlm0248RZvVaR8 |
| — | $bcrypt$ln=14,r=8,p=1$aM15816PilIJep0o$nFNh2CVHVjNldFVKDHDlm |
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
scrypt's memory requirement scales as N*r*128 bytes. With N=32768 and r=8, each hash requires 32 MiB of memory — this limits GPU parallelism for attackers. Do not reduce r below 8.
Technical Notes
Parameters: ln=log2(N) where N is the work factor, r=block size (8), p=parallelism (1). OWASP recommends N=32768 (ln=15), r=8, p=1 minimum. scrypt is memory-hard like Argon2, designed by Colin Percival. ln=14 = N=16384.
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