REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

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

/-----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 JavaScript. 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 JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.

Javascript Implementation

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

const privateKeyPemHeaderDetectionAnyTypeRegex = /-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/;

function validatePrivateKeyPemHeaderDetectionAnyType(input: string): boolean {
  return privateKeyPemHeaderDetectionAnyTypeRegex.test(input);
}

// Example
console.log(validatePrivateKeyPemHeaderDetectionAnyType("-----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 JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. 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