Everything about ssh keys on Ubuntu

Last Updated: Feb. 17th 2022 at 10:03pm Tags: blog linux ssh

Everything about ssh keys on Ubuntu

Secure Shell (SSH) is a cryptographic protocol used for a secure network connection between a client and a server.

SSH keys are used for connecting to servers as well as git repositories.

SSH keys can be re-usable and you can share the “public” key with anyone.
But be careful to never share your private key.

Generate an SSH Key

Use ssh-keygen to generate a new password.

ssh-keygen -t rsa -b 4096 -C "your_email@domain.com"

You will be thrown into a wizard where you will be asked:

Enter file in which to save the key (/home/USER/.ssh/id_rsa):

Choose where you want the key created (if you leave out the path $PWD will be used)

Enter passphrase (empty for no passphrase):

You can have no passphrase for when you are configuring automated tasks, but please be secure and use a password for your main key. If you entered a passphrase you will need to enter it twice to confirm.

There will be two files created one with a .pub extension and another with no extension. The .pub file is your public key.
You can share this with your system administrators, put it in your Ansible scripts; whatever you want the only thing it does is allow you to connect to the server that is using it.

The second file is your private key which should be guarded with strict security.

SSH config file

The ssh config file is stored in your home directory /home/USER/.ssh/ config

It has no file extension. Here is an example config file containing multiple git repositories.

Host gitlab.com
  Hostname gitlab.com
  user nick
  PreferredAuthentications publickey
  IdentityFile /home/USER/.ssh/nickyeoman_rsa

Host github.com
  Hostname github.com
  user git
  PreferredAuthentications publickey
  IdentityFile /home/USER/.ssh/nickyeoman_rsa

Host gitea.nickyeoman.com
  Hostname gitea.nickyeoman.com
  user git
  PreferredAuthentications publickey
  IdentityFile /home/USER/.ssh/nickyeoman_rsa
  Port 1234

Host digitalocean.nickyeoman.com
  user root
  PreferredAuthentications publickey
  IdentityFile /home/USER/.ssh/nicksecure_rsa
  Port 1234

Notes:

  • Host is the alias you want to type after ssh
  • Wildcard (*) works for Host.
  • Indentation is not required; however, it makes the file easier to read.
  • man ssh_config to find all options

Pro tip: use Ansible to mange your ssh config file.

Copy public key to server

There are a number of ways to do this:

  • ssh-copy-id remote_username@server_ip_address
  • scp

Regenerate your public SSH Key

Here is how you can regenerate your public SSH key if it’s RSA based

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

The public key will appear where you tell it to.

Reference

Comments

You need to login to comment.