简体   繁体   English

如何在Java中使用OPENSSH PRIVATE KEY?

[英]How to work with OPENSSH PRIVATE KEY in Java?

I am generating a DSA key with the below command: 我使用以下命令生成DSA密钥:

ssh-keygen -t dsa

Then I try to sign data using bouncycastle API like that: 然后我尝试使用bouncycastle API签署数据,如下所示:

    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    String privateKeyContent = // the content of the generated file

    //init privateKey
    byte[] pemContent = null;
    PEMParser pemParser = new PEMParser(new StringReader(privateKeyContent));
    Object pemObject = pemParser.readObject(); // throws

And getting this exception 得到这个例外

java.io.IOException: unrecognised object: OPENSSH PRIVATE KEY java.io.IOException:无法识别的对象:OPENSSH PRIVATE KEY

So I have been trying to convert the key file to PEM, using this example, and executing: 所以我一直在尝试将密钥文件转换为PEM,使用示例,并执行:

ssh-keygen -e -f key -m PEM > key.pem

But I am getting an error: 但我收到一个错误:

do_convert_to_pem: unsupported key type DSA

Any ideas on how to solve this? 关于如何解决这个问题的任何想法?

There are a few things going on here. 这里有一些事情发生。

  1. You are generating keys using a pretty recent version of OpenSSH (which is good). 您正在使用最新版本的OpenSSH生成密钥(这很好)。 These are now output in OpenSSH's new key format which the BouncyCastle API does not recognise as its a custom format. 这些现在以OpenSSH的新密钥格式输出,BouncyCastle API无法将其识别为自定义格式。

  2. You are generating a DSA key. 您正在生成DSA密钥。 OpenSSH deprecated use of DSA as it's not considered as secure as the other private key types provided like RSA, ECDSA, ED25519 etc. So whilst its letting you generate the key; OpenSSH不赞成使用DSA,因为它不像RSA,ECDSA,ED25519等提供的其他私钥类型那样安全。因此,它让你生成密钥; its not letting you convert it. 它不会让你转换它。

I would recommend that you change the key type to an RSA key with 2048 bits (minimum). 我建议您将密钥类型更改为2048位(最小)的RSA密钥。 That will, however, not stop the BouncyCastle API error because it will still be in the new OpenSSH format. 但是,这不会停止BouncyCastle API错误,因为它仍然是新的OpenSSH格式。

It really depends on what you are doing with the key. 这真的取决于你用钥匙做什么。 If you not using it within an SSH API to authenticate to remote servers and simply want to sign data with BouncyCastle API then you would be better off generating the key using OpenSSL with the command 如果您没有在SSH API中使用它来对远程服务器进行身份验证,并且只想使用BouncyCastle API对数据进行签名,那么最好使用OpenSSL使用命令生成密钥

openssl genrsa -out private.pem 2048

This key should then be recognised by the BouncyCastle API. 然后,BouncyCastle API将识别此密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM