macOS Keychain

by Roman Zolotarev

You can store arbitrary keys or tokens in the keychain. This solution works on Mac only, but it works out of the box on any Mac.

security for rescue

security is a built-in command line interface to keychains and Security framework. To add a password to default keychain run:

security add-generic-password -a ${USER} -s NAME -w

You have to specify your account name with -a and service name with -s. If you put -w at the end of the command you will be prompted to enter the password.

To retrieve password use:

security find-generic-password -a ${USER} -s NAME -w

You can delete the password anytime:

security delete-generic-password -a ${USER} -s NAME

Use with GitHub personal access token

Let’s use GitHub as an example. Add these functions to your ~/.bashrc

function get_github_personal_access_token () {
  local token
  token=$(curl -s \
      -H "X-GitHub-OTP: ${1}" \
      -u "${USER}" \
      -d "{\"scopes\": [\"admin:public_key\"], \"note\": \"$(hostname)-$(date +%s)\"}" \
      | jq -r .token)
  security delete-generic-password -a "${USER}" -s GitHub
  security add-generic-password -a "${USER}" -s GitHub -w "$token"

function add_ssh_key_to_github () {
  curl -s \
    -H "Authorization: token $(security find-generic-password -a "${USER}" -s GitHub -w)" \
    -d "{\"title\": \"$(date +%s)\", \"key\": \"$(cat "$1")\"}"

function list_github_ssh_keys () {
  curl -s \
    -H "Authorization: token $(security find-generic-password -a "${USER}" -s GitHub -w)" \
    | jq 'map({title: .title, key:.key})'

Then call get_github_personal_access_token function with GitHub OTP code as an argument. Assuming you have enabled two-factor authentication for your GitHub account. E.g.

get_github_personal_access_token XXXXXX

Enter your GitHub password and security will add the new GitHub access token to your keychain.

Generate your SSH key pair first. To add your public SSH key run this command:

add_ssh_key_to_github ~/.ssh/

Later you can list your SSH keys associated with your GitHub account.


To learn more: man security.

Illustration: macOS Keychain