I'm trying to use Java's Runtime.getRuntime().exec() to extract public key from private key using ssh-keygen linux utility.
When I run this command on terminal, it works flawless and I'm able to extract the public key from an RSA private key
ssh-keygen -y -f /home/useraccount/private.txt > /home/useraccount/public.txt
But when I run the same command using Java it does not create public.txt file. It doesn't throw any error either.
Process p = Runtime.getRuntime().exec("ssh-keygen -y -f /home/useraccount/private.txt > /home/useraccount/public.txt");
p.waitFor();
I'm wondering why is that?
Not really an answer because I don't have to time to test but basic options:
// 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();