I'm trying to execute a gpg-command in Java to create a new Keypair, but I'm not getting an answer from the console. My code works well if I try to execute a gpg-command for the version gpg --version
or to retrieve the keylist with gpg --list-key
.
I'm using code from another Stackoverflow-Question:
public void getKeyList(){
try {
Process gpgProcess = Runtime.getRuntime().exec("gpg --gen-key");
BufferedReader gpgOutput = new BufferedReader(new InputStreamReader(gpgProcess.getInputStream()));
BufferedWriter gpgInput = new BufferedWriter(new OutputStreamWriter(gpgProcess.getOutputStream()));
BufferedReader gpgErrorOutput = new BufferedReader(new InputStreamReader(gpgProcess.getErrorStream()));
boolean executing = true;
while(executing){
try {
int exitValue = gpgProcess.exitValue();
if (gpgErrorOutput.ready()){
String error = getStreamText(gpgErrorOutput);
System.err.println(error);
}else if (gpgOutput.ready()){
System.out.println(getStreamText(gpgOutput));
}
} catch (Exception e){
//The process is not yet ready to exit. Take a break and try again.
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
System.err.println("This thread has insomnia: " + e1.getMessage());
}
}
}
} catch (IOException e){
e.printStackTrace();
}
}
private String getStreamText(BufferedReader reader) throws IOException{
StringBuilder result = new StringBuilder();
try{
while(reader.ready()){
result.append(reader.readLine());
if(reader.ready()){
result.append("\n");
}
}
}catch(IOException ioe){
System.err.println("Error while reading the stream: " + ioe.getMessage());
throw ioe;
}
return result.toString();
}
I've also tried ProcessBuilder
instead of Runtime
, but that's not the solution.
Do you have any idea on how to solve this problem, or is it totally impossible to interact with the console during the key-generation process?