byte[] encrypt(byte[] plain, String recipient) {
try {
ProcessBuilder pb = new ProcessBuilder(
"gpg",
"--no-tty",
"--batch",
"--yes",
"--always-trust",
"--recipient", recipient,
"--encrypt");
Process p = pb.start();
p.getOutputStream().write(plain);
p.getOutputStream().flush();
p.getOutputStream().close();
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.
engineering team!