List of usage examples for org.bouncycastle.openpgp PGPPublicKeyEncryptedData getKeyID
public long getKeyID()
From source file:alpha.offsync.security.OpenPGPSecurityUtility.java
License:Apache License
@Override public void decrypt(final OutputStream outputStream, final InputStream inputStream) { try {/* www .j av a 2 s . c o m*/ final File keyFile = this.secretKeyRing; final char[] passwd = this.secretKeyRingPassword; final InputStream in = PGPUtil.getDecoderStream(inputStream); try { final PGPObjectFactory pgpF = new PGPObjectFactory(in); PGPEncryptedDataList enc; final Object o = pgpF.nextObject(); if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } final Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(new FileInputStream(keyFile))); while ((sKey == null) && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = this.findSecretKey(pgpSec, pbe.getKeyID(), passwd); } if (sKey == null) throw new IllegalArgumentException("secret key for message not found."); final InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey)); final PGPObjectFactory plainFact = new PGPObjectFactory(clear); final PGPCompressedData cData = (PGPCompressedData) plainFact.nextObject(); final InputStream compressedStream = new BufferedInputStream(cData.getDataStream()); final PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream); final Object message = pgpFact.nextObject(); if (message instanceof PGPLiteralData) { final PGPLiteralData ld = (PGPLiteralData) message; final InputStream unc = ld.getInputStream(); final OutputStream fOut = new BufferedOutputStream(outputStream); Streams.pipeAll(unc, fOut); fOut.close(); } 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."); } catch (final PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } } catch (final FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.arcusx.simplepgp.PgpDataDecryptor.java
public void decrypt(InputStream encryptedIn, InputStream privateKeyIn, InputStream publicKeyIn, OutputStream plainOut, boolean signatureRequired) throws PGPException, IOException { encryptedIn = PGPUtil.getDecoderStream(encryptedIn); try {/* w w w . j a v a 2s. com*/ JcaPGPObjectFactory pgpObjectFactory = new JcaPGPObjectFactory(encryptedIn); Object o = pgpObjectFactory.nextObject(); // // the first object might be a PGP marker packet. // PGPEncryptedDataList enc; if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpObjectFactory.nextObject(); } // // find the secret key // Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey privateKey = null; PGPPublicKeyEncryptedData publicKeyEncryptedData = null; PGPSecretKeyRingCollection privateKeyRingCollection = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(privateKeyIn), new JcaKeyFingerprintCalculator()); while (privateKey == null && it.hasNext()) { publicKeyEncryptedData = (PGPPublicKeyEncryptedData) it.next(); privateKey = findSecretKey(privateKeyRingCollection, publicKeyEncryptedData.getKeyID(), "".toCharArray()); } if (privateKey == null) { throw new IllegalArgumentException("Secret key for message not found."); } PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder() .setProvider("BC").build(privateKey); InputStream clearTextIn = publicKeyEncryptedData.getDataStream(decryptorFactory); PGPOnePassSignature onePassSignature = null; JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clearTextIn); Object message = pgpFact.nextObject(); if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; pgpFact = new JcaPGPObjectFactory(cData.getDataStream()); message = pgpFact.nextObject(); } if (message instanceof PGPOnePassSignatureList) { PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) message; onePassSignature = onePassSignatureList.get(0); message = pgpFact.nextObject(); } if (onePassSignature == null && signatureRequired) { throw new SecurityException("No signature object found."); } if (message instanceof PGPLiteralData) { PGPLiteralData literalData = (PGPLiteralData) message; InputStream literalDataIn = literalData.getInputStream(); PGPPublicKey publicKey = PgpKeyUtils.readPublicKey(publicKeyIn); if (onePassSignature != null) { onePassSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey); } int len = 0; byte[] buf = new byte[BUFFER_SIZE]; while ((len = literalDataIn.read(buf, 0, buf.length)) >= 0) { if (onePassSignature != null) { onePassSignature.update(buf, 0, len); } plainOut.write(buf, 0, len); } if (onePassSignature != null) { PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); PGPSignature signature = p3.get(0); if (!onePassSignature.verify(signature)) throw new PGPException("Signature invalid."); } plainOut.close(); } else { throw new PGPException("message is not a simple encrypted file - type unknown." + message); } if (!publicKeyEncryptedData.isIntegrityProtected()) throw new IllegalStateException("Message is not integrity protected."); if (!publicKeyEncryptedData.verify()) throw new IllegalStateException("Message is integrity protected but integrity check failed."); } catch (NoSuchProviderException ex) { throw new PGPException("Decryption failed.", ex); } finally { IOUtils.closeQuietly(encryptedIn); IOUtils.closeQuietly(privateKeyIn); IOUtils.closeQuietly(publicKeyIn); IOUtils.closeQuietly(plainOut); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Decrypt the specified (PKE) input file. * //from w w w . ja va 2 s.c o m * Either pubRing and secRing should be null, or pgpSecKey should be null, but not both. * * @param out * @param inFile * @param pubRing * @param secRing * @param pgpSecKey * @param encKey * @param passwd * @param mdcRequired * @throws PGPException */ private void decryptKeyBasedFile(OutputStream out, InputStream inFile, PGPPublicKeyRingCollection pubRing, PGPSecretKeyRingCollection secRing, PGPSecretKey pgpSecKey, char[] passwd, boolean mdcRequired) throws PGPException { try { InputStream fileToDecrypt = PGPUtil.getDecoderStream(inFile); PGPObjectFactory pgpFact = new PGPObjectFactory(fileToDecrypt); Object message = pgpFact.nextObject(); PGPPublicKeyEncryptedData pked = null; // PGPCompressedData cData; // Check for signed only if (!(message instanceof PGPCompressedData)) { // // Encrypted - the first object might be a PGP marker packet. // if (!(message instanceof PGPEncryptedDataList)) { message = pgpFact.nextObject(); if (!(message instanceof PGPEncryptedDataList)) { throw new PGPException("Unrecognised PGP message type: " + message.getClass()); } } PGPEncryptedDataList enc = (PGPEncryptedDataList) message; int count = 0; // find the secret key that is needed while (count != enc.size()) { if (enc.get(count) instanceof PGPPublicKeyEncryptedData) { pked = (PGPPublicKeyEncryptedData) enc.get(count); if (pgpSecKey == null) { pgpSecKey = secRing.getSecretKey(pked.getKeyID()); if (pgpSecKey != null) { break; } } else { if (pgpSecKey.getKeyID() == pked.getKeyID()) { break; } } } count++; } if (pgpSecKey == null) { throw new PGPException("Corresponding secret key not found"); } // Check for revoked key PGPPublicKey encKey = pgpSecKey.getPublicKey(); if (encKey == null) { encKey = findPublicKey(pubRing, pgpSecKey.getKeyID(), true); } if (encKey.isRevoked()) { String keyId = Long.toHexString(encKey.getKeyID()).substring(8); System.out.println("Warning: Encryption key (0x" + keyId + ") has been revoked"); // throw new PGPException("Encryption key (0x"+keyId+") has been revoked"); } InputStream clear = pked.getDataStream(pgpSecKey.extractPrivateKey(passwd, "BC"), "BC"); PGPObjectFactory pgpClearFact = new PGPObjectFactory(clear); message = pgpClearFact.nextObject(); if (message == null) { message = pgpFact.nextObject(); } // // cData = (PGPCompressedData) pgpFact.nextObject(); // } // else { // cData = (PGPCompressedData) message; } if (message instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) message; pgpFact = new PGPObjectFactory(compressedData.getDataStream()); message = pgpFact.nextObject(); } // Plain file if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; InputStream dataIn = ld.getInputStream(); int ch; while ((ch = dataIn.read()) >= 0) { out.write(ch); } out.close(); } else if (message instanceof PGPOnePassSignatureList) { // One-pass signature if (!checkOnePassSignature(out, (PGPOnePassSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed"); } System.out.println("Signature verified"); } else if (message instanceof PGPSignatureList) { // Signature list if (!checkSignature(out, (PGPSignatureList) message, pgpFact, pubRing)) { throw new PGPException("Signature verification failed"); } System.out.println("Signature verified"); } else { // what? // System.out.println("Unrecognised message type"); throw new PGPException("Unrecognised PGP message type: " + message.getClass()); } if (pked != null) { if (pked.isIntegrityProtected()) { if (!pked.verify()) { throw new PGPException("Message failed integrity check"); } if (_verbose) { System.out.println("Message integrity check passed"); } } else { if (_verbose) { System.out.println("No message integrity check"); } if (mdcRequired) { throw new PGPException("Missing required message integrity check"); } } } } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in decryption", e); } }
From source file:com.ginema.crypto.encryption.PGPEncryption.java
License:Apache License
/** * decrypt the passed in message stream/*from w ww . ja va 2 s. co m*/ * * @param encrypted The message to be decrypted. * @param passPhrase Pass phrase (key) * * @return Clear text as a byte array. I18N considerations are not handled by this routine * @exception IOException * @exception PGPException * @exception NoSuchProviderException */ @SuppressWarnings("unchecked") public static byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password) throws IOException, PGPException, NoSuchProviderException { InputStream in = PGPUtil.getDecoderStream(new ByteArrayInputStream(encrypted)); PGPObjectFactory pgpF = new PGPObjectFactory(in); PGPEncryptedDataList enc = null; 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; PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn)); while (sKey == null && it.hasNext()) { pbe = it.next(); sKey = findSecretKey(pgpSec, pbe.getKeyID(), password); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe.getDataStream(sKey, "BC"); PGPObjectFactory pgpFact = new PGPObjectFactory(clear); PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject(); pgpFact = new PGPObjectFactory(cData.getDataStream()); PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject(); InputStream unc = ld.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int ch; while ((ch = unc.read()) >= 0) { out.write(ch); } byte[] returnBytes = out.toByteArray(); out.close(); return returnBytes; }
From source file:com.google.e2e.bcdriver.Decryptor.java
License:Apache License
static final Result decrypt(InputStream in, PGPPrivateKey decryptKey, KeyChecker.PKR verify) throws IOException, PGPException, SignatureException { PGPObjectFactory pgpf = new PGPObjectFactory(PGPUtil.getDecoderStream(in), new BcKeyFingerprintCalculator()); Object o = pgpf.nextObject(); if (o == null) { throw new IOException("No encrypted content"); }/*from w ww. j a v a2s.c o m*/ PGPEncryptedDataList enclist; if (o instanceof PGPEncryptedDataList) { enclist = (PGPEncryptedDataList) o; } else { enclist = (PGPEncryptedDataList) (pgpf.nextObject()); } Iterator<PGPPublicKeyEncryptedData> pkedi = Util.getTypedIterator(enclist.getEncryptedDataObjects(), PGPPublicKeyEncryptedData.class); if (pkedi == null) { throw new IOException("no encrypted data found!"); } while (pkedi.hasNext()) { PGPPublicKeyEncryptedData pked = pkedi.next(); if (pked.getKeyID() == decryptKey.getKeyID()) { return decryptSignedContent(pked, decryptKey, verify); } } return null; }
From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java
License:Apache License
/** * @param encryptedStream The stream of data that can be decrypted with the private key. * @param privateKeyFile The file that contains the private key that can decrypt the stream data. * * @return a private key required to decrypt the given stream from file. * * @throws IOException/* w w w . j ava2 s . co m*/ * @throws PGPException */ @Nullable public static PGPSecretKey getPrivateKeyFor(final InputStream encryptedStream, final File privateKeyFile) throws IOException, PGPException { /* Open the encrypted file. */ InputStream encryptedDataStream = PGPUtil.getDecoderStream(encryptedStream); PGPObjectFactory encryptedDataFactory = new PGPObjectFactory(encryptedDataStream); /* The first object might be a PGP marker packet. */ Object encryptedDataObjects = encryptedDataFactory.nextObject(); if (!(encryptedDataObjects instanceof PGPEncryptedDataList)) encryptedDataObjects = encryptedDataFactory.nextObject(); @SuppressWarnings("unchecked") Iterator<PGPPublicKeyEncryptedData> encryptedDataIterator = ((PGPEncryptedDataList) encryptedDataObjects) .getEncryptedDataObjects(); /* Extract the public key out of the data and find the matching private key required to decrypt the data. */ PGPSecretKey privateKey = null; while (privateKey == null && encryptedDataIterator.hasNext()) { PGPPublicKeyEncryptedData encryptedData = encryptedDataIterator.next(); privateKey = getPrivateKey(privateKeyFile, encryptedData.getKeyID()); } return privateKey; }
From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java
License:Apache License
/** * Decrypt a PGP encrypted stream.//w w w . jav a 2 s . c o m * * @param encryptedStream The stream that contains the encrypted data. * @param privateKey The private key to use for decrypting the data. * @param passPhrase The passphrase the private key is encrypted with. * * @return The plain-text stream. * * @throws NoSuchProviderException * @throws IOException * @throws PGPException */ public static InputStream decrypt(final InputStream encryptedStream, final PGPSecretKey privateKey, final String passPhrase) throws IOException, PGPException, NoSuchProviderException { /* Open the encrypted file. */ InputStream encryptedDataStream = PGPUtil.getDecoderStream(encryptedStream); PGPObjectFactory encryptedDataFactory = new PGPObjectFactory(encryptedDataStream); /* Find the PGP encrypted data. */ Object encryptedDataObjects = null; do try { encryptedDataObjects = encryptedDataFactory.nextObject(); } catch (final IOException e) { logger.warn(e.getMessage()); } while (!(encryptedDataObjects instanceof PGPEncryptedDataList) && encryptedDataObjects != null); if (encryptedDataObjects == null) throw new PGPException("No encrypted objects found."); @SuppressWarnings("unchecked") Iterator<PGPPublicKeyEncryptedData> encryptedDataIterator = ((PGPEncryptedDataList) encryptedDataObjects) .getEncryptedDataObjects(); /* Extract the public key out of the data and find the matching private key required to decrypt the data. */ PGPPublicKeyEncryptedData encryptedData = null; while (encryptedDataIterator.hasNext()) { encryptedData = encryptedDataIterator.next(); if (encryptedData.getKeyID() == privateKey.getKeyID()) break; } if (encryptedData == null) throw new PGPException("No encrypted data found."); /* Decrypt the data. */ InputStream unencryptedStream = encryptedData.getDataStream( privateKey.extractPrivateKey(passPhrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME), BouncyCastleProvider.PROVIDER_NAME); PGPObjectFactory pgpFactory = new PGPObjectFactory(unencryptedStream); Object unencryptedObject = pgpFactory.nextObject(); /* Possibly decompress the decrypted data. */ if (unencryptedObject instanceof PGPCompressedData) { PGPCompressedData compressedData = (PGPCompressedData) unencryptedObject; pgpFactory = new PGPObjectFactory(compressedData.getDataStream()); unencryptedObject = pgpFactory.nextObject(); } /* Verify integrity. */ if (encryptedData.isIntegrityProtected() && !encryptedData.verify()) throw new PGPException("Message integrity check failed."); /* Check to see if the data is valid decrypted data. */ if (unencryptedObject == null) throw new PGPException("No encrypted data found."); if (unencryptedObject instanceof PGPOnePassSignatureList) throw new PGPException("Encrypted data is a signature, not an encrypted message."); if (!(unencryptedObject instanceof PGPLiteralData)) throw new PGPException("Message type unrecognized: " + unencryptedObject.getClass()); /* Write out decrypted data. */ PGPLiteralData unencryptedData = (PGPLiteralData) unencryptedObject; return unencryptedData.getInputStream(); }
From source file:com.simple.sftpfetch.decrypt.PGPFileDecrypter.java
License:Apache License
/** * Get the matching PGPPrivateKey for the given public key encrypted data * * @param sKey private key information//from w w w .j a va 2s.co m * @param pbe public key encrypted data * * @return the matching PGPPrivateKey * * @throws PGPException * @throws NoSuchProviderException */ private PGPPrivateKey getPrivateKey(PGPPrivateKey sKey, PGPPublicKeyEncryptedData pbe) throws PGPException, NoSuchProviderException { PGPSecretKey pgpSecKey = pgpSec.getSecretKey(pbe.getKeyID()); if (pgpSecKey != null) { sKey = pgpSecKey.extractPrivateKey(new char[] {}, "BC"); } return sKey; }
From source file:eu.mrbussy.security.crypto.pgp.PGPDecryptor.java
License:Open Source License
public InputStream decryptFile(InputStream in) throws Exception { InputStream is = null;// ww w . ja v a2 s. c o m byte[] bytes = null; InputStream keyIn = new FileInputStream(new File(privateKeyFilePath)); char[] passwd = password.toCharArray(); in = 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 && it.hasNext()) { pbe = it.next(); sKey = PGPUtils.findPrivateKey(keyIn, pbe.getKeyID(), passwd); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe.getDataStream(sKey, "BC"); PGPObjectFactory plainFact = new PGPObjectFactory(clear); Object message = plainFact.nextObject(); PGPObjectFactory pgpFact = null; if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; pgpFact = new PGPObjectFactory(cData.getDataStream()); message = pgpFact.nextObject(); } PGPOnePassSignature ops = null; if (message instanceof PGPOnePassSignatureList) { if (isSigned) { PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) message; ops = p1.get(0); long keyId = ops.getKeyID(); PGPPublicKey signerPublicKey = PGPUtils.readPublicKey(signingPublicKeyFilePath, keyId); ops.initVerify(signerPublicKey, "BC"); } message = pgpFact.nextObject(); } if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; if (pbe.isIntegrityProtected()) { if (!pbe.verify()) { throw new PGPException("message failed integrity check"); } } is = ld.getInputStream(); bytes = IOUtils.toByteArray(is); if (isSigned) { ops.update(bytes); PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject(); if (!ops.verify(p3.get(0))) { throw new PGPException("Signature verification failed!"); } } } else { throw new PGPException("message is not a simple encrypted file - type unknown."); } return new ByteArrayInputStream(bytes); }
From source file:google.registry.rde.BouncyCastleTest.java
License:Open Source License
@Test public void testEncryptDecrypt_ExplicitStyle() throws Exception { int bufferSize = 64 * 1024; // Alice loads Bob's "publicKey" into memory. PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); // Alice encrypts the secret message for Bob using his "publicKey". PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(AES_128)); encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey)); byte[] encryptedData; try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) { output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8)); }/*from w w w.j a v a 2 s .c o m*/ encryptedData = output.toByteArray(); } logger.info("Encrypted data: " + dumpHex(encryptedData)); // Bob loads his "privateKey" into memory. PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY); PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey()); // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey". try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) { PGPObjectFactory pgpFact = new BcPGPObjectFactory(input); PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject(); assertThat(encDataList.size()).isEqualTo(1); PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0); assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID()); assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID()); try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) { assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8))) .isEqualTo(FALL_OF_HYPERION_A_DREAM); } } }