Create the Private Key / Public Key Combinations on your Local Machine
ssh-keygen -t rsa
This will create two files in the following directory:
The private key is titled ‘id_rsa’, and, the public key which will reside on your server is called ‘id_rsa.pub’:
Remember, you will always require the private key in order to authenticate yourself against the public key residing on your server.
If you’re having trouble understanding this, remember this analogy:
Think of a keyhole as the public key which resides on your server, anyone can attempt to open the door (server) by putting their key in the keyhole, however, only the correct key (private key) will open the door.
Create the SSH Folder on Your Server
SSH into your server and create a folder called ‘.ssh’ in your home directory:
Transfer the Public Key from Local Machine to Your Server
Next, we will transfer the public key you created locally in step 1 to your server using SCP.
scp ~/.ssh/id_rsa.pub email@example.com:~/.ssh/authorized_keys
Login using Your Public Key
You’re finished! You can now login to your CentOS server using public key authentication via any of the methods below:
Login using a Config File
It’s really easy to login when you use config files.
Simply create a ‘config’ file on your local machine as follows:
Once created, just edit the file using nano and specify your private key, username and hostname:
Host myserver HostName myservernameorip.com User root IdentityFile ~/.ssh/id_rsa
Now, you simply login via SSH by issuing the following:
Login with Specified Private Key
You can alternatively SSH into your server by specifying the private key we created earlier, simply use the -i flag to achieve this:
ssh -i id_rsa firstname.lastname@example.org
That’s all there is to it!