Encrypting using gpg from Java

February 23, 2011

Recently, we worked with a third-party that had trouble reading files encrypted using the Bouncy Castle’s OpenPGP implementation. We ended up deciding to rely directly on the GNU Privacy Guard’s OpenPGP implementation. As I didn’t find any working example on the web, I figured that the following piece of code might end up being useful to someone one day. Enjoy.

byte[] encrypt(byte[] plain, String recipient) {
  try {
    ProcessBuilder pb = new ProcessBuilder(
      "--recipient", recipient,

    Process p = pb.start();

    int code = p.waitFor();
    if (code != 0) {
    throw new RuntimeException(format("encryption failed with code %s: %s", code,
      CharStreams.toString(new InputStreamReader(p.getErrorStream()))));
    return ByteStreams.toByteArray(p.getInputStream());
  } catch (IOException e) {
    throw new RuntimeException(e);
  } catch (InterruptedException e) {
    throw new RuntimeException(e);

CharStreams and ByteStreams are from Google Guava.

Obviously, the recipient key must be imported where this code will run. If the key cannot be found, you might have to set the --homedir argument manually when creating the ProcessBuilder.