Search code examples
javalinuxunixgpgpugnupg

Running command for Linux from Java runtime


Can anyone help me how to run a gpg encryption command from a java program using Runtime.getRuntime().exec()?

sample command which I wanted to run shown below:

gpg -u 'receipient' -r KeyID --armor --output /home/myuser/tmp/check.pgp --sign --passphrase '&sw@217' --batch --encrypt /home/myuser/tmp/check.txt*

When I try to execute this from my Java program it gives error like "usage: gpg [options] [filename]"

Please help on resolving this error and run the above gpg command from a java program.


Solution

  • The following code should solve your problem if the gpg binary is correctly installed on your host.

    Process p = new ProcessBuilder("gpg -u 'receipient' -r KeyID --armor --output /home/myuser/tmp/check.pgp --sign --passphrase '&sw@217' --batch --encrypt /home/myuser/tmp/check.txt*".split(" "))
    .inheritIO()
    .start();
    
    p.waitFor();
    

    I haven't the correct settings but this code runs as expected. You can try it here: https://tech.io/snippet/VzJtME0