简体   繁体   English

如何在Java中将OpenSSH私钥转换为RSA私钥?

[英]How to convert OpenSSH private key to RSA private key in Java?

I have a private key file in OpenSSH format: 我有一个OpenSSH格式的私钥文件:

-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----

but I need it in RSA format: 但我需要RSA格式:

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

On the terminal I would do this: 在终端上,我会这样做:

ssh-keygen -p -m PEM -f my-openssh-file

but I need to do it in Java. 但是我需要用Java来做。

I've tried using org.bouncycastle.openssl.PEMWriter, but I can't work out how to convert my input key (as an input string) to a PrivateKey object that can be passed to the PEMWriter. 我已经尝试过使用org.bouncycastle.openssl.PEMWriter,但是我不知道如何将输入键(作为输入字符串)转换为可以传递给PEMWriter的PrivateKey对象。

This is actually possible with the Maverick Synergy Java SSH API . 使用Maverick Synergy Java SSH API实际上可以做到这一点。

This new branch of our SSH APIs supports the new OpenSSH private key file format so you can load the new key and convert it to the old PEM format supported by BouncyCastle. SSH API的这个新分支支持新的OpenSSH私钥文件格式,因此您可以加载新密钥并将其转换为BouncyCastle支持的旧PEM格式。

You will need the following maven dependencies: 您将需要以下Maven依赖项:

    <dependency>
        <groupId>com.sshtools</groupId>
        <artifactId>maverick-synergy-client</artifactId>
        <version>3.0.0-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>com.sshtools</groupId>
        <artifactId>maverick-bc</artifactId>
        <version>3.0.0-SNAPSHOT</version>
    </dependency>

You will also need the following snapshot repository because there is no formal release of the API at the current time: 您还需要以下快照存储库,因为当前没有API的正式版本:

    <repository>
        <id>oss-snapshots</id>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
        <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
    </repository>

First you can load the new OpenSSH private key format using: 首先,您可以使用以下命令加载新的OpenSSH私钥格式:

SshKeyPair key = SshKeyUtils.getPrivateKey(
          new File("id_rsa"), "passphrase");

Then you can convert it by passing it into the older format implementation and retrieving the text via the getFormattedKey method. 然后,可以通过将其传递到较旧的格式实现中并通过getFormattedKey方法检索文本来对其进行转换。

System.out.write(new OpenSSHPrivateKeyFileBC(
          key, "passphrase").getFormattedKey());

As a bit of background to this answer and to declare I am the developer of the recommended project, Maverick Synergy is a third generation API that has inherited from the J2SSH Maverick and Maverick Legacy commercial APIs. 作为回答这个问题的背景,并宣布我是推荐项目的开发人员,Maverick Synergy是继承自J2SSH Maverick和Maverick Legacy商业API的第三代API。 Maverick Synergy is fully available as an open source product licensed under the LGPL. Maverick Synergy作为LGPL许可的开放源代码产品完全可用。

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

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