Key-based authentication is very popular nowadays with services on the web for IT, sometimes even required or much easier to setup because it’s treated as the default. For example, when installing a private Ubuntu server with SSH, password logins need to be explicitly enabled if you want to use them. Gitolite is another example. I’ve had issues with finding out how to quickly generate new keys in OSX after switching to it from Windows which has PuTTY.
So, to create a new public and private key pair simply use:
ssh-keygen -t rsa
or
ssh-keygen -t dsa
The first command is usually the one to go with. It will ask where to save the keys. The public key will have a .pub
extension added to it automatically. I don’t usually add new keys to one of the standard files, ~/.ssh/id_rsa
or ~/.ssh/id_dsa
but put them alongside them in the ~/.ssh
directory and give them names like raspberry
, openshift_private
etc. Both id_rsa
and id_dsa
are included by default when authenticating to remote servers using the ssh
command in terminal but adding keys in different paths on your own is not too complicated either, here's how:
ssh-add <path-to-private-key-file>
Having too many keys (usually about 5) can mean that a server won’t get to the right one in the end and just close the connection (too many login attempts
). A specific key can be chosen when connecting to a server using ssh -i <path-to-private-key>
. If a server requires a username and a password, use ssh -o PubkeyAuthentication=no
to avoid going through keys entirely.
Notes
I created a script that uses a bunch of ssh-add
commands to quickly add all my private keys to the system after rebooting.
The ~/.ssh
directory needs to be owned by your user with 700
permissions (use chmod <code> <file>
).
To list all the currently used private key files launch ssh-add -l
.
To remove a key use ssh-add -d <path-to-file>
. This will not remove the key from the hard drive, only from the SSH Agent.
Why is the system asking to confirm the identity of a server on the web when connecting for the first time? This is because the initial handshake with a remote server is considered an unsafe operation and can lead to connecting to a malicious server instead. This is the reason why public institutions exist that sell certificates (although recently it turned out they’re not so safe after all) to companies confirming their identity on the web. https://
connections use these certificates. They can be privately generated but then, again, the user will receive a notification that they’re not officially recognized. This is an example of a privately generated key notification in Google Chrome:
There are other commands in the system that use similar parameters as ssh
for managing keys when executing, scp
for example.
Using multiple different keys for different servers is a bit more work but in the end I believe it’s also a bit safer.