How to do PGP encryption in Java?

How to do PGP encryption in Java?
Photo by Allec Gomes / Unsplash

In order to do PGP encryption, you need the PGP public key file. In this post I will tell how to encrypt data with PGP public key in Java.

Dependencies

Welcome to the home of the Legion of the Bouncy Castle. A fun place to stay, if you've got some time to kill.
bouncycastle.org
Home of open source libraries of the Legion of the Bouncy Castle and their Java cryptography and C# cryptography resources

https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on/1.70

The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms. This jar contains JCE provider and lightweight API for the Bouncy Castle Cryptography APIs for JDK 1.5 and up.

https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk15on/1.70

The Bouncy Castle Java APIs for CMS, PKCS, EAC, TSP, CMP, CRMF, OCSP, and certificate generation. This jar contains APIs for JDK 1.5 and up. The APIs can be used in conjunction with a JCE/JCA provider such as the one provided with the Bouncy Castle Cryptography APIs.

Read PGPPublicKey from file

Now we have The Bouncy Castle Java APIs, let's try to load the PGP public file into PGPPublicKey object.

The main idea is iterator the keys in the ring collection and find the key isEncryptionKey.

Encrypt Data

Key points:

PGPEncryptedDataGenerator::addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(pgpPublicKey));
PGPLiteralDataGenerator::open

That is it. Hope you find it helps.
I will write another post for PGP decryption.

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe