Add key pairs to Amazon EC2 instance.

I want to add another key pair to my EC2 instance.

Key Pairs

EC2 uses public-key cryptography, or asymmetric cryptography, which is a key pair consisting of a public key and a private key. The public key encrypts data and the private key decrypts it. The public key is stored on the EC2 instance in the ~/.ssh/authorized_keys file. In order to login, the private key needs to be used from the connecting machine. In a sense, the public key is the lock and the private key is the key.

Creating a New Key Pair

There are a few ways to create a new key pair. One method is to use the Amazon EC2 console. Go to your EC2 instance. In the left pane, there is a “Network & Security” section which contains a Key Pairs link. This page shows all existing key pairs. Click Create Key Pair which will generate a new private key. Save private key in the .ssh folder and change the permissions to read-only. You should also back it up via secure storage. I keep my keys backed up on a VeraCrypt USB.

chmod 400 this-key-pair.pem

Retrieve the Public Key

Next, retrieve the public key from the private key with ssh-keygen. ssh-keygen can generate, manage, and convert ssh authentication keys for SSH protocol version 2. The command uses two flags: -f and -y. -f indicates the filename of the private key and -y reads the private key and prints the public key.

ssh-keygen -y -f /path_to_key_pair/this-key-pair.pem

The resulting output is the ssh-rsa public key.

Add the Public Key to the EC2 Master List

Next, add the public key to the ~/.ssh/authorized_keys file in the EC2 instance. Connect to the instance with the existing private key file. If the existing private key is on a different machine, transfer the new public key to that machine. For example, via flash drive.

ssh-keygen -y -f /path_to_key_pair/this-key-pair.pem >> my-new-public-key.txt
cp /path_to_key_pair/my-new-public-key.txt /path_to_usb/

Once the transfer is complete, the follow the next steps on machine #2. SSH into the EC2 instance and copy the new public key to the ~/.ssh/authorized_keys file.

echo /path_to_usb/my-new-public-key.txt >> ~/.ssh/authorized_keys

Log In

Go back to machine #1 and try to login - it should be successful.

cd ~/.ssh/
ssh -i "this-key-pair.pem" username@your-ec2-instance.com

Keep in mind that you need to keep your private key 100% secured. Anyone who has this key can use it to log into your EC2 instance.

via GIPHY

Resources

SSH on Windows 10

  1. Built-in SSH
  2. PuTTY
  3. Bash on Ubuntu on Windows 10

Subscribe to Eric Brock

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe