Wednesday, 6 May 2015

How to Generate a Public/Private SSH keys

Before generating any key check the .ssh folder in user directory for previous generated keys.
$ cd ~/.ssh
$ ls
id_rsa  id_rsa.pub  known_hosts
If you see some previously generated keys (id_rsa, id_rsa.pub files), you should backup those keys, otherwise skip the step below and jump to Generate a key for the first time.
$ mkdir ssh_keys_backup
$ cp id_rsa* ssh_keys_backup
$ rm id_rsa*
Now you are ready to generate the key. Proceed to Generate a key for the first time

Generate a key for the first time
At the prompt, enter:
ssh-keygen -t rsa -C "Linux Key"
You should see:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Press 'Enter' here to accept the default.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
DO NOT just press enter to leave the passphrase empty. It is important that you use a strong passphrase for this key. If you do not use a passphrase, anyone who gets access to your key (such as if your laptop were stolen or your computer got a virus) could easily commit code as you -- people who trust you could then run malicious code, compromising their servers.
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
7e:f5:7e:51:ec:3d:2c:36:02:9d:5b:89:4a:3a:b7:b5 Linux Key


Copy your key

Once the key pair is generated, it's time to place the public key on the virtual server that we want to use.
You can copy the public key into the new machine's authorized_keys file with the ssh-copy-id command. Make sure to replace the example username and IP address below.
ssh-copy-id username@123.45.56.78
Alternatively, you can paste in the keys using SSH:
cat ~/.ssh/id_rsa.pub | ssh username@123.45.56.78 "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"
No matter which command you chose, you should see something like:
The authenticity of host '12.34.56.78 (12.34.56.78)' can't be established.
RSA key fingerprint is b1:2d:33:67:ce:35:4d:5f:f3:a8:cd:c0:c4:48:86:12.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '12.34.56.78' (RSA) to the list of known hosts.
user@12.34.56.78's password:
Now try logging into the machine, with "ssh 'user@12.34.56.78'", and check in:

  ~/.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.
Now you can go ahead and log into username@12.34.56.78 and you will not be prompted for a password. However, if you set a passphrase, you will be asked to enter the passphrase at that time (and whenever else you log in in the future).


 

No comments:

Post a Comment