mydew
mydew

Reputation: 57

Java Process streams

I have a problem with interacting with some terminal application (in my situation it is openSSL). I have a command to send and then this application wants password and reply given password. My code doesn't work. I mean that I don't see any output from it.

For testing I've made also simple application which is waiting for two strings to type and running it from my Java code works.

Have you any suggestions?

ProcessBuilder pb = new ProcessBuilder("openssl.exe");
    Process process = pb.start();

    final InputStream is = process.getInputStream();
    new Thread(new Runnable() {
        public void run() {
            try {
                BufferedReader reader =
                    new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }).start();


    OutputStream out = process.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

    writer.write("genrsa -des3 -out ca.key 512\n");
    writer.write("password\n");
    writer.write("password\n");
    writer.flush();

    writer.close();
    process.waitFor();

Upvotes: 0

Views: 257

Answers (1)

halfbit
halfbit

Reputation: 3464

I think, OpenSSL does not behave as you expect. I tried the following (on Linux):

echo $'genrsa -des3 -out xxx.key 512\npassword\npassword\n' \
    | openssl 2>stderr.txt 1>stdout.txt

It prompts me for two password entries on the terminal:

Enter pass phrase for xxx.key:
Verifying - Enter pass phrase for xxx.key:

Stdout.txt receives:

OpenSSL> OpenSSL> OpenSSL> OpenSSL> OpenSSL>

Stderr.txt receives:

Generating RSA private key, 512 bit long modulus
..........++++++++++++
...........++++++++++++
e is 65537 (0x10001)
openssl:Error: 'password' is an invalid command.
openssl:Error: 'password' is an invalid command.

This means that most of openssls output goes to stderr. It does not output newlines to stdout, so that reader.readLine() will never get a complete line. That is why you do not see any output. (Use read() instead. You might also need to read stderr to avoid blocking.)

OpenSSL always tries to get the password from the current terminal without echoing, not from stdin. Presenting them on stdin without special options causes interpretation as commands. For details and options you have see this discussion: Securely passing password to openssl via stdin

Upvotes: 1

Related Questions