How to use SFTP (with server validation - known hosts)

The topic How to use SFTP (introduction gives an overview of server validation. Many SSH implementations use a file called known_hosts which is loaded by clients to validate servers. Typically, this file is generated when a command-line client first connects to a server - a prompt asks if the server should be added to the list of known hosts.

The known_hosts file contains a list of approved servers and their public keys.

A single line in a known_hosts file looks like this:

edtmobile, ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAt60CtjBMxiOOqgqfFtKZHY3g99uZpuh5E143FTO4dw+EHWNKemoWq59FMFMIZfSLyUpWmsjVT3PP1bczOXP1OSn967kxLB/w7Xr84B1ZrTLwuR/ilq73HpgO7A8pdEJN7ybprzhs5CBEgaLQo2pOxfqRYyc8TO2ADnZ1WwtjW48=

The first field is the hostname, i.e. the SSH server. The IP address is also listed - a number of comma separated hostnames and IP addresses can be listed.

The second field is the applicable public key algorithm -"ssh-rsa" (for RSA key pairs) or "ssh-dss" (for DSA key pairs).

The third field is the public key encoded using base 64.

The known_hosts file normally consists of multiple lines, one for each of the hosts that the client may wish to connect to. It is quite typical for a host to have entries in two lines, so that both RSA and DSA public keys can be listed. Note that the server may send back an RSA key or a DSA key. If known_hosts only contains a DSA key for the host, and an RSA key is returned, server validation will fail. The server can be forced to send back a particular type of key as described in How to use SFTP (choosing algorithms).

As noted, public keys are cached by an instance of SSHFTPValidator which can be accessed through the SSHFTPClient.getValidator() method.

To load the known_hosts file into the validator cache, use the loadKnownHosts method, as shown below:


If another known_hosts file is subsequently loaded via this method, its contents will be added to the current list of known hosts.

To clear out the current list of known hosts, use the removeAllKnownHosts method, e.g.


The list of public keys in the cache can be retrieved by the getKnownHosts method. The hashtable returned has host-names as its keys and hash-tables of algorithm-names/fingerprints as its values.

Hashtable cache = ftp.getValidator().getKnownHosts();

Server public keys can also be maintained in their own file and explicitly added to the validator cache. See How to use SFTP (with server validation - public key files).