Generate an SSH Key on macOS
Learn how to generate an SSH key on macOS using Terminal. Works on macOS Ventura, Sonoma, and later.
Not using macOS?
In order to connect to your servers using an SSH key, you need to generate a key pair on your local machine first. In this guide we will see how to generate and secure your SSH key on macOS using the built-in Terminal app.
Generate an SSH Key Pair
Open Terminal (press Cmd + Space, type “Terminal”, and hit Enter) and run:
ssh-keygen -t ed25519 -a 100
ssh-keygen -t rsa -b 4096 -a 100
The -a 100 option increases the bcrypt KDF rounds, slowing down brute-force attempts if someone gets your encrypted private key, it does nothing if you do not use a passphrase.
You will be asked where to save the key file, press enter to use the default location.
Enter file in which to save the key (/Users/yourname/.ssh/id_ed25519):
You will be prompted to enter a passphrase. It is recommended to use a passphrase, but it is not mandatory. If you choose to use a passphrase, make sure it is a strong one.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your key pair will be created and saved under ~/.ssh directory, the private key as id_ed25519 or id_rsa depending on the type of key you generated, and the public key as id_ed25519.pub or id_rsa.pub.
Add the Key to the macOS Keychain
macOS includes a built-in SSH agent that integrates with the system Keychain. Adding your key means you won’t have to type your passphrase every time.
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
To make this persist across reboots, add the following to ~/.ssh/config (create the file if it doesn’t exist):
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ed25519
View your Public Key
cat ~/.ssh/id_ed25519.pub
cat ~/.ssh/id_rsa.pub
Setting Correct Permissions
macOS typically sets the right file permissions for generated keys, but if you copied the key from somewhere or you’re not sure, it’s always a good idea to explicitly set them:
chmod 600 ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_rsa
