Java 中的 ssh-keygen 命令从私钥中提取 public 密钥

ssh-keygen command in Java to extract public key from private key

我正在尝试使用 Java 的 Runtime.getRuntime().exec() 从私钥中 提取 public 密钥使用 ssh-keygen linux 实用程序。

当我在终端上 运行 这个命令时,它运行完美,我能够从 RSA 私钥中提取 public 密钥

ssh-keygen -y -f /home/useraccount/private.txt > /home/useraccount/public.txt

但是当我 运行 使用 Java 相同的命令时,它不会创建 public.txt 文件。它也不会抛出任何错误。

Process p = Runtime.getRuntime().exec("ssh-keygen -y -f /home/useraccount/private.txt > /home/useraccount/public.txt");
p.waitFor();

我想知道这是为什么?

不是真正的答案,因为我没有时间测试但基本选项:

// example code with no exception handling; add as needed for your program

String cmd = "ssh-keygen -y -f privatefile";
File out = new File ("publicfile"); // only for first two methods

//// use the stream ////
Process p = Runtime.exec (cmd);
Files.copy (p.getInputStream(), out.toPath());
p.waitFor(); // just cleanup, since EOF on the stream means the subprocess is done

//// use redirection ////
ProcessBuilder b = new ProcessBuilder (cmd.split(" "));
b.redirectOutput (out);
Process p = b.start(); p.waitFor();

//// use shell ////
Process p = Runtime.exec ("sh", "-c", cmd + " > publicfile");
// all POSIX systems should have an available shell named sh but 
// if not specify an exact name or path and change the -c if needed 
p.waitFor();