PGP Encryption and Decryption Snippet

Converting public key to PGPpublickey in java:

(new JcaPGPKeyConverter().getPGPPublicKey(PGPPublicKey.RSA_GENERAL, <PublicKey object>, new Date()))

Converting Privatekey to PGPPrivatekey in java:

(new JcaPGPKeyConverter().getPGPPrivateKey(<PublicKey object>, <PrivateKey object>))

Certificate extenstions:

Application would support .CER or *.CRT certificate extensions

Encryption :

	public static void rsaEncryptFile(OutputStream out, String fileName,  PGPPublicKey encKey, boolean armor,
			boolean withIntegrityCheck)  {
		
		try {
			Security.addProvider(new BouncyCastleProvider());

			if (armor) {
				out = new ArmoredOutputStream(out);
				
			}

			ByteArrayOutputStream bOut = new ByteArrayOutputStream();
		

			PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);

			PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY,new File(fileName));
			

			comData.close();

			JcePGPDataEncryptorBuilder c = new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256)
					.setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC");

			PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(c);

			JcePublicKeyKeyEncryptionMethodGenerator d = new JcePublicKeyKeyEncryptionMethodGenerator(encKey)
					.setProvider(new BouncyCastleProvider()).setSecureRandom(new SecureRandom());

			cPk.addMethod(d);

			
			byte[] bytes = bOut.toByteArray();

			OutputStream cOut = cPk.open(out, bytes.length); 
			
			  cOut.write((bytes));
//			  bw.write(Base64.getEncoder().encodeToString(bytes));
//			  FileUtils.copyFile(new File("D:\\Development_Docs\\PGP\\Bulk\\plain-text-common.pgp"), cOut);
			
			  
			  
			  cOut.close();
			  out.close();
			 // bw.close();
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

Decryption :

	@SuppressWarnings("unchecked")
	public void rsaDecryptFile(InputStream in, OutputStream out, PGPPrivateKey priK)  {
		try {
			Security.addProvider(new BouncyCastleProvider());
			
			in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);
			PGPObjectFactory pgpF = new PGPObjectFactory(in);
			PGPEncryptedDataList enc;
			Object o = pgpF.nextObject();
			//
			// the first object might be a PGP marker packet.
			//
			if (o instanceof PGPEncryptedDataList) {
				enc = (PGPEncryptedDataList) o;
			} else {
				enc = (PGPEncryptedDataList) pgpF.nextObject();
			}

			//
			// find the secret key
			//
			Iterator<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects();
			PGPPrivateKey sKey = null;
			PGPPublicKeyEncryptedData pbe = null;

			while (sKey == null &amp;&amp; it.hasNext()) {
				pbe = it.next();
//				sKey = findSecretKey(pubK, pbe.getKeyID(), priK);
				sKey = priK;
				

			}

			if (sKey == null) {
				throw new IllegalArgumentException("Secret key for message not found.");
			}

			
			
			
			PublicKeyDataDecryptorFactory b = new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC")
					.setContentProvider("BC").build(sKey);

			InputStream clear = pbe.getDataStream(b);
			PGPObjectFactory plainFact = new PGPObjectFactory(clear);

			Object message = plainFact.nextObject();
			System.out.println("Secret key info 3:: " + pbe.getKeyID() + new Date());
			if (message instanceof PGPCompressedData) {
				PGPCompressedData cData = (PGPCompressedData) message;
				PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());

				message = pgpFact.nextObject();
			}
			
			if (message instanceof PGPLiteralData) {
				PGPLiteralData ld = (PGPLiteralData) message;
				InputStream unc = ld.getInputStream();
				int ch;
				

				
				/*
				 * while ((ch = unc.read()) >= 0) { out.write(ch); }
				 */
				 

				FileUtils.copyInputStreamToFile(unc, new File("D:\\Development_Docs\\PGP\\Bulk\\target.txt"));

				
			} else if (message instanceof PGPOnePassSignatureList) {
				throw new PGPException("Encrypted message contains a signed message - not literal data.");
			} else {
				throw new PGPException("Message is not a simple encrypted file - type unknown.");
			}
			

			if (pbe.isIntegrityProtected()) {
				if (!pbe.verify()) {
					throw new PGPException("Message failed integrity check");
				}
			}
			
			
		}catch (PGPException e) {
			// TODO: handle exception
			e.printStackTrace();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
	}

Leave a Comment