Creating JSch HostKey instance from a public key in .pub format

倾然丶 夕夏残阳落幕 提交于 2019-12-04 02:21:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!