How to Create and use SSH Keys
Here we'll go through how to create an SSH key on a mac and then use it to access secured content for communication between your resources without passwords
SSH, or Secure Shell Protocol, is a method for securely interacting between computers, including servers, over a network. It utilizes robust cryptographic techniques to encrypt connections between devices. While SSH can use key-based authentication as a more secure alternative to passwords, both methods can be configured according to security requirements.
This is particularly handy when connecting with cloud servers for security and restricting access to only specific users. It’s a standard practice and most hosting providers have or are removing the standard username and password credentials for their server access to more secure SSH keys.
We’ll go through how to generate an SSH key pair on your machine, add a matching key to another machine (a server) and then use the keys to authenticate between the devices. This is something I use all the time and have been wanting to write down the process so I don’t have to keep going back to try and remember how I’ve set everything up for authentication.
This is focused on a Mac… which means any UNIX based system (some commands may be slightly different for Linux, but mostly the same)… for Microsoft Windows (prior to windows 10 and 11) key generation you’ll need to follow the extra notes I’ll pop in the sections and highlight that they’re for Windows users.
So, on that note, here’s what we’ll be going through:
Generate an SSH Key
Mac and Linux come with a built in utility to generate SSH key’s called ssh-keygen
that you can run in your Terminal console window.
So to get started, open your Terminal and then enter:
ssh-keygen -t rsa
This will ask you to enter the location for your keys and default to the standard location if nothing is entered, which are all stored in the ~/.ssh folder. The default name for the key that is automatically picked up to use is id_rsa and id_rsa.pub if you haven’t created one before.
The one with no extension is the Private key and the one with the .pub extension is the Public key.
When you enter the above keygen code it will pop up with the
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/yourusername/.ssh/id_rsa):
You can either enter a new file path and name or leave it as it is, if it’s already present it will come up with a warning and ask you if you want to overwrite it. (you don’t need to add any extension for the keyname (id_rsa for example is just fine for the name of the file)
*NOTE: If you are using this key anywhere else and you overwrite it, you will need to update the public key where it’s being used or the access will not work anymore.
Once you select the path and keyname it will ask you for a passphrase to protect the key, meaning you will need to enter this for the services to access it. Some resources require this to be entered. This is optional, you can just enter twice to skip this if you don’t want the extra security for your keys.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Once completed it will have your key and public key file location saved with a key fingerprint and a key image for it:
Your identification has been saved in /Users/yourusername/.ssh/id_testkey
Your public key has been saved in /Users/yourusername/.ssh/id_testkey.pub
The key fingerprint is:
SHA256:5Ymbofohin+6O14EZy7OyA3yBeFyLSp6aeQV7nci0 yourusername@ipadd
The key's randomart image is:
+--[RSA 256]--+
| . |
| . o |
|. = . |
| + O . + . |
|+.o B E S o |
|=BoX . + |
|o.X.* = + |
| +.+. + |
|.oB*. |
+----[SHA256]-----+
This will now create 2 files in the .ssh folder:
id_testkey
id_testkey.pub
*NOTE: for Microsoft Windows prior to 10 and 11, you will need install PuTTY and follow these steps: Generate SSH Keys Using PuTTY
ssh-keygen Command Options
There are various command options you can use with the ssh-keygen command, as mentioned in the SSH Keygen academy documents but we’re only using the -t command in our example:
-b “Bits” This option specifies the number of bits in the key. The regulations that govern the use case for SSH may require a specific key length to be used. In general, 2048 bits is considered to be sufficient for RSA keys.
-e “Export” This option allows reformatting of existing keys between the OpenSSH key file format and the format documented in RFC 4716, “SSH Public Key File Format”.
-p “Change the passphrase” This option allows changing the passphrase of a private key file with
[-P old_passphrase]
and[-N new_passphrase]
,[-f keyfile]
.-t “Type” This option specifies the type of key to be created. Commonly used values are: - rsa for RSA keys - dsa for DSA keys - ecdsa for elliptic curve DSA keys
-i "Input" When ssh-keygen is required to access an existing key, this option designates the file.
-f "File" Specifies name of the file in which to store the created key.
-N "New" Provides a new passphrase for the key.
-P "Passphrase" Provides the (old) passphrase when reading a key.
-c "Comment" Changes the comment for a keyfile.
-p Change the passphrase of a private key file.
-q Silence ssh-keygen.
-v Verbose mode.
-l "Fingerprint" Print the fingerprint of the specified public key.
-B "Bubble babble" Shows a "bubble babble" (Tectia format) fingerprint of a keyfile.
-F Search for a specified hostname in a known_hosts file.
-R Remove all keys belonging to a hostname from a known_hosts file.
-y Read a private OpenSSH format file and print an OpenSSH public key to stdout.
Add Key to a Linux Server
We can add the keys to the server in a few ways, but I’m going to run through adding it via the command line directly to the required file, and also another way that can update it in a single line, it depends if you are connecting to your server via password or not.
Update the authorized_keys
*NOTE: This option is if you can connect to your server via SSH without an initial SSH key, so if you’re adding a key for someone else, or if you can connect via a browser based console, which alot of providers (such as Digitalocean) allow for that doesn’t require an initial SSH key or password to connect.
Now the first thing you want to do is get the contents of the public key you created earlier, so you can either open a text editor, load up the /Users/yourusername/.ssh/id_testkey.pub
file and copy the contents, or you can simply, if you still have your Terminal open enter the below:
cat /Users/yourusername/.ssh/id_testkey.pub
and this will output the generated key that should look something similar to this:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDV6DQJmTeZdKKwdNpOSd8yLKV0d693+a2enK3AWNIEg8aCmcRCs5Ml4kZOEC42WRyxe9FdAlHvGDs+ht1yC90vwrvNG2F2Vn/FIScPper4LgFiZIakz99j/y261oR3+LV5Lc= yourusername@youripaddress
So Copy this entire code, and let’s connect to your server.
I’m using a Digitalocean droplet, so I’ll use this as an example, but if your hosting provider has a browser based Console (which most should), you can do a similar process.
Login to Digitalocean and select your droplet. Once your droplet is open, select the Console option in the top menu list and it will open a Console in a new window as a root user so you have access as an admin.
*NOTE: This is only a quick Ubuntu server I created to demo this example
If you setup through Digitalocean, you should have the ~/.ssh and the authorized_keys folder and file already there, and you can check by trying to access the folder and listing it’s items:
cd ~/.ssh
ls
If it comes up with an error when using the cd command or when you use the ls command and the authorized_keys file isn’t listed, then you will need to create them.
To do that you can enter the below:
# make the SSH directory
mkdir -p ~/.ssh
# Create the authorized_keys file
touch ~/.ssh/authorized_keys
# set permissions for the folder and file so they can be accessed for authentication and login
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
# Permission settings based on the user for the .ssh file and contents
chmod -R go= ~/.ssh
chown -R $USER:$USER ~/.ssh
Once permissions are provided you can simply run the command to copy the Public key from earlier and paste it within the quotation marks in the below command:
echo "<your-public-key>" >> ~/.ssh/authorized_keys
Now you should be able to login to the server without having to enter a password and just using the key.
Add Key using ssh-copy-id
*NOTE: This option is only if you can access your server via username and password, otherwise use the previous method.
On your local machine, within your Terminal window, you can simply enter the below:
ssh-copy-id username@ip-address-of-server
This assumes that you are using the default key like id_rsa, however, if you’re not using the standard key, like we did in the example above(id_testkey), you will need to specify the path to the key and this can be done using the below code exmaple:
ssh-copy-id -i /Users/yourusername/.ssh/id_testkey username@ip-address-of-server
This will then prompt you if you want to connect:
Are you sure you want to continue connecting (yes/no)? yes
And then it will ask for your password:
username@ip-address-of-server's password:
Then once you’ve entered your password and if all successful, it will display a message and to login using SSH:
Number of key(s) added: 1
Now try logging in to the machine, with: "ssh 'username@ip-address-of-server'"
and check to make sure that only the key(s) you wanted were added.
*NOTE: Make sure you update the details with your own details
Connect to Server Using SSH Key
Now that you have setup the SSH keys between your machine and the server, this should be the easiest part (fingers crossed 😅).
Open your Terminal console window.
To connect with the default ssh key (id_rsa) then you can simply enter:
ssh username@ip-address-of-server
However, if you’re using a different key then you can use -i to specify the key location on your machine:
ssh -i /Users/yourusername/.ssh/id_testkey username@ip-address-of-server
If it’s the first time, it’ll ask if you want to add the fingerprint, choose Y and then it will load the server console in the window, you’ll be able to tell as it will have listed the username and the machine:
username@ip-address-of-server:~#
Summary
There we go, now you should have created a secure connection between your machine and your server without the need for password access.
I know I used the Digitalocean droplets as an example for the server, but the concept is the same when using SSH keys to authenticate between machines and there should only be a slight difference in the commands between operating systems. Especially now that windows from 10 and up have OpenSSH built in that allows to do the same console commands as UNIX systems and not needing to install and use PuTTY.
This is probably the best option to remote into another machine using cryptographic authentication between devices.
Until next time, happy dev-ing peeps! 😁