REGEXVAULTv2.0
Security/Certificates & PKI
Verified Safe

PEM Private Key Block Regex for PHP

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

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching pem private key block, ported and verified for PHP. 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 PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.

Php Implementation

Php
<?php
// PEM Private Key Block
// ReDoS-safe | RegexVault — Security > Certificates & PKI

define('PEM_PRIVATE_KEY_BLOCK_PATTERN', '/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----[\r\n]+(?:[A-Za-z0-9+\/=\r\n]{1,80}[\r\n]+)*-----END (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/');

function validate_pem_private_key_block(string $input): bool {
    return (bool) preg_match(PEM_PRIVATE_KEY_BLOCK_PATTERN, $input);
}

// Example
var_dump(validate_pem_private_key_block("-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgk=
-----END PRIVATE KEY-----")); // bool(true)

Test Cases

Matches (Valid)
Rejects (Invalid)
-----BEGIN PRIVATE KEY----- MIIEvAIBADANBgk= -----END PRIVATE KEY----------BEGIN CERTIFICATE----- data -----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA -----END RSA PRIVATE KEY----------BEGIN PRIVATE----- data -----END PRIVATE-----
-----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEA -----END OPENSSH 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 PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. 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

Private keys committed to Git are the most damaging security leak — they cannot be revoked retroactively from Git history without a full rebase/filter-branch. Use git-secrets pre-commit hook to prevent this.

Technical Notes

CRITICAL detection pattern. Key type headers: 'PRIVATE KEY' (PKCS#8, unencrypted), 'RSA PRIVATE KEY' (PKCS#1, legacy OpenSSL), 'EC PRIVATE KEY' (SEC1), 'OPENSSH PRIVATE KEY' (SSH private keys). Encrypted private keys have 'ENCRYPTED PRIVATE KEY' header.

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