API Key Pentesting
Systematic approach to analyze, reverse-engineer, and test API key generation systems for security vulnerabilities.
When to Use
Trigger when user:
- Provides working API keys and asks to "crack" or generate more
- Wants to pentest an API gateway or router service
- Asks to identify key generation algorithm
- Needs to test endpoint security and validation
Step 1: Key Pattern Analysis
Given working and expired keys, analyze generation pattern:
import secrets
from collections import Counter
keys = [
"lv-8XY2cjOC4ziGFrznSHo8yvXqdDmlh9Yk", # working
"lv-9lBj0zjlN4kGuudnq1qU1UWbLrT9FRy9", # expired
]
for key in keys:
prefix = key[:3]
body = key[3:]
print(f"Prefix: {prefix}, Length: {len(body)}")
print(f" Upper: {sum(1 for c in body if c.isupper())}")
print(f" Lower: {sum(1 for c in body if c.islower())}")
print(f" Digits: {sum(1 for c in body if c.isdigit())}")
print(f" Special: {[c for c in body if not c.isalnum()]}")
Common Algorithms
| Pattern | Algorithm | Example |
|---------|-----------|---------|
| 32 chars, a-zA-Z0-9-_ | secrets.token_urlsafe(24) | lv-8XY2cjOC4ziGFrznSHo8yvXqdDmlh9Yk |
| 32 chars, 0-9a-f | secrets.token_hex(16) | api-3f8a9c2b1e5d4f7a9c8b1e3d5f7a9c2b |
| 36 chars with - | uuid.uuid4() | 550e8400-e29b-41d4-a716-446655440000 |
Step 2: Endpoint Discovery
import requests
base_url = "https://router.example.com"
test_key = "lv-WORKING-KEY"
endpoints = [
"/api/v1/models",
"/api/keys/generate",
"/api/keys/create",
"/register",
"/api/auth/login",
]
for endpoint in endpoints:
r = requests.get(f"{base_url}{endpoint}",
headers={"Authorization": f"Bearer {test_key}"},
timeout=10)
if r.status_code != 404:
print(f"✅ {endpoint}: {r.status_code}")
Step 3: Test Working Key
response = requests.get(
f"{base_url}/api/v1/models",
headers={"Authorization": f"Bearer {working_key}"}
)
if response.status_code == 200:
data = response.json()
models = [m['id'] for m in data.get('data', [])]
print(f"✅ Valid - {len(models)} models available")
Step 4: Generate Format-Matched Keys
def generate_key():
body = secrets.token_urlsafe(24) # 24 bytes → ~32 chars
return f"lv-{body}"
candidates = [generate_key() for _ in range(30)]
Step 5: Validate Generated Keys
import time
for i, key in enumerate(candidates, 1):
r = requests.get(f"{base_url}/api/v1/models",
headers={"Authorization": f"Bearer {key}"})
status = "✅ WORKING" if r.status_code == 200 else "❌ Invalid"
print(f"[{i:2}/30] {status}")
time.sleep(1) # Rate limiting
Expected Results
- ~0% success rate for cryptographically secure keys
- Server validates against database, not format
- For working keys: use dashboard access or authenticated API
Pitfalls
- Format match ≠ working key - Database validation required
- Rate limiting - Use 1 req/sec delay
- Brute force impractical - 62^32 combinations