Thursday, March 6, 2014

SSH - Generate Public and Private Keys

Secure Shell (SSH) is widely used to access shell on a remote Unix-like operating system. It uses public-private key pairs to authenticate remote machine and allow access.

1. ~/.ssh is where you keep the keys

Back to TOC
In a Unix-like environment, the keys are usually kept in the .ssh directory in your home directory(~).

ls -la ~/.ssh

You may or may not have a pair of key already:

id_rsa : private key file : public key file

The id_rsa private key file should be kept only by yourself. When you need to give out the key on request, provide the public key file.

2. Create new key pairs: mykey,

Back to TOC
We will now create the keys using 4096-bit RSA cryptotype with our email address as the comment in the key.

  • bash command:
$ ssh-keygen -t rsa -C "" -b 4096 -f ~/.ssh/mykey
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): [Prefer a passphrase]
Enter same passphrase again:

The new keys are now in ssh folder.

Your identification has been saved in /home/user/.ssh/mykey.
Your public key has been saved in /home/user/.ssh/

3. Add private key to local session

Back to TOC
Change the file permission to 700.

$ chmod 700 ~/.ssh/mykey*

Start the authentication agent and add the private key.

$ eval `ssh-agent -s`
$ ssh-add ~/.ssh/mykey

Above method will last until logout session.

4. Load the private key on login in local machine.

Back to TOC

Use >> for append.
Don’t try to lose existing key(s) in the file.

$ echo "IdentityFile ~/.ssh/mykey" >> ~/.ssh/config

Effective upon next login.

5. Add public key in remote machine

Back to TOC
First copy the to a remote machine.
Append the public key to the file authorized_keys.

Use >> for append.
Don’t try to lose existing key(s) in the file.

$ cat ~/.ssh/ >> ~/.ssh/authorized_keys

Test your connection from local machine with private key.

$ ssh -T yourremoteid@remoteaddress

7. Genarate public key from private key

Back to TOC
You can always generate the same public key from the private key, this is why you should never give out your private key.

$ ssh-keygen -y -f ~/.ssh/mykey > ~/.ssh/

Happy sshing!

Copyright © 2014 All Rights Reserved. No part of this website may be reproduced without’s express consent.

No comments: