Resolving UnknownHostKey Error in Java SFTP Using JSch
The "UnknownHostKey" error occurs when JSch encounters an unknown host key while establishing an SFTP connection. To resolve this issue, you need to provide JSch with the expected host key for authentication.
Setting StrictHostKeyChecking
Initially, you attempted to disable host key checking by setting "StrictHostKeyChecking" to "no" before connecting to the SFTP server. This is a security risk and should not be done unless absolutely necessary.
Proper Approach: Setting Expected Host Key
Instead, you should set up an expected host key for JSch to verify against. There are two primary methods for achieving this:
Using known_hosts File
ssh-keyscan example.com > known_hosts JSch.setKnownHosts("path/to/known_hosts");
Using HostKeyRepository
// Create HostKey from public key HostKey key = new HostKey("example.com", "rsa", ...); // Add HostKey to repository JSch.getHostKeyRepository().add(key);
Note: Both approaches ensure that JSch can verify the authenticity of the SFTP server using the expected host key, thereby resolving the "UnknownHostKey" error.
The above is the detailed content of How to Resolve the 'UnknownHostKey' Error in Java SFTP Using JSch?. For more information, please follow other related articles on the PHP Chinese website!