In this blogpost, I will focus on setting up SSH keys on a CentOS 7 installation. SSH keys provide a straightforward, secure way of logging into your server and is the recommended authentication method.

Create a new user

Log in to your CentOS 7 server with a root account.

ssh root@server_ip_address

Use the adduser command to add a new user to your centos 7 server.

adduser username

Create RSA Key-Pair

The next step is to create a key pair on the client machine that is going to use the account:

ssh-keygen -b 4096

-b 4096 is used to created a more secure (longer) keypair

$ ssh-keygen -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/your_home/.ssh/id_rsa):

If you leave file path blank it will save to ~/.ssh/

You now have a public and private key that you can use to setup ssh authentication with the Centos 7 server.

Copy the Public Key to the CentOS 7 Server

Client Machine

To display the content of your key, type this into client machine where you peformed the commands from the previous chapter:

cat ~/.ssh/

the path mentioned in the above command can defer if you specified another location in the previous chapter.

CentOS 7 server

Impersonate the newly created user so the files we will create will have the right permissions:

sudo su username

Now we need to add the public key to the authorized_keys file, this file must be placed in the ~/.ssh directory.

Let's create it in case it doesn't exist:

mkdir ~/.ssh

Now you need to create or modify the authorized_keys file within this directory.

Now add the public key to the end of the authorized_keys file with the following command:

echo 'content of' >> ~/.ssh/authorized_keys

The above command will do an append this means it will create the file if non-existent or add the public key if there's data in the file already.

Set permissions on the .ssh folder and authorized_keys file:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

~ will automatically resolve to the logged in user home directory

Sudo (optional)

Use the usermod command to add the user to the wheel group for Sudo access for the new user account.

usermod -aG wheel username