Setting up SSH Keys is straightforward and essential for enhancing security, especially when utilising the native Terminal applications available on Linux or macOS systems.
Start by opening the Terminal program on your local machine and typing the following command to generate the keys:
ssh-keygen
Generation Options: This command will prompt you with a few questions; it is recommended to accept the defaults for the file name (usually id_rsa).
Passphrase: When asked for a Passphrase, we strongly recommend entering a strong passphrase. This adds an extra layer of security to your Private Key, preventing its use if the key file is compromised. (If you choose not to use one, simply press Return).
Result: Two keys will be generated in the default path (typically): ~/.ssh/
Private Key: id_rsa
Public Key: id_rsa.pub
Next, you need to copy the Public Key (id_rsa.pub) to the remote server you wish to log into and add it to the authorized_keys file. You can do this efficiently using the ssh-copy-id command:
ssh-copy-id -i ~/.ssh/id_rsa.pub username@ip.add.ress.here
Ensure you replace:
username with the intended server access username.
ip.add.ress.here with the IP address or domain name of your server.
If your server uses an SSH port other than the default (22), you can specify it using the -p option (Example for port 2222):
ssh-copy-id -p 2222 -i ~/.ssh/id_rsa.pub username@ip.add.ress.here
Authentication: When running this command, you will be prompted for the current password for that user on the server. Once entered, the key will be copied and the necessary permissions set automatically on the server.
After copying the key, you should ensure the file and directory permissions on the remote server are correctly set (to prevent authentication failures). SSH into your server (using the password one last time), and execute the following commands:
# Log in to the server
ssh username@domain.com
# Inside the server, set permissions:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Note: The chown command is typically unnecessary if ssh-copy-id was used and executed by the correct user.
You can now test the connection. The server should automatically accept your Private Key without asking for a password (or it will ask for the passphrase you set for the key):
ssh username@domain.com