Reputation: 177
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();
Upvotes: 3
Views: 6845
Reputation: 202292
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.
So read the line from File
to string, remove the <type>
and <comment>
and use this expression (taken from KnownHosts.setKnownHosts
, the key is the <base64-encoded-public-key>
part):
Util.fromBase64(Util.str2byte(key), 0, key.length())
Upvotes: 6