bcrypt Hash Regex for Go
/^\$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 Go. 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 Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.
Go Implementation
// bcrypt Hash
// ReDoS-safe | RegexVault — Security > Password Formats
package validation
import "regexp"
var bcryptHashRe = regexp.MustCompile(`^\$2[ayb]\$([0-2][0-9]|3[0-1])\$[./A-Za-z0-9]{53}$`)
func ValidateBcryptHash(s string) bool {
return bcryptHashRe.MatchString(s)
}
// Example
// fmt.Println(ValidateBcryptHash("$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW")) // trueTest 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 Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. 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