REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

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

/-----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 Python. 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 Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.

Python Implementation

Python
# Private Key PEM Header Detection (Any Type)
# ReDoS-safe | RegexVault — Security > Secrets & Config

import re

private_key_pem_header_detection_any_type_pattern = re.compile(r'-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----')

def validate_private_key_pem_header_detection_any_type(value: str) -> bool:
    return bool(private_key_pem_header_detection_any_type_pattern.fullmatch(value))

# Example
print(validate_private_key_pem_header_detection_any_type("-----BEGIN PRIVATE KEY-----"))  # 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 Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. 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