通过.pub格式的公共密钥创建JSch HostKey实例 [英] Creating JSch HostKey instance from a public key in .pub format
问题描述
我正在尝试使用JSch将文件从Windows机器发送到Linux机器.因此,我将主机公共密钥从Linux计算机复制到了Windows计算机,并将密钥添加到了我的HostKeyRepository
.但是由于某种原因,我得到了无效的密钥类型"异常.这是我的代码:
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();
推荐答案
.pub
文件的格式为:
<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).
使用JSch Util.fromBase64()
将base64-encoded-public-key
部分转换为byte[]
.
Use the JSch Util.fromBase64()
to convert the base64-encoded-public-key
part to byte[]
.
static byte[] fromBase64(byte[] buf, int start, int length)
您还可以在KnownHosts.setKnownHosts(InputStream input)
中检查known_hosts
文件解析的JSch实现.
You can also check the JSch implementation of the known_hosts
file parsing in the KnownHosts.setKnownHosts(InputStream input)
.
known_hosts
文件的格式与.pub
文件类似,不同之处在于,前面有一个额外的hostname
部分,通常不包括comment
:
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.
因此,将File
中的行读取为字符串,删除<type>
和<comment>
并使用此表达式(取自KnownHosts.setKnownHosts
,键为<base64-encoded-public-key>
部分):
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())
这篇关于通过.pub格式的公共密钥创建JSch HostKey实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!