Creating a private/public key pair on Ubuntu

Creating a private/public key pair on Ubuntu

Last updated:

There are many reasons you might want to create a key pair on Linux, more specifically on Ubuntu.

For more information about key pairs, see this.

If your server is an Amazon EC2 Server Instance, you might want to look at more specific information here

Key pairs are just one way to log into a system. (Perhaps the one you currently use is regular username and password ssh login). Key pairs are generally more secure than password logging in.

One thing you have to keep in mind is that using key pairs is a two-way method: you'll need to create a private key and a public-key.

Personally, I use them so I can use git remotely. Another very common use of public/private key pairs is when you want to, for example, scp a file from your local server into a remote server without needing to type the ssh password lots of times. Another good reason to use this is to disable anyone from logging into your server, which reduces the chance someone will break into your server. (I'm not an expert on security so do you own research before securing your web server, as it's a very important step.)

Ok so let's start: Ubuntu has a very handy way to accomplish this:

Create yourself a .ssh directory if you don't already have one.

mkdir ~/.ssh

Then type this command to create the key per se:

ssh-keygen -t rsa

(you'll be prompted for a passphrase. It adds another layer of security still. You can choose one or leave it blank.)

cd to your home folder to check the key has been created:

cd ~/.ssh
ls

You should see two files: id_rsa and id_rsa.pub.

Now you'll need to transfer the public key (the .pub file) to your remote server. Again, Ubuntu has a simple command to do this:

ssh-copy-id <username>@<host>

If the last step was successful, you should be able to log into your server with no password (only from this machine, of course!. Ubuntu will use the private key wev'e just created to authenticate.)

ssh <username>@<host>

et voilà

troubleshooting: if a command isn't working, try issuing that command again with sudo.

see also: official ubuntu docs