PGP Encryption and Decryption with Java [closed]

You can write a simple wrapper around GNU PGP which basically executes the GPG command from Java.

The advantage of using GNU PGP is that you will not be tied to a specific library. The amount of documentation and support available online for third-party libraries is not as rich as other encryption schemes since most invoke PGP from command-line. The PGP keys will also stay in one common place i.e. the user specific key ring rather than exported in multiple files.

The GPG command for decryption is

echo "password" | gpg --passphrase-fd 0 --output plaintext.txt --decrypt encrypted.gpg

By specifying passphrase-fd as 0 you can provide the password through the standard input stream.

Here is how the Java code looks like –

public static void decryptFile(String privKeyPass) {
    String[] cmd = new String[];
    int i = 7;
    cmd[i++] = "gpg";
    cmd[i++] = "--passphrase-fd";
    cmd[i++] = "0";
    cmd[i++] = "--output";
    cmd[i++] = "plaintext.txt";
    cmd[i++] = "--decrypt";
    cmd[i++] = "encrypted.gpg";
    Process process = Runtime.getRuntime().exec(cmd);

    BufferedWriterout = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    out.write(privKeyPass);
    try {
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
   // Read process.getInputStream()
   // Read process.getErrorStream()
}

Leave a Comment