REGEXVAULTv2.0
Security/Certificates & PKI
Verified Safe

SSH Private Key (OpenSSH Format) Regex for Go

/-----BEGIN OPENSSH PRIVATE KEY-----[\r\n]+(?:[A-Za-z0-9+/=\r\n]{1,80}[\r\n]+)*-----END OPENSSH PRIVATE KEY-----/

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching ssh private key (openssh format), 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

Go
// SSH Private Key (OpenSSH Format)
// ReDoS-safe | RegexVault — Security > Certificates & PKI

package validation

import "regexp"

var sshPrivateKeyOpensshFormatRe = regexp.MustCompile(`-----BEGIN OPENSSH PRIVATE KEY-----[\r\n]+(?:[A-Za-z0-9+/=\r\n]{1,80}[\r\n]+)*-----END OPENSSH PRIVATE KEY-----`)

func ValidateSshPrivateKeyOpensshFormat(s string) bool {
    return sshPrivateKeyOpensshFormatRe.MatchString(s)
}

// Example
// fmt.Println(ValidateSshPrivateKeyOpensshFormat("-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAAAAAA
-----END OPENSSH PRIVATE KEY-----")) // true

Test Cases

Matches (Valid)
Rejects (Invalid)
-----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAAAAAA -----END OPENSSH PRIVATE KEY----------BEGIN RSA PRIVATE KEY----- data -----END RSA PRIVATE KEY-----

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

Even a passphrase-protected SSH private key is dangerous if exposed — offline passphrase cracking via john/hashcat is feasible for weak passphrases. Prefer hardware security keys (FIDO2/sk-ssh-ed25519) that cannot be extracted.

Technical Notes

OpenSSH private key format (openssh-key-v1) is the default since OpenSSH 6.5 (2014). Unlike PEM RSA keys, this format includes key type metadata and may be passphrase-protected. The base64 payload includes the key type, public key, and encrypted private key.

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