Accidentally committing secret keys, API tokens, private keys, or database credentials to Git remains one of the most common and dangerous mistakes in modern development. Once a secret enters the repository history, it can be exposed through public repositories, pull requests, or even old commits that get cloned by attackers. The best defense is a proactive, zero-trust local environment that scans every commit before it reaches the remote repository.
The most effective technical solution is building a custom Git pre-commit hook that uses Shannon Entropy to detect high-randomness strings typical of cryptographic material and blocks the commit automatically.
Where P(x_i) is the probability of occurrence of the ( i )-th character.
#!/usr/bin/env python3
import re
import subprocess
import sys
import math
from collections import Counter
def calculate_shannon_entropy(data: str) -> float:
"""Calculate the Shannon Entropy of a string to measure its randomness."""
if not data:
return 0.0
frequencies = Counter(data)
length = len(data)
entropy = 0.0
for count in frequencies.values():
probability = count / length
entropy -= probability * math.log2(probability)
return entropy
def scan_staged_diffs(entropy_threshold: float = 4.5, min_length: int = 24) -> bool:
"""Scan ONLY the actual staged hunks entering the git index."""
try:
result = subprocess.run(
["git", "diff", "--cached", "-U0", "--no-color"],
capture_output=True,
text=True,
check=True
)
except subprocess.CalledProcessError as e:
print(f"[-] Error executing git diff: {e}")
return False
current_file = "Unknown"
leaks_found = []
token_pattern = re.compile(r'[A-Za-z0-9+/=_-]{' + str(min_length) + r',}')
for line in result.stdout.splitlines():
if line.startswith("+++ b/"):
current_file = line[6:]
continue
if line.startswith("+") and not line.startswith("+++"):
added_content = line[1:].strip()
candidates = token_pattern.findall(added_content)
for candidate in candidates:
entropy = calculate_shannon_entropy(candidate)
if entropy > entropy_threshold:
leaks_found.append({
"file": current_file,
"string": candidate[:32] + "..." if len(candidate) > 32 else candidate,
"entropy": round(entropy, 2)
})
if leaks_found:
print("\n\033[91m🚨 [SECURITY] HARDWARE SHIELD: POTENTIAL CRYPTOGRAPHIC LEAK BLOCKED\033[0m")
print("=" * 75)
for leak in leaks_found:
print(f" 📍 File : {leak['file']}")
print(f" 🔒 String : {leak['string']}")
print(f" 📊 Entropy: {leak['entropy']} (Threshold: {entropy_threshold})")
print("-" * 75)
print("\n\033[93mAction Required:\033[0m Remove the secret, use environment variables, or update your config.")
return True
return False
if __name__ == "__main__":
if scan_staged_diffs():
sys.exit(1) # Block the commit
else:
print("\033[92m✅ Zero-Trust Scan Passed: No high-entropy anomalies found in staged changes.\033[0m")
sys.exit(0) chmod +x .git/hooks/pre-commit
