Decrypting password encrypted pgp data in Java

OpenPGP provides the ability to also encrypt data with a password. This way we can decrypt it without using a private decryption key.

This chapter demonstrates how to decrypt password encrypted (PBE) OpenPGP data with Java.

List of examples

1. Decrypting a password encrypted OpenPGP file

2. Exception Handling

1. Decrypting a password encrypted OpenPGP file

In order to decrypt a password encrypted OpenPGP file, we must know the password it was encrypted with. The example below shows how to decrypt such file

import com.didisoft.pgp.PGPLib;
 
public class DecryptPBEFileDemo {
 public static void main(String[] args) throws Exception{
  // initialize the library instance
  PGPLib pgp = new PGPLib();
 
  String decryptionPassword = "changeit";
 
  // The decrypt method returns the original name of the file
  // that was encrypted. We can use it afterwards,
  // to rename OUTPUT.txt to it for example.		
  String originalFileName = 
     pgp.decryptFilePBE("examples/DataFiles/encrypted.pgp", 
		        decryptionPassword , 
                        "examples/DataFiles/OUTPUT.txt");
 }
}


2. Exception Handling

The method defines that it throws java.io.IOException and com.didisoft.pgp.PGPException.

We can extend the exception handling by catching a few subclasses of PGPException as is shown below:

import java.io.IOException;
import com.didisoft.pgp.*;
import com.didisoft.pgp.exceptions.*;
 
public class ExceptionHandlingDemo {
 public static void main(String[] a) {
   PGPLib pgp = new PGPLib();
   try {
    pgp.decrypt...
   } catch (IOException e) {
    // error reading input or writing output
   } catch (NonPGPDataException e) {
    // the passed encrypted input is not a valid OpenPGP archive
   } catch (IntegrityCheckException e) {
    // the passed encrypted input is corrupted
   } catch (FileIsEncryptedException e) {
    // the passed encrypted input is encrypted with a public key,
    // but we try to decrypt it with a password
   } catch (WrongPasswordException e) {
    // the provided password is wrong
   } catch (DetachedSignatureException e) {
    // the input is not an encrypted message, but a detached OpenPGP signature
   } catch (PGPException e) {
    // general decryption error not among the above ones 
   }
 }
}