macOS Keychain

Password store built into macOS. Scripts can keep API keys there instead of in files or the shell profile and read them with the security command.

I keep API keys for my scripts in the macOS Keychain, not in an environment variable or a file. The Safari Bookmark Sorter reads its key for the Claude API from there.

Commands

Store a key. The command asks for it twice without showing it, so it ends up neither in the shell history nor in a file:

security add-generic-password -a "$USER" -s anthropic-api-key -w

Replace an existing entry (without -U the command fails if the entry exists):

security add-generic-password -U -a "$USER" -s anthropic-api-key -w

Check that the entry exists without showing the key:

security find-generic-password -s anthropic-api-key >/dev/null && echo "key present"

Show only the start and the length, for example to spot a truncated key:

security find-generic-password -s anthropic-api-key -w | awk '{print substr($0,1,13), "…", length($0), "characters"}'

Read the key in plain text. Scripts use this; in the terminal it shows the key on screen:

security find-generic-password -s anthropic-api-key -w

List the names of all entries with api-key in their name, without the keys:

security dump-keychain | sed -n 's/.*"svce"<blob>="\(.*api-key.*\)"/\1/p' | sort -u

Delete an entry:

security delete-generic-password -s anthropic-api-key-other-project

Conventions

  • One entry per project, named after a common pattern such as anthropic-api-key-<project>. Listing only works with a shared pattern, the API console then shows usage per project, and a leaked key can be revoked on its own.
  • The first time a script reads an entry, macOS asks for permission. "Always Allow" stops the question.
  • The Keychain Access app finds the entries when you search for "api-key". The newer Passwords app usually does not show them.

More on this

Used in
  • RSS News with n8n and OpenRouter Guide: n8n reads security notices, a language model rates and rewrites them, and a restricted SSH script commits them to the Git repository of a static site.
  • Safari Bookmark Sorter Python script that sorts Safari bookmarks into folders with Claude Haiku and hands the result to Safari as an import file, so iCloud syncs it.
Mentioned in
  • Claude API Anthropic's programming interface to the Claude models. Billed separately from a claude.ai subscription, with keys from the Claude Console.

Show in the graph view →