REGEXVAULTv2.0
Security/Secrets & Config
Verified Safe

Generic Secret Assignment in Code Regex for Python

/(?:password|passwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|encryption[_-]?key)(?:[\s]*[:=][\s]*)["']([^"'\s]{8,})["']/i

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching generic secret assignment in code, 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
# Generic Secret Assignment in Code
# ReDoS-safe | RegexVault — Security > Secrets & Config

import re

generic_secret_assignment_in_code_pattern = re.compile(r'(?:password|passwd|secret|token|api[_-]?key|auth[_-]?key|access[_-]?key|client[_-]?secret|private[_-]?key|encryption[_-]?key)(?:[\s]*[:=][\s]*)["']([^"'\s]{8,})["']')

def validate_generic_secret_assignment_in_code(value: str) -> bool:
    return bool(generic_secret_assignment_in_code_pattern.fullmatch(value))

# Example
print(validate_generic_secret_assignment_in_code("password = 'mySecretPassword123'"))  # True

Test Cases

Matches (Valid)
Rejects (Invalid)
password = 'mySecretPassword123'password = ''
api_key = "AIzaSyD-9tSrke72I6e0qOZV"api_key = variable_name
token: 'eyJhbGciOiJIUzI1NiJ9'// password might be here

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

Effective secret scanning requires both pattern matching AND entropy analysis. Simple dictionary words that match the pattern are likely placeholders. Tools like TruffleHog and GitLeaks combine regex with Shannon entropy scoring.

Technical Notes

Detection pattern for secret scanning in codebases and config files. The value capture group (1) should be examined for entropy and length. False positive rate is non-trivial — values like 'your_password_here' or 'changeme' are common placeholders. Use entropy scoring alongside pattern matching.

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