I'm available for challenging remote roles. Let's get in touch.

How to generate and use SSH keys on macOS

Learn how to generate SSH keys, why you should use passphrases, how to use your SSH keys on GitHub, and more.

Flavio Silva
Flavio Silva • June 23, 2023
How to generate and use SSH keys on macOS
Image by Freepik

I last tested these instructions on macOS Ventura 13.3.1.

Introduction

In this step-by-step guide, you'll learn how to generate SSH keys, why you should use passphrases, how to prevent typing passphrases every time you start an SSH connection, and how to use your SSH keys on GitHub.

Go straight to the instructions if you want to skip some of the theories below.

Do not type the $ sign you see in the command examples in this article. That's just an indicator that you should run the command that follows it in your command line tool.

What is SSH?

SSH is short for Secure Shell, a cryptographic network protocol that allows for secure authentication, encrypted data transfer, and command execution between computers.

"SSH applications are based on a client-server architecture, connecting an SSH client instance with an SSH server." ("Secure Shell")

What is an SSH client?

An SSH client is a software program that uses the Secure Shell protocol to connect to a remote computer running an SSH server.

What is an SSH server?

An SSH server is a software program that uses the Secure Shell protocol to accept connections from remote computers running an SSH client.

What is OpenSSH?

OpenSSH is the world's most widely used SSH implementation, providing client and server implementations. It is open source and part of the OpenBSD project and the default SSH implementation in most Linux and Unix-like distributions, including macOS. It's also available for Windows through third-party distributions like Cygwin and Windows Subsystem for Linux (WSL).

OpenSSH on macOS

The macOS provides OpenSSH as its default SSH implementation. The conveniently named ssh command line tool is the client part of the OpenSSH software package.

If you want to know about it, run the following command:


$ ssh -V

You should see an output like this: OpenSSH_9.0p1, LibreSSL 3.3.6.

Now you can notice that it also mentions LibreSSL. That's because macOS combines OpenSSH and LibreSSL for its SSH implementation.

LibreSSL is an open-source cryptographic library that aims to provide a more secure and modernized version of the SSL/TLS protocols and cryptographic functions. OpenSSH uses LibreSSL as its underlying library in macOS to provide some cryptographic operations and SSL/TLS support.

You can also use OpenSSH's server software on your macOS. To allow your Mac to accept SSH connections, you can go to:


Apple Menu -> System Settings -> General -> Sharing

Then, turn the Remote Login option on. Be cautious, though. Only do that if you need it. Only open ports on your computer as you need. It's turned off by default for a reason.

What are SSH keys, and why should we use them?

SSH keys (short for Secure Shell keys) are cryptographic keys used for authentication in the Secure Shell protocol. They come in pairs of a public and a private key, and they only make sense when used together, i.e., one is only useful with the other. Each key is a text file in your filesystem.

SSH keys allow secure passwordless authentication and offer several advantages over traditional password-based authentication, such as enhanced security since they're based on robust cryptographic algorithms (and virtually eliminate the risk of brute-force password attacks), convenience since you don't have to remember and type passwords every time, and automation because we can use them for automated tasks, such as script execution or server management.

You store your public key on the server you want to connect to while keeping your private key on your local machine. Then, when you try to connect to a remote server using your SSH client, the server verifies your identity by matching your public key with the corresponding private key stored on your local machine. Then, the server grants you access and establishes an encrypted session if there's a match. One key security point is that your private key never leaves your local machine. When using password authentication, your password goes through the network.

Protecting your private key is essential since anyone with access to it can authenticate as you. Therefore, ensure the private key is stored securely and not shared with unauthorized individuals. As a rule, you should never share or send it anywhere with anyone.

Securely backing up your public and private keys is also advised. That way, when you format your computer or get a new one, you can retrieve your keys instead of generating new ones and replacing them everywhere you use them.

Make sure you don't have SSH keys already

You might have SSH keys already and don't know it. So let's figure it out.

Open your Terminal and cd into your user's dir:


$ cd ~/

Now let's list all files and folders in that dir:


$ ls -lah

Look for a directory named .ssh. If you can't find one, you don't have SSH keys. If you have, cd into it and list all files to make sure you have your keys there:


$ cd .ssh


$ ls -lah

You can have many key pairs and give them whatever names you want, but usually, any files inside the .ssh dir other than known_hosts and config are keys. The public one typically has the same name as the private one but ends with .pub.

If you generated your keys using the RSA algorithm (more about that in the next section) and used the default names, you should be able to see the following two files:


id_rsa
id_rsa.pub

Alternatively, If you generated your keys using the Ed25519 algorithm (more about that in the next section) and used the default names, you should be able to see the following two files:


id_ed25519
id_ed25519.pub

In either case, you already have your keys, so you can head to the How to use your SSH keys on GitHub section.

You don't have SSH keys if you can't see them or any other key files.

So let's generate your keys now.

How to generate SSH keys on macOS

It's easy to generate SSH keys on macOS. You only have to run the following command:


$ ssh-keygen -t ed25519 -C "your_email@example.com"

Don't forget to replace your_email@example.com with your email.

The ssh-keygen command is one of the utilities included in OpenSSH. We use it to generate, manage, and manipulate SSH key pairs.

We use the -t option to specify the type of cryptographic algorithm used to generate our keys.

RSA (Rivest–Shamir–Adleman) is a widely used cryptography algorithm.

In the case above, though, we're using the Ed25519 algorithm. It's a modern elliptic curve cryptography (ECC) algorithm known for its strong security and efficient performance, and it's becoming increasingly popular and recommended for most SSH key generation. For example, GitHub is now recommending it on its SSH guides.

We use the -C option to add a comment to the generated keys, usually an email address or any other descriptive comment.

After running the command, you should see an output like the following:


Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/your_user_name/.ssh/id_ed25519):

You can type your custom key name or hit return to use the default one. I'll use the default one.

After that, you'll be asked to type a passphrase:


Enter passphrase (empty for no passphrase):

I'll talk about passphrases in a moment. For now, suffice it to say that although it is optional, it is highly recommended, and we'll see a nice setup on how to type your passphrase only once, ever, instead of having to type them every time you start an SSH connection. Your passphrase should have at least sixteen characters.

After typing your passphrase, you'll be asked to type it again, and after that, you should see an output like the following alongside your key's fingerprint:


Your identification has been saved in /Users/your_user_name/.ssh/id_ed25519
Your public key has been saved in /Users/your_user_name/.ssh/id_ed25519.pub

In the message above, "Your identification" means your private key, i.e., the file id_ed25519.

Congrats! You now have your keys on the ~/.ssh dir (provided you went with the default dir).

What are passphrases, and why should we use them?

You should protect your private key at all costs. But if someone gains access to your machine or your keys leak, they can copy your private key, and that's it. They now own it as much as you do and can use it wherever you can.

Wouldn't it be nice if you could add an extra layer of security over your private key? Well, that's what a passphrase does. It encrypts your private key on your filesystem, so when you use it, you must provide the passphrase to decrypt it. That way, any nonauthorized person who gains access to your private key must also know its passphrase to use it. So that's our additional layer of security. It works like two-factor authentication.

"A passphrase is similar to a password, except it can be a phrase with a series of words, punctuation, numbers, whitespace, or any string of characters you want. Good passphrases are 10-30 characters long, are not simple sentences or otherwise easily guessable [...], and contain a mix of upper and lowercase letters, numbers, and non-alphanumeric characters. The passphrase can be changed later by using the -p option." ("ssh-keygen - OpenBSD manual pages")

The downside of having a passphrase is that, as I said earlier, we have to type it every time we start a new SSH connection. That's necessary because when we use passphrases, the private key is encrypted in our filesystem, so we need to decrypt it before having it available in memory to be used.

But there are two ways to avoid typing your passphrase every time you start an SSH connection, and I'll show you how to do both, so you can choose what method you prefer:

How to prevent typing your passphrase every time on macOS

  1. Using the ssh-agent tool. This way requires you to run two commands and type your passphrase every time you create a new macOS user session (typically after a computer reboot). Use ssh-agent if you prefer this way.

  2. Using Apple's Keychain. This way requires you to run one command, add a simple configuration to a text file, and type your passphrase, all three steps only once, ever. Then, every time you create a new macOS user session (e.g., boot your computer and log in), your passphrase will be available in memory by the Keychain. That's the best way to have the best of both worlds: your private key is protected, i.e., if anyone copies it, they still can't use it without its passphrase, and you don't have to type your passphrase ever again unless you format your macOS or get a new one. Use Keychain if you prefer this way, as I do.

What is the ssh-agent, and how to use it?

Note: You don't have to worry about the ssh-agent if you didn't type a passphrase when you generated your keys. In that case, head to the How to use your SSH keys on GitHub section.

The ssh-agent command line tool manages SSH keys and facilitates secure authentication when using SSH. It acts as a security agent that holds private keys in memory and provides them to SSH clients upon request, eliminating the need to enter passphrases for encrypted private keys repeatedly.

To do that, we have to do two things. First, we have to run the following command every time we reboot our computer (or create a new user session) to start ssh-agent:


$ eval "$(ssh-agent -s)"

You should see an output like this:


Agent pid 5361

Nice, that means ssh-agent is now running in the background.

Then, we run the following command to decrypt our private key and send it to ssh-agent. It will then hold the decrypted key in memory and provide it whenever requested.


$ ssh-add ~/.ssh/id_ed25519

You'll be asked to type your passphrase, and after that, you should see an output like the following:


Identity added: /Users/your_user_name/.ssh/id_ed25519

And that's it. You can now connect via SSH without typing your passphrase again until you log out of your macOS session or restart your machine.

Head to the How to use your SSH keys on GitHub section if you use it.

What is Apple's Keychain, and how to add your SSH keys to it

Note: You don't have to worry about Apple's Keychain if you didn't type a passphrase when you generated your keys. In that case, head to the How to use your SSH keys on GitHub section.

Apple's Keychain is a password management system built into macOS. We use it to store passwords and other sensitive information, including our SSH key passphrases.

To add your passphrase to Keychain, run the following command:


$ ssh-add --apple-use-keychain ~/.ssh/id_ed25519

You'll be asked to type your passphrase.

Now, you can connect via SSH without typing your passphrase again. But if you restart your machine, it'll be like you never run that command, i.e., you'll have to type your passphrase every time you start an SSH connection. So you need to take one more step.

Check if you have a config file in your .ssh dir:


$ cd ~/.ssh
$ ls -lah

If you can't see it, run the following command to create an empty config file:


$ touch ~/.ssh/config

Now, open it and add the following to the top of it:


UseKeychain yes

If you are not sure how to open that file, you can use a few options, including opening the built-in TextEditor from the command line by running the following:


$ open -a TextEdit ~/.ssh/config

And that's it! 🎉

You'll only be bothered by the passphrase again if you format your machine or get a new one.

If you use GitHub, head to the next section to put your keys to good use.

How to use your SSH keys on GitHub

You add your public key to GitHub to make it possible to connect to it via SSH.

But first, let's make sure you can't authenticate on GitHub with SSH by running the following command:


$ ssh -T git@github.com

If that's your first time trying to connect to GitHub using SSH, you should get a message like this:


The authenticity of host 'github.com (20.201.28.151)' can't be established.
...
Are you sure you want to continue connecting (yes/no/[fingerprint])?

Type yes and hit return.

Then you should see the following:


git@github.com: Permission denied (publickey).

Alternatively, you can try to git clone a GitHub repo using the SSH path (the one starting with git@github.com instead of https://github.com).

You should get the same error message alongside some other output.

If those commands work, you already have your public SSH key added to GitHub. Otherwise, let's keep going.

You'll add your public key to GitHub. Make sure you use the file ending with .pub. Otherwise, you will expose your private key. If that happens, you should delete the pair (public and private keys) and generate new ones. Remember, they're text files on your filesystem, so you only have to delete them.

I could describe here the steps to add it to GitHub, but GitHub itself has a page dedicated to it, so you can follow the steps there and get back here to test if it works and finish reading this guide. Just make sure you select Authentication Key on the Key type dropdown.

After adding your public key to GitHub, rerun the following command:


$ ssh -T git@github.com

If everything worked, you should see a message like this:


Hi <your_github_user_name>! You've successfully authenticated, but GitHub does not provide shell access.

Yay! It works! 🥳

You can also use the SSH path to git clone a repo without having to type any password or passphrase. It should just work.

If you went with Apple's Keychain path, you can now make the final test. Yes. I know that you know, and I know that you know that I know. Go ahead. Do it. Restart your Mac and try to run the command above. See for yourself. No more passphrases! 🤯

How to use your SSH keys on other services?

The nice thing about SSH keys is that they work the same everywhere. So once you have your local machine set up, as you do by now, you add your public key to a service, and that's it. You can connect to it via SSH.

How to change a passphrase or add one to a private key without one

You can change the passphrase for an existing private key without regenerating the key pair. You can also add a passphrase to a private key that doesn't have one. In either case, you run the following command (change the file name and path if necessary):


$ ssh-keygen -p -f ~/.ssh/id_ed25519

If your key already has a passphrase, enter it before changing it to a new one.

Conclusion

And that's it for this guide. I hope you enjoyed it!

Thank you for reading, and let me know if you have any issues or suggestions in the comments below.

Are you using Git? Head to my guide on How to sign Git commits with SSH keys.

Or, if you're new to Git, head to my Introduction to Git.




I incorporated generative AI tools into my workflow, and I love them. But I use them carefully to brainstorm, research information faster, and express myself clearly. It's not copy/paste in any way.



How to sign Git commits with SSH keys
How to set up your Mac for software development
How to install and use Homebrew on macOS
How to install Git with Homebrew on macOS
How to install Command Line Developer Tools on macOS
Introduction to Git

OpenSSH
Connecting to GitHub with SSH

Bibliography

"ssh-keygen - OpenBSD manual pages" OpenBSD, n.d. Wed. 24 May 2023 <https://man.openbsd.org/ssh-keygen>

"Secure Shell" Wikipedia, n.d. Web. Fri. 19 May 2023 <https://en.wikipedia.org/wiki/Secure_Shell>

How to generate and use SSH keys on macOS by Flavio Silva is licensed under a Creative Commons Attribution 4.0 International License.

Leave a comment using your GitHub account

© 2024 Flavio Silva