|
| 1 | +package com.baeldung.bouncycastle.pgp; |
| 2 | + |
| 3 | +import java.io.BufferedInputStream; |
| 4 | +import java.io.BufferedOutputStream; |
| 5 | +import java.io.FileInputStream; |
| 6 | +import java.io.FileOutputStream; |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.InputStream; |
| 9 | +import java.io.OutputStream; |
| 10 | +import java.nio.file.Path; |
| 11 | +import java.nio.file.Paths; |
| 12 | +import java.security.NoSuchProviderException; |
| 13 | +import java.security.SecureRandom; |
| 14 | +import java.security.Security; |
| 15 | +import java.util.Iterator; |
| 16 | + |
| 17 | +import org.bouncycastle.bcpg.ArmoredOutputStream; |
| 18 | +import org.bouncycastle.bcpg.CompressionAlgorithmTags; |
| 19 | +import org.bouncycastle.jce.provider.BouncyCastleProvider; |
| 20 | +import org.bouncycastle.openpgp.PGPCompressedData; |
| 21 | +import org.bouncycastle.openpgp.PGPEncryptedData; |
| 22 | +import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; |
| 23 | +import org.bouncycastle.openpgp.PGPEncryptedDataList; |
| 24 | +import org.bouncycastle.openpgp.PGPException; |
| 25 | +import org.bouncycastle.openpgp.PGPLiteralData; |
| 26 | +import org.bouncycastle.openpgp.PGPOnePassSignatureList; |
| 27 | +import org.bouncycastle.openpgp.PGPPrivateKey; |
| 28 | +import org.bouncycastle.openpgp.PGPPublicKey; |
| 29 | +import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; |
| 30 | +import org.bouncycastle.openpgp.PGPSecretKeyRingCollection; |
| 31 | +import org.bouncycastle.openpgp.PGPUtil; |
| 32 | +import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; |
| 33 | +import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; |
| 34 | +import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; |
| 35 | +import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; |
| 36 | +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; |
| 37 | +import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; |
| 38 | +import org.bouncycastle.util.io.Streams; |
| 39 | +import org.slf4j.Logger; |
| 40 | +import org.slf4j.LoggerFactory; |
| 41 | + |
| 42 | +public class BouncyCastlePGPDemoApplication { |
| 43 | + |
| 44 | + private static final Logger logger = LoggerFactory.getLogger(BouncyCastlePGPDemoApplication.class); |
| 45 | + |
| 46 | + static { |
| 47 | + Security.addProvider(new BouncyCastleProvider()); |
| 48 | + } |
| 49 | + |
| 50 | + public static void main(String[] args) { |
| 51 | + |
| 52 | + Path resourcesPath = Paths.get("src", "main", "resources"); |
| 53 | + String pgpresource = resourcesPath.resolve("pgp") |
| 54 | + .toAbsolutePath() |
| 55 | + .toString(); |
| 56 | + String pubKeyFileName = pgpresource + "/public_key.asc"; |
| 57 | + String encryptedFileName = pgpresource + "/EncryptedOutputFile.pgp"; |
| 58 | + String plainTextInputFileName = pgpresource + "/PlainTextInputFile.txt"; |
| 59 | + String privKeyFileName = pgpresource + "/private_key.asc"; |
| 60 | + |
| 61 | + try { |
| 62 | + encryptFile(encryptedFileName, plainTextInputFileName, pubKeyFileName, true); |
| 63 | + decryptFile(encryptedFileName, privKeyFileName, "baeldung".toCharArray(), "decryptedFile", true); |
| 64 | + } catch (NoSuchProviderException e) { |
| 65 | + logger.error(e.getMessage()); |
| 66 | + } catch (IOException e) { |
| 67 | + logger.error(e.getMessage()); |
| 68 | + } catch (PGPException e) { |
| 69 | + logger.error(e.getMessage()); |
| 70 | + } |
| 71 | + |
| 72 | + } |
| 73 | + |
| 74 | + public static void encryptFile(String outputFileName, String inputFileName, String pubKeyFileName, boolean armor) throws IOException, NoSuchProviderException, PGPException { |
| 75 | + |
| 76 | + OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName)); |
| 77 | + PGPPublicKey encKey = PGPExampleUtil.readPublicKey(pubKeyFileName); |
| 78 | + if (armor) { |
| 79 | + out = new ArmoredOutputStream(out); |
| 80 | + } |
| 81 | + try { |
| 82 | + byte[] bytes = PGPExampleUtil.compressFile(inputFileName, CompressionAlgorithmTags.ZIP); |
| 83 | + PGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setProvider("BC") |
| 84 | + .setSecureRandom(new SecureRandom()) |
| 85 | + .setWithIntegrityPacket(true); |
| 86 | + PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptorBuilder); |
| 87 | + encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC")); |
| 88 | + OutputStream cOut = encGen.open(out, bytes.length); |
| 89 | + cOut.write(bytes); |
| 90 | + cOut.close(); |
| 91 | + out.close(); |
| 92 | + } catch (PGPException e) { |
| 93 | + logger.error(e.getMessage()); |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + public static void decryptFile(String encryptedInputFileName, String privatekeyFileName, char[] passPhrase, String defaultFileName, boolean withIntegrityCheck) throws IOException, NoSuchProviderException { |
| 98 | + InputStream instream = new BufferedInputStream(new FileInputStream(encryptedInputFileName)); |
| 99 | + InputStream privateKeyInStream = new BufferedInputStream(new FileInputStream(privatekeyFileName)); |
| 100 | + instream = PGPUtil.getDecoderStream(instream); |
| 101 | + |
| 102 | + try { |
| 103 | + JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(instream); |
| 104 | + PGPEncryptedDataList enc; |
| 105 | + Object o = pgpF.nextObject(); |
| 106 | + // the first object might be a PGP marker packet. |
| 107 | + if (o instanceof PGPEncryptedDataList) { |
| 108 | + enc = (PGPEncryptedDataList) o; |
| 109 | + } else { |
| 110 | + enc = (PGPEncryptedDataList) pgpF.nextObject(); |
| 111 | + } |
| 112 | + Iterator it = enc.getEncryptedDataObjects(); |
| 113 | + PGPPrivateKey sKey = null; |
| 114 | + PGPPublicKeyEncryptedData pbe = null; |
| 115 | + PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateKeyInStream), new JcaKeyFingerprintCalculator()); |
| 116 | + while (sKey == null && it.hasNext()) { |
| 117 | + pbe = (PGPPublicKeyEncryptedData) it.next(); |
| 118 | + sKey = PGPExampleUtil.findSecretKey(pgpSec, pbe.getKeyID(), passPhrase); |
| 119 | + } |
| 120 | + if (sKey == null) { |
| 121 | + throw new IllegalArgumentException("secret key for message not found."); |
| 122 | + } |
| 123 | + InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC") |
| 124 | + .build(sKey)); |
| 125 | + JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear); |
| 126 | + Object message = plainFact.nextObject(); |
| 127 | + if (message instanceof PGPCompressedData) { |
| 128 | + PGPCompressedData cData = (PGPCompressedData) message; |
| 129 | + JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream()); |
| 130 | + message = pgpFact.nextObject(); |
| 131 | + } |
| 132 | + if (message instanceof PGPLiteralData) { |
| 133 | + PGPLiteralData ld = (PGPLiteralData) message; |
| 134 | + String outFileName = ld.getFileName(); |
| 135 | + outFileName = defaultFileName; |
| 136 | + InputStream unc = ld.getInputStream(); |
| 137 | + OutputStream fOut = new FileOutputStream(outFileName); |
| 138 | + Streams.pipeAll(unc, fOut); |
| 139 | + fOut.close(); |
| 140 | + } else if (message instanceof PGPOnePassSignatureList) { |
| 141 | + throw new PGPException("encrypted message contains a signed message - not literal data."); |
| 142 | + } else { |
| 143 | + throw new PGPException("message is not a simple encrypted file - type unknown."); |
| 144 | + } |
| 145 | + if (pbe.isIntegrityProtected() && pbe.verify()) { |
| 146 | + logger.error("message integrity check passed"); |
| 147 | + } else { |
| 148 | + logger.error("message integrity check failed"); |
| 149 | + } |
| 150 | + } catch (PGPException e) { |
| 151 | + logger.error(e.getMessage()); |
| 152 | + } |
| 153 | + privateKeyInStream.close(); |
| 154 | + instream.close(); |
| 155 | + } |
| 156 | +} |
0 commit comments