Dependencies
1 2 3 4 5 | <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpg-jdk15on</artifactId> <version>1.54</version> </dependency> |
The Util Class
This is the main util class which will do all the encryption and decryption. I've named it SimplePgpUtil, you can name it however you want.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Security; import java.util.Iterator; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.sig.KeyFlags; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPCompressedData; import org.bouncycastle.openpgp.PGPCompressedDataGenerator; import org.bouncycastle.openpgp.PGPEncryptedData; import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; import org.bouncycastle.openpgp.PGPEncryptedDataList; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPLiteralDataGenerator; import org.bouncycastle.openpgp.PGPObjectFactory; import org.bouncycastle.openpgp.PGPOnePassSignatureList; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKeyRingCollection; import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.PGPSignatureSubpacketVector; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; import org.bouncycastle.openpgp.operator.bc.BcPublicKeyDataDecryptorFactory; import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; public class SimplePgpUtil { // private static final int BUFFER_SIZE = 1 << 16; // should always be power // of 2 private static final int KEY_FLAGS = 27; private static final int[] MASTER_KEY_CERTIFICATION_TYPES = new int[] { PGPSignature.POSITIVE_CERTIFICATION, PGPSignature.CASUAL_CERTIFICATION, PGPSignature.NO_CERTIFICATION, PGPSignature.DEFAULT_CERTIFICATION }; public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException { PGPPublicKeyRingCollection keyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(in), new BcKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for // encryption, in the real // world you would probably want to be a bit smarter about this. // PGPPublicKey publicKey = null; // // iterate through the key rings. // Iterator<PGPPublicKeyRing> rIt = keyRingCollection.getKeyRings(); while (publicKey == null && rIt.hasNext()) { PGPPublicKeyRing kRing = rIt.next(); Iterator<PGPPublicKey> kIt = kRing.getPublicKeys(); while (publicKey == null && kIt.hasNext()) { PGPPublicKey key = kIt.next(); if (key.isEncryptionKey()) { publicKey = key; } } } if (publicKey == null) { throw new IllegalArgumentException("Can't find public key in the key ring."); } if (!isForEncryption(publicKey)) { throw new IllegalArgumentException("KeyID " + publicKey.getKeyID() + " not flagged for encryption."); } return publicKey; } public static void encryptStream(OutputStream out, PGPPublicKey encKey, InputStream streamData) throws IOException, PGPException { Security.addProvider(new BouncyCastleProvider()); out = new ArmoredOutputStream(out); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); writeStreamToLiteralData(comData.open(bOut), PGPLiteralDataGenerator.BINARY, PGPLiteralData.CONSOLE, streamData); comData.close(); BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES); dataEncryptor.setWithIntegrityPacket(true); dataEncryptor.setSecureRandom(new SecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey)); byte[] bytes = bOut.toByteArray(); OutputStream cOut = encryptedDataGenerator.open(out, bytes.length); cOut.write(bytes); cOut.close(); out.close(); } /** * decrypt the passed in message stream */ @SuppressWarnings("unchecked") public static void decryptFile(InputStream in, OutputStream out, InputStream keyIn, char[] passwd) throws Exception { Security.addProvider(new BouncyCastleProvider()); in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in); PGPObjectFactory pgpF = new PGPObjectFactory(in, new BcKeyFingerprintCalculator()); 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 && it.hasNext()) { pbe = it.next(); sKey = findPrivateKey(keyIn, pbe.getKeyID(), passwd); } if (sKey == null) { throw new IllegalArgumentException("Secret key for message not found."); } InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey)); PGPObjectFactory plainFact = new PGPObjectFactory(clear, new BcKeyFingerprintCalculator()); Object message = plainFact.nextObject(); if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream(), new BcKeyFingerprintCalculator()); 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); } } 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"); } } } /** * Load a secret key ring collection from keyIn and find the private key * corresponding to keyID if it exists. * * @param keyIn * input stream representing a key ring collection. * @param keyID * keyID we want. * @param pass * passphrase to decrypt secret key with. * @return * @throws IOException * @throws PGPException * @throws NoSuchProviderException */ public static PGPPrivateKey findPrivateKey(InputStream keyIn, long keyID, char[] pass) throws IOException, PGPException, NoSuchProviderException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator()); return findPrivateKey(pgpSec.getSecretKey(keyID), pass); } /** * Load a secret key and find the private key in it * * @param pgpSecKey * The secret key * @param pass * passphrase to decrypt secret key with * @return * @throws PGPException */ public static PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecKey, char[] pass) throws PGPException { if (pgpSecKey == null) return null; PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()) .build(pass); return pgpSecKey.extractPrivateKey(decryptor); } public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck) throws IOException, NoSuchProviderException, PGPException { 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(); BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES); dataEncryptor.setWithIntegrityPacket(withIntegrityCheck); dataEncryptor.setSecureRandom(new SecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey)); byte[] bytes = bOut.toByteArray(); OutputStream cOut = encryptedDataGenerator.open(out, bytes.length); cOut.write(bytes); cOut.close(); out.close(); } private static void writeStreamToLiteralData(OutputStream os, char fileType, String name, InputStream streamData) throws IOException { int bufferLength = 2048; byte[] buff = new byte[bufferLength]; PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(); OutputStream pOut = lData.open(os, fileType, name, PGPLiteralData.NOW, buff); byte[] buffer = new byte[bufferLength]; int len; while ((len = streamData.read(buffer)) > 0) { pOut.write(buffer, 0, len); } pOut.close(); } @SuppressWarnings("deprecation") public static boolean isForEncryption(PGPPublicKey key) { if (key.getAlgorithm() == PublicKeyAlgorithmTags.RSA_SIGN || key.getAlgorithm() == PublicKeyAlgorithmTags.DSA || key.getAlgorithm() == PublicKeyAlgorithmTags.EC || key.getAlgorithm() == PublicKeyAlgorithmTags.ECDSA) { return false; } return hasKeyFlags(key, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE); } @SuppressWarnings("unchecked") private static boolean hasKeyFlags(PGPPublicKey encKey, int keyUsage) { if (encKey.isMasterKey()) { for (int i = 0; i != SimplePgpUtil.MASTER_KEY_CERTIFICATION_TYPES.length; i++) { for (Iterator<PGPSignature> eIt = encKey .getSignaturesOfType(SimplePgpUtil.MASTER_KEY_CERTIFICATION_TYPES[i]); eIt.hasNext();) { PGPSignature sig = eIt.next(); if (!isMatchingUsage(sig, keyUsage)) { return false; } } } } else { for (Iterator<PGPSignature> eIt = encKey.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); eIt.hasNext();) { PGPSignature sig = eIt.next(); if (!isMatchingUsage(sig, keyUsage)) { return false; } } } return true; } private static boolean isMatchingUsage(PGPSignature sig, int keyUsage) { if (sig.hasSubpackets()) { PGPSignatureSubpacketVector sv = sig.getHashedSubPackets(); if (sv.hasSubpacket(SimplePgpUtil.KEY_FLAGS)) { if (sv.getKeyFlags() == 0 && keyUsage == 0) { return false; } } } return true; } } |
Usage
Here is how to encrypt the file. You'll still need a physical key file, with you can generate it with PGP command line util. The example below encrypt it directly to a ByteArrayOutputStream out which you'll be able convert it to string. Bear in mind this I've hardcode in the Util class to always encrypt it in armored output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | private String encryptMessage(String data) throws IOException, PGPException { //the private key file InputStream fis = this.getClass().getResourceAsStream("/path/to/key/file.id"); ByteArrayOutputStream out = new ByteArrayOutputStream(); //convert the data to input stream InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); //encrypt it! SimplePgpUtil.encryptStream(out, SimplePgpUtil.readPublicKey(fis), stream); //close all the stream out.close(); stream.close(); return new String(out.toByteArray()); } |
Here is how the encryptedData looks like in string. Which is easier to send it over thru any type of transport, i.e. email/network/chat/etc
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | -----BEGIN PGP MESSAGE----- Version: BCPG v1.54 hQIOA/ZYUvF+8XJLEAgAi3GaSWFy3pqwojmqgDhP1D76elrcmhhzMAuMalR2CJop K7+iBqv7d4hyz8UnTHVkm00RvraqRxftyzgtxpzQ0wI13/k03ZTH+4mcnEk0s98d 2bKkxKXmvADQ8u7cSxR+Xp2vVR0OZ6AGVWphkjwrRG0CJ8T6aVj0aHXyYZUpJY9a UQqp3X2ZljRPq68bKotOTGYcddlWd1HohUJpMr0a+SF+jBwm9HEj7+8JpuCs4g0B KG++SswNK968EskS8tL9mVGxWjpMVt3Za6BLp4Ma9WXpozAI7PLZutqF8kYqfyXD eXTvxIBzGXnOA678DlR7Y4MDuWqPSP71TJq5cptDcwgAibHYZ1ISE9awnomrYiLW InGokP0t8Ns2Ulx2Kp3UJ/LNuNDDXfH8ki0THB+xpKAXUgbAEaSAta4H8PpYLROH iANw+xvs5lxIAN3Xym7alSzbt14j+RGu4r0b1PE3lwGa2U4mYjOCKY0HUbztg0YZ Rp7yOsqsjEfz29YwckPqZsfxmwBmKwploDIvFJeFw9JUIGSsStfuLyiPkjToDtJB L+zgFOqzAufQ1E7j4V+Pmk8BNCCF9i1qISctGibZVQJBjiphIC12JUIc6qazaLeK E/aketdvMTrjiZF8NMTRMrh/MUN/l6O+h0SEsV1gBhi4sjvj9E+FKE57DW5iCR+m wNLBYgGWMtisTeacGfljIDnTloT1XMed31TH6ot7M9enJVCUpawMvbZ6NKoLZvOn uEYE1pNOFZZz6LTdhWMU85hnKocOXsExd2u0NTRx57TWwx4/aOsRNHTdGfUS4Nlt 2tK+ISxaij29tDv8IfzmxUHxdAuoFEVdBVtob3suaDS5GMtx9K7tFxVm91j/GELT v4Rnqi3l6j18+dETxR9aPoAWkQFOHHQ0rsfwrclNoOR0Rih5UVSYWO/clWGt+lIO 79mW9d27SkBEdMvkgreLXpY4DFO0sGIRXwxfNxn3K9CRZVkT/0mBHFgbyjjmN8a2 zeS+sBXpyztwpV1YZE3lIb01SeKQls7nZGZHep48Qf4fsoKgpwgC8ngSSr+f9uZm M/6IoTU90b5I2HRKsYvA3ZhLGm+12kjIiSQ7Uqgo7MuIUesdtzFGGgwIjVovMTWI mScZilmq2QbgbSpGstR4I+dovpepQMsrETe/Kad7rtYjv19V+ctziuLJTEa/qfCN Kp2ZJ0iFvXAcjARKAkkvBGNF8RvQX6ZGmjso0la7tolpvYyacaC4gRWA31WiKq80 gg4ffgh8ZJT4Md4KoY9BafjZgXqke0crjRoIX7WtZrpkhoVyqgmbsvRe8cm2eY1W pSgFjW/DoFYohxv005niIX8fwXvUZbZMf3Mjrww71F+HwpxoOaiPTU2eKi4Nfi+i Kc+3pawfSOemrlnJyT5JQI9QBTXeKg== =SqcE -----END PGP MESSAGE----- |
Here is how decrypt the file. You'll need a public key file. The key should be provided by the owner. Again, the encrypted message should be in armored format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private String decryptMessage(String message) throws IOException, PGPException { //trim it, just to be safe message = message.trim(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); //convert encrypted message to input stream ByteArrayInputStream bais = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)); //public key file InputStream fis = this.getClass().getResourceAsStream("/path/to/public/key/file.key"); // the real action. 'password1' is the passphrase SimplePgpUtil.decryptFile(bais, baos, fis, new String("password1").toCharArray()); //close all the stream baos.close(); bais.close(); fis.close(); //return the decrypted message return new String(baos.toByteArray()); } |
That's it.
org.bouncycastle.openpgp.PGPException: org.bouncycastle.openpgp.PGPPublicKeyRing found where PGPSecretKeyRing expected got this.any help is appreciated.
ReplyDeleteThanks.
In decrypting the file Object o givers instanceOf PGPEncryptedDataList as always null(line 135). I have tried looking for answers but unable to solve it.
ReplyDeleteAdded JCE certificates in lib as written in one of the solutions and nothing seems to be working.
Any help would be highly appreciated.