A regex to catch API keys before pasting into an AI — and why it’s never enough
Give me one regex that catches most API keys so I can warn myself before pasting logs into an AI chat.
One regex that catches the common prefixed formats:
\b(sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36,}|xox[abprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[sr]k_(live|test)_[A-Za-z0-9]{16,}|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})\b
That covers OpenAI/Anthropic-style sk-…, AWS access keys, GitHub tokens, Slack tokens, Google API keys, Stripe keys and JWTs.
Now the honest part — why this is a floor, not a solution:
- Unprefixed secrets. Database passwords, most SaaS API keys, and anything in
Authorization: Basic …have no recognisable prefix. You need context rules (password=,token:) and those have false positives. - Personal data isn’t a pattern. Names, addresses, a customer’s health question in a support ticket — no regex sees those. A small on-device NER model helps; a human skim helps more.
- Paths leak identity.
/Users/jane.doe/…in a stack trace tells everyone who you are. - The paste is not the only exit. Screenshots, browser extensions, and coding agents reading your
.envall bypass the clipboard.
So: use the regex as an automatic first line, add context rules and a preview step, and treat “I checked it with a regex” as “I closed one door”.
Does it catch sk-ant-… keys?
Yes — sk-ant-api03-… starts with sk- followed by allowed characters, so the first alternative matches the whole key. If you want to label it as Anthropic specifically, add sk-ant-[A-Za-z0-9_-]{20,} as its own alternative before the generic sk- one.
Comments (0)
No comments yet.
Sign in to comment.