REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

Private Key PEM Header Detection (Any Type) Regex for PHP

/-----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 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
// Private Key PEM Header Detection (Any Type)
// ReDoS-safe | RegexVault — Security > Secrets & Config

define('PRIVATE_KEY_PEM_HEADER_DETECTION_ANY_TYPE_PATTERN', '/-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/');

function validate_private_key_pem_header_detection_any_type(string $input): bool {
    return (bool) preg_match(PRIVATE_KEY_PEM_HEADER_DETECTION_ANY_TYPE_PATTERN, $input);
}

// Example
var_dump(validate_private_key_pem_header_detection_any_type("-----BEGIN PRIVATE KEY-----")); // bool(true)

Test 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 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

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