Skip to content

Instantly share code, notes, and snippets.

@aubique
Last active January 16, 2022 16:04
Generate a new SSH key pair

SSH Key Generation

Generate an SSH public keypair with OpenSSH:

ssh-keygen -t rsa -C "email"

You can also specify arguments and provide info about the source machine:

ssh-keygen -t rsa -b 4096 -C "$HOSTNAME($(lsb_release -cs)):$(date -I)" -f ~/.ssh/id_rsa_dest-source -P "<passphrase>"

Config File

If you'd like to access to Github with SSH then add that to ~/.ssh/config:

Host github.com
  Hostname github.com
  User login
  IdentityFile ~/.ssh/id_rsa_gh

Afterwards, you can test out the created SSH key:

The command to reset a private SSH key passphrase:

ssh-keygen -f ~/.ssh/id_rsa_gh -p

Show fingerprint of specified public key:

$ ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub
2048 fd:52:c5:f0:6b:b5:37:38:d7:93:e8:58:ab:bf:72:52 /etc/ssh/ssh_host_rsa_key.pub
$ ssh-keygen -lf id_rsa.pub
2048 e1:0a:a4:27:66:a7:6f:c8:77:cb:8d:d7:bd:f3:8f:d7 id_rsa.pub (RSA)

Adding your SSH key to the ssh-agent

Before adding a new SSH key to the ssh-agent, you should have checked for existing SSH keys and generated a new SSH key.

Ensure ssh-agent is enabled

Start the ssh-agent in the background:

eval "$(ssh-agent -s)"

Add your SSH key to the ssh-agent:

ssh-add ~/.ssh/id_rsa

If you used an existing SSH key rather than generating a new SSH key, you'll need to replace id_rsa in the command with the name of your existing private key file

You can delete all cached keys and check the saved ones:

ssh-add -D
ssh-add -l

Generate an RSA private key with OpenSSL

Generate a 2048 bit RSA Key encrypted using Triple-DES:

openssl genrsa -des3 -out private.pem 2048

Export the RSA Public Key to a File:

openssl rsa -in private.pem -outform PEM -pubout -out public.pem

Copying Public Key Using SSH

If you have a password-based SSH access to an account on your server, you can upload your keys using a conventional SSH method. And pipe over the content into a file authorized_keys by adding the public key to the existing ones.

The full command looks like this:

cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

There is a way to provide new keys via existing on-demand ssh access (such as Termux):

ssh <user>@<dest-host> -p <port> "su -c \"tee -a /data/ssh/shell/.ssh/authorized_keys\"" < ~/.ssh/id_rsa_dest-source.pub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment