如何在Java中使用OPENSSH私钥? [英] How to work with OPENSSH PRIVATE KEY in Java?

查看:313
本文介绍了如何在Java中使用OPENSSH私钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令生成DSA密钥:

I am generating a DSA key with the below command:

ssh-keygen -t dsa

然后,我尝试使用bouncycastle API签名数据:

Then I try to sign data using bouncycastle API like that:

    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

并获得此异常

java.io.IOException:无法识别的对象:OPENSSH私钥

java.io.IOException: unrecognised object: OPENSSH PRIVATE KEY

因此,我一直在尝试使用示例并将该文件转换为PEM,并执行:

So I have been trying to convert the key file to PEM, using this example, and executing:

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

但是我遇到一个错误:

do_convert_to_pem: unsupported key type DSA

关于如何解决此问题的任何想法?

Any ideas on how to solve this?

推荐答案

这里发生了一些事情.

There are a few things going on here.

  1. 您正在使用OpenSSH的最新版本生成密钥(很好).现在,这些内容以OpenSSH的新密钥格式输出,BouncyCastle API无法将其识别为自定义格式.

  1. You are generating keys using a pretty recent version of OpenSSH (which is good). These are now output in OpenSSH's new key format which the BouncyCastle API does not recognise as its a custom format.

您正在生成DSA密钥. OpenSSH不赞成使用DSA,因为它不像其他提供的私钥类型(如RSA,ECDSA,ED25519等)那样安全.它不会让您转换它.

You are generating a DSA key. 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; its not letting you convert it.

我建议您将密钥类型更改为2048位(最小)的RSA密钥.但是,这不会停止BouncyCastle API错误,因为它仍然是新的OpenSSH格式.

I would recommend that you change the key type to an RSA key with 2048 bits (minimum). That will, however, not stop the BouncyCastle API error because it will still be in the new OpenSSH format.

这实际上取决于您对密钥进行的操作.如果您未在SSH API中使用它来对远程服务器进行身份验证,而只想使用BouncyCastle API签名数据,那么最好使用带有命令的OpenSSL来生成密钥

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

openssl genrsa -out private.pem 2048

然后,BouncyCastle API会识别此密钥.

This key should then be recognised by the BouncyCastle API.

这篇关于如何在Java中使用OPENSSH私钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆