REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

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

/-----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 Java. 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 Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.

Java Implementation

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

import java.util.regex.Pattern;

public class PrivateKeyPemHeaderDetectionAnyTypeValidator {
    private static final Pattern PATTERN =
        Pattern.compile("-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----");

    public static boolean validate(String input) {
        return PATTERN.matcher(input).matches();
    }

    // Example
    public static void main(String[] args) {
        System.out.println(validate("-----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 Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. 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