Private Key PEM Header Detection (Any Type) Regex for Go
/-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/What this pattern does
This page provides a well-structured, multi-part regular expression for matching private key pem header detection (any type), 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
// Private Key PEM Header Detection (Any Type)
// ReDoS-safe | RegexVault — Security > Secrets & Config
package validation
import "regexp"
var privateKeyPemHeaderDetectionAnyTypeRe = regexp.MustCompile(`-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----`)
func ValidatePrivateKeyPemHeaderDetectionAnyType(s string) bool {
return privateKeyPemHeaderDetectionAnyTypeRe.MatchString(s)
}
// Example
// fmt.Println(ValidatePrivateKeyPemHeaderDetectionAnyType("-----BEGIN PRIVATE KEY-----")) // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
-----BEGIN PRIVATE KEY----- | -----BEGIN CERTIFICATE----- |
-----BEGIN RSA PRIVATE KEY----- | -----BEGIN PUBLIC KEY----- |
-----BEGIN EC PRIVATE KEY----- | BEGIN RSA PRIVATE KEY |
-----BEGIN OPENSSH PRIVATE KEY----- | — |
-----BEGIN ENCRYPTED PRIVATE KEY----- | — |
When to use this pattern
This pattern is drawn from the Security > Secrets & Config 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
ENCRYPTED PRIVATE KEY is slightly less dangerous than plain PRIVATE KEY — but the passphrase is still crackable offline. Never treat encryption as a substitute for access control.
Technical Notes
Lightweight header-only scanner. More permissive than sec-pki-02 — useful as a first-pass trigger before more expensive full-block extraction. Matches any key type including PKCS#8 (PRIVATE KEY), PKCS#1 RSA (RSA PRIVATE KEY), SEC1 EC (EC PRIVATE KEY), and OpenSSH.
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