Detect Private Keys in Code

Identify and redact RSA, EC, and Ed25519 private keys embedded in source code, configuration files, and scripts. Prevent cryptographic key leaks before sharing code.

Secret Types

Detailed Explanation

Detecting Private Keys in Code

Private keys are the most critical secrets in any cryptographic system. Unlike API keys that can be rotated in seconds, a compromised private key may require revoking and reissuing certificates, updating all dependent systems, and notifying affected parties.

Private Key Formats

Private keys are typically stored in PEM format with distinctive header and footer markers:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA0Z3VS5JJcds3xfn/ygWyF8PbnGy...
-----END RSA PRIVATE KEY-----

-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIBkg4LVWM9buwRo+RzDaq4DLNIv+xPH15cN...
-----END EC PRIVATE KEY-----

-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAA...
-----END OPENSSH PRIVATE KEY-----

Detection Approach

The PEM format makes private keys easy to detect with pattern matching:

-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----

This regex matches all standard private key types: RSA, DSA, EC, Ed25519, and OpenSSH formats. The key content between the markers (Base64-encoded binary data) is captured as part of the match and fully redacted.

Where Private Keys Appear

  • Repository files — Accidentally committed .pem, .key, or inline in code
  • Docker images — Baked into container layers during build
  • CI/CD configurations — Stored as pipeline variables and printed in logs
  • Configuration management — Ansible vaults, Terraform state, Kubernetes secrets (base64-encoded, not encrypted)
  • Stack Overflow questions — Developers posting code samples with real keys

Redaction Output

# Before
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA0Z3VS5JJcds3xfn/ygWyF8PbnGy...
(multiple lines of Base64 data)
-----END RSA PRIVATE KEY-----

# After
[REDACTED_PRIVATE_KEY]

The entire key block is replaced with a single placeholder, ensuring no partial key data remains visible.

Use Case

A developer is creating a tutorial about TLS certificate generation and wants to include real terminal output showing the key generation process. Before publishing, they run the content through the Secret Redactor to replace all private key blocks with safe placeholders while keeping the certificate (public) portions intact for the tutorial.

Try It — Secret Redactor

Open full tool