I want to decrypt a file using PGP keys.
I have downloaded PGP keys installer and installed. Using that I created a text file and encrypted the text file using PGP keys.
Then I got a .pgp extension file which is encrypted. Now I want to decrypt the same file using Java code using PGP.
In Java, How do I decrypt a text file which is already encrypted using PGP keys?
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()
}