使用 java 生成 SSH 密钥

Sou*_*ata 5 java ssh putty

我尝试使用以下代码生成 SSH 密钥

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
         keyPairGenerator.initialize(2048);
         KeyPair keyPair=keyPairGenerator.generateKeyPair();

         RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
         RSAPrivateKey privateKey=(RSAPrivateKey)keyPair.getPrivate();

         String base64PubKey = Base64.encodeBase64String(publicKey.getEncoded());
         ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
         DataOutputStream dos = new DataOutputStream(byteOs);
         dos.writeInt("ssh-rsa".getBytes().length);
         dos.write("ssh-rsa".getBytes());
         dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
         dos.write(publicKey.getPublicExponent().toByteArray());
         dos.writeInt(publicKey.getModulus().toByteArray().length);
         dos.write(publicKey.getModulus().toByteArray());
         String publicKeyEncoded = new String(
                                    Base64.encodeBase64(byteOs.toByteArray()));
         String key =  "ssh-rsa " + publicKeyEncoded + " ";
         System.out.println("Public Key ------");
         System.out.println(key);


         System.out.println("------------------------------");
         System.out.println("Private key");
         System.out.println(Base64.encodeBase64(privateKey.getEncoded()));
Run Code Online (Sandbox Code Playgroud)

现在,当我将私钥的内容存储在文件中并尝试使用 putty 验证它时,它说私钥格式无效。

你们能帮我解决这个问题吗?我是如何丢失私钥格式的,所以 putty 无法识别它。

Sam*_*uri 1

Putty 无法识别 OpenSSH 格式的密钥——必须首先使用 Puttygen 将它们转换为 Putty 样式。

有一个用于此转换的 Debian/Ubuntu 软件包:

apt-get install putty-tools
puttygen openssh_formattted_key -o putty_formatted_key.ppk
Run Code Online (Sandbox Code Playgroud)

也许能够调查这一点并弄清楚密钥是如何转换的,或者从代码内部将命令作为进程运行。


在 Windows 上,Puttygen GUI 可用于执行此操作:

https://devops.profitbricks.com/tutorials/use-ssh-keys-with-putty-on-windows/

下载链接:https://the.earth.li/~sgtatham/putty/latest/x86/puttygen.exe

如果您想使用直接生成的密钥,我建议您使用 MINGW32/MINGW64、Cygwin 等,它们允许您在命令提示符或其他类似终端的窗口中使用 ssh 命令。