How to use PGP in Camel Routes

By how to

The Code

Camel is a powerful enterprise routing framework that can be used to send information any which way, with just about any protocol you'd want to use. And it's no secret how important encryption is, so using the two together just makes sense.

And now the code:

// Public Key FileName
final String keyFileName = "/path/to/public.gpg";
// Private Key FileName
final String keyFileNameSec = "/path/to/private.gpg";
// Keyring Userid Used to Encrypt
final String keyUserid = "userid_for_key";
// Private key password
final String keyPassword = "sooper_sekret_pass";

CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
    public void configure() {
      from("stream:in")
      .multicast().to("direct:original", "direct:encrypt");

      // Save the original input
      from("direct:original")
      .to("file:C:\\Users\\srobin\\Desktop\\crypto?fileName=original.txt");

      // Encrypts and saves the input
      from("direct:encrypt")
      .marshal().pgp(keyFileName, keyUserid)
      .multicast()
      .to("direct:unencrypt", "file:C:\\Users\\srobin\\Desktop\\crypto?fileName=encrypted.txt");

      // Decrypts and saves the output
      from("direct:unencrypt")
      .unmarshal().pgp(keyFileNameSec, keyUserid, keyPassword)
      .to("file:C:\\Users\\srobin\\Desktop\\crypto?fileName=unencrypted.txt");
    }
});

This simple example is mostly just a proof of concept to show how you might encrypt and decrypt data using PGP and Camel, but it gets the point across as to how you'd use it in a real system.

If you're using Maven, don't forget to add the following to your POM:

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-crypto</artifactId>
  <version>2.9.0</version>
</dependency>

Resources