Those two files are both used by SSH but for completely different purposes, which could easily explain your confusion.
By default SSH uses user accounts and passwords that are managed by the host OS. (Well, actually managed by PAM but that distinction probably isn't too useful here.) What this means is that when you attempt to connect to SSH with the username 'bob' and some password the SSH server program will ask the OS "I got this guy named 'bob' who's telling me his password is 'wonka'. Can I let him in?" If the answer is yes, then SSH allows you to authenticate and you go on your merry way.
In addition to passwords SSH will also let you use what's called public-key cryptography to identify you. The specific encryption algorithm can vary, but is usually RSA or DSA, or more recently ECDSA. In any case when you set up your keys, using the
ssh-keygen program, you create two files. One that is your private key and one that is your public key. The names are fairly self-explanatory. By design the public key can be strewn about like dandelion seeds in the wind without compromising you. The private key should always be kept in the strictest of confidence.
So what you do is place your public key in the
authorized_keys file. Then when you attempt to connect to SSH with username 'bob' and your private key it will ask the OS "I got this guy name 'bob', can be be here?" If the answer is yes then SSH will inspect your private key and verify if the public key in the
authorized_keys file is its pair. If both answers are yes, then you are allowed in.
Much like how the
authorized_keys file is used to authenticate users the
known_hosts file is used to authenticate servers. Whenever SSH is configured on a new server it always generates a public and private key for the server, just like you did for your user. Every time you connect to an SSH server, it shows you its public key, together with a proof that it possesses the corresponding private key. If you do not have its public key, then your computer will ask for it and add it into the
known_hosts file. If you have the key, and it matches, then you connect straight away. If the keys do not match, then you get a big nasty warning. This is where things get interesting. The 3 situations that a key mismatch typically happens are:
- The key changed on the server. This could be from reinstalling the OS or on some OSes the key gets recreated when updating SSH.
- The hostname or IP address you are connecting to used to belong to a different server. This could be address reassignment, DHCP, or something similar.
- Malicious man-in-the-middle attack is happening. This is the biggest thing that key checking is trying to protect you from.
In both cases,
authorized_keys, the SSH program is using public key cryptography in order to identify either the client or the server.