Adding your ssh key password to MacOS Keychain

One really nice feature of MacOS is the integration of ssh keys with the OS keychain. This allows you to put a password on your ssh private key(s) that will unlock when you log in. Using this feature, combined with the ssh agent, and you can have a password protected ssh key, and not have to store it on any remote machines or enter the password every time you use it.

First, you generate your key(s) with ssh-keygen as you normally would (if you don’t understand what that is, then stop now, and go learn about the basics of SSH, then come back here). Once you have the key with the cipher of your choice, you need to add it to the MacOS keychain using the ssh-add command. Apple has added two custom options to the command that allow it to interact with the keychain: --apple-load-keychain and --apple-use-keychain. In previous versions, these were -A and -K, but as of Monterey, they have deprecated them, and prefer the long names.

To add a key to the keychain:

ssh-add --apple-use-keychain .ssh/id_rsa

It will prompt you for the password you assigned to the key, and store it in the keychain. Then, when you log in to the OS, it will unlock the key for you so you don’t have to type its password anymore. To make sure ssh honors this, create a file called config in your .ssh folder and add at a minimum this lines:

# This is a MacOS only option that looks for passwords for the keys
# in the keychain.  Ignore if it is an unknown option.
IgnoreUnknown UseKeyChain
UseKeychain yes 

The IgnoreUnknown option is a function of the ssh config system to ignore options that the version you are running doesn’t know about. That way you can create a portable config file that you can use on other platforms, and it will not complain about UseKeychain if it is not a valid option.

If you plan to use the ssh agent, you can also add the following lines to your config file to load the now unlocked keys into the agent:

# Search the following identities (keys) and add them to the agent
AddKeysToAgent yes
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_rsa

Put an IdentityFile line for each cipher you have a key for and want loaded into the agent. Now you can copy the public part of identities to your hosts, and ssh to them without a password, but still have the private key password protected on disk.

To preload the keys into your agent, add the following to your zsh or bash profile:

# Add my keys to the ssh agent; passwords are pulled from the keychain.
# The --apple-load-keychain option is unique to MacOS.

ssh-add --apple-load-keychain 

If you already have ssh keys you have generated in the past with no password, you might want to add a password to your keys.

2 thoughts on “Adding your ssh key password to MacOS Keychain”

  1. Thanks for posting this, but the title is a bit misleading as the post describes how to put **keys’ passwords** into the Apple Keychain, not the keys themselves.

    Reply

Leave a Comment