PEM Certificate Block Regex for Go
/-----BEGIN CERTIFICATE-----[\r\n]+(?:[A-Za-z0-9+/=\r\n]{1,80}[\r\n]+)*-----END CERTIFICATE-----/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching pem certificate block, 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
// PEM Certificate Block
// ReDoS-safe | RegexVault — Security > Certificates & PKI
package validation
import "regexp"
var pemCertificateBlockRe = regexp.MustCompile(`-----BEGIN CERTIFICATE-----[\r\n]+(?:[A-Za-z0-9+/=\r\n]{1,80}[\r\n]+)*-----END CERTIFICATE-----`)
func ValidatePemCertificateBlock(s string) bool {
return pemCertificateBlockRe.MatchString(s)
}
// Example
// fmt.Println(ValidatePemCertificateBlock("-----BEGIN CERTIFICATE-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
-----END CERTIFICATE-----")) // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
-----BEGIN CERTIFICATE-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
-----END CERTIFICATE----- | BEGIN CERTIFICATE |
| — | -----BEGIN CERT-----
data
-----END CERT----- |
| — | -----BEGIN CERTIFICATE-----data-----END CERTIFICATE----- |
When to use this pattern
This pattern is drawn from the Security > Certificates & PKI 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
Never confuse a certificate (public) with a private key (secret). A certificate can be safely shared — it is designed to be public. Misclassifying a certificate as sensitive and hiding it can cause trust chain issues.
Technical Notes
PEM format: base64-encoded DER certificate wrapped in BEGIN/END markers. Lines are max 76 characters in the standard. Use for detecting certificates in config files, code, or traffic. Parse with a proper X.509 library to extract subject, issuer, validity, and SANs.
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