问题
I am trying to send a file from a Windows machine to a Linux machine using JSch. Because of that I copied the host public key from the Linux machine to my Windows machine and added the key to my HostKeyRepository
. But for some reason I get "invalid key type" exception. Here is my code:
HostKeyRepository repo = jsch.getHostKeyRepository();
File file = new File("D:\\Uni\\Arbeit\\ssh_host_rsa_key.pub");
byte[] HK = Files.readAllBytes(file.toPath());
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
HostKey hk = new HostKey(null, HK);
repo.add(hk, null);
session.connect();
回答1:
The .pub
file has format:
<type> <base64-encoded-public-key> <comment>
What goes to the HostKey constructor is the public key part only, in a binary form (not base64-encoded).
Use the JSch Util.fromBase64()
to convert the base64-encoded-public-key
part to byte[]
.
static byte[] fromBase64(byte[] buf, int start, int length)
You can also check the JSch implementation of the known_hosts
file parsing in the KnownHosts.setKnownHosts(InputStream input)
.
The known_hosts
file has a similar format as the .pub
file, except that there's an additional hostname
part in the front and the comment
is usually not included:
<hostname> <type> <base64-encoded-public-key> [comment]
Note that your implementation does not have to be that complex as theirs, if you know that you are going to parse one specific format of the file.
来源:https://stackoverflow.com/questions/29604333/creating-jsch-hostkey-instance-from-a-public-key-in-pub-format