List of usage examples for org.bouncycastle.openpgp.operator.jcajce JcePublicKeyDataDecryptorFactoryBuilder JcePublicKeyDataDecryptorFactoryBuilder
public JcePublicKeyDataDecryptorFactoryBuilder()
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 {// www . j a v a 2s. c o m 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.goodvikings.cryptim.api.KeyRing.java
License:BEER-WARE LICENSE
public boolean decryptVerifyMessage(InputStream in, OutputStream out, String jid) throws IOException, PGPException, SignatureException { in = new ArmoredInputStream(in); PGPObjectFactory plainFact = new PGPObjectFactory( ((PGPPublicKeyEncryptedData) ((PGPEncryptedDataList) new PGPObjectFactory(in).nextObject()) .getEncryptedDataObjects().next()) .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(PROVIDER) .build(kp.getPrivateKey()))); PGPOnePassSignatureList onePassSignatureList = null; PGPSignatureList signatureList = null; PGPCompressedData compressedData = null; Object obj = plainFact.nextObject(); ByteArrayOutputStream actualOutput = new ByteArrayOutputStream(); while (obj != null) { if (obj instanceof PGPCompressedData) { compressedData = (PGPCompressedData) obj; plainFact = new PGPObjectFactory(compressedData.getDataStream()); obj = plainFact.nextObject(); }/*from w ww .j a v a 2s . c om*/ if (obj instanceof PGPLiteralData) { Streams.pipeAll(((PGPLiteralData) obj).getInputStream(), actualOutput); } else if (obj instanceof PGPOnePassSignatureList) { onePassSignatureList = (PGPOnePassSignatureList) obj; } else if (obj instanceof PGPSignatureList) { signatureList = (PGPSignatureList) obj; } else { throw new PGPException("message unknown message type."); } obj = plainFact.nextObject(); } actualOutput.close(); byte[] output = actualOutput.toByteArray(); PGPOnePassSignature ops = onePassSignatureList.get(0); ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER), keys.get(jid)); ops.update(output); out.write(output); out.flush(); out.close(); return ops.verify(signatureList.get(0)); }
From source file:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java
/** * decrypt the passed in message stream/*from ww w . ja v a 2s . co m*/ */ private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName) throws IOException, NoSuchProviderException { in = PGPUtil.getDecoderStream(in); try { JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(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 it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator()); while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = MyPGPUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey)); JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear); Object message = plainFact.nextObject(); if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream()); message = pgpFact.nextObject(); } if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; String outFileName = ld.getFileName(); if (outFileName.length() == 0) { outFileName = defaultFileName; } else { /** * modify 20160520 set fileName ???????? */ String separator = ""; if (outFileName.contains("/")) { separator = "/"; } else if (outFileName.contains("\\")) { separator = "\\"; } String fileName = outFileName.substring(outFileName.lastIndexOf(separator) + 1); // String defseparator = ""; if (defaultFileName.contains("/")) { defseparator = "/"; } else if (defaultFileName.contains("\\")) { defseparator = "\\"; } defaultFileName = defaultFileName.substring(0, defaultFileName.lastIndexOf(defseparator)); outFileName = defaultFileName + File.separator + fileName; } InputStream unc = ld.getInputStream(); OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName)); 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."); } if (pbe.isIntegrityProtected()) { if (!pbe.verify()) { System.err.println("message failed integrity check"); } else { System.err.println("message integrity check passed"); } } else { System.err.println("no message integrity check"); } } catch (PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } }
From source file:org.apache.camel.converter.crypto.PGPDataFormat.java
License:Apache License
@SuppressWarnings("resource") public Object unmarshal(Exchange exchange, InputStream encryptedStream) throws Exception { if (encryptedStream == null) { return null; }/*from w ww . j a v a 2 s .c o m*/ InputStream in = PGPUtil.getDecoderStream(encryptedStream); PGPObjectFactory pgpFactory = new PGPObjectFactory(in); Object o = pgpFactory.nextObject(); // the first object might be a PGP marker packet PGPEncryptedDataList enc; if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpFactory.nextObject(); } PGPPublicKeyEncryptedData pbe = null; PGPPrivateKey key = null; // find encrypted data for which a private key exists in the secret key ring for (int i = 0; i < enc.size() && key == null; i++) { pbe = (PGPPublicKeyEncryptedData) enc.get(i); key = PGPDataFormatUtil.findPrivateKeyWithKeyId(exchange.getContext(), findKeyFileName(exchange), findEncryptionKeyRing(exchange), pbe.getKeyID(), findKeyPassword(exchange), getPassphraseAccessor(), getProvider()); } if (key == null) { throw new PGPException("Provided input is encrypted with unknown pair of keys."); } InputStream encData = pbe .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(getProvider()).build(key)); pgpFactory = new PGPObjectFactory(encData); PGPCompressedData comData = (PGPCompressedData) pgpFactory.nextObject(); pgpFactory = new PGPObjectFactory(comData.getDataStream()); Object object = pgpFactory.nextObject(); PGPOnePassSignature signature; if (object instanceof PGPOnePassSignatureList) { signature = getSignature(exchange, (PGPOnePassSignatureList) object); object = pgpFactory.nextObject(); } else { signature = null; } PGPLiteralData ld = (PGPLiteralData) object; InputStream litData = ld.getInputStream(); // enable streaming via OutputStreamCache CachedOutputStream cos; ByteArrayOutputStream bos; OutputStream os; if (exchange.getContext().getStreamCachingStrategy().isEnabled()) { cos = new CachedOutputStream(exchange); bos = null; os = cos; } else { cos = null; bos = new ByteArrayOutputStream(); os = bos; } try { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = litData.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); if (signature != null) { signature.update(buffer, 0, bytesRead); } os.flush(); } } finally { IOHelper.close(os, litData, encData, in); } if (signature != null) { PGPSignatureList sigList = (PGPSignatureList) pgpFactory.nextObject(); if (!signature.verify(getSignatureWithKeyId(signature.getKeyID(), sigList))) { throw new SignatureException("Cannot verify PGP signature"); } } if (cos != null) { return cos.newStreamCache(); } else { return bos.toByteArray(); } }
From source file:org.apache.camel.converter.crypto.PGPKeyAccessDataFormat.java
License:Apache License
private InputStream getDecryptedData(Exchange exchange, InputStream encryptedStream) throws Exception, PGPException { PGPObjectFactory pgpFactory = new PGPObjectFactory(encryptedStream); Object firstObject = pgpFactory.nextObject(); // the first object might be a PGP marker packet PGPEncryptedDataList enc = getEcryptedDataList(pgpFactory, firstObject); if (enc == null) { throw getFormatException(); }/*from w w w . j ava 2 s .c o m*/ PGPPublicKeyEncryptedData pbe = null; PGPPrivateKey key = null; // find encrypted data for which a private key exists in the secret key ring for (int i = 0; i < enc.size() && key == null; i++) { Object encryptedData = enc.get(i); if (!(encryptedData instanceof PGPPublicKeyEncryptedData)) { throw getFormatException(); } pbe = (PGPPublicKeyEncryptedData) encryptedData; key = secretKeyAccessor.getPrivateKey(exchange, pbe.getKeyID()); if (key != null) { // take the first key break; } } if (key == null) { throw new PGPException( "PGP message is encrypted with a key which could not be found in the Secret Keyring."); } InputStream encData = pbe .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(getProvider()).build(key)); return encData; }
From source file:org.apache.gobblin.crypto.GPGFileDecryptor.java
License:Apache License
/** * Taking in a file inputstream, keyring inputstream and a passPhrase, generate a decrypted file inputstream. * @param inputStream file inputstream/*from ww w .j a v a 2s . com*/ * @param keyIn keyring inputstream. This InputStream is owned by the caller. * @param passPhrase passPhrase * @return an {@link InputStream} for the decrypted content * @throws IOException */ public InputStream decryptFile(InputStream inputStream, InputStream keyIn, String passPhrase) throws IOException { try { PGPEncryptedDataList enc = getPGPEncryptedDataList(inputStream); Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator()); while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = findSecretKey(pgpSec, pbe.getKeyID(), passPhrase); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(sKey)); JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear); return new LazyMaterializeDecryptorInputStream(pgpFact); } catch (PGPException e) { throw new IOException(e); } }
From source file:org.opentestsystem.delivery.testreg.transformer.GpgVerifier.java
License:Open Source License
public byte[] decryptAndVerify(File encryptedSignedFile) throws IOException, SignatureException, PGPException { byte[] output = null; InputStream in = PGPUtil.getDecoderStream(new FileInputStream(encryptedSignedFile)); InputStream publicKeyIn = encryptor.getStreamForPath(publicKeyringLocation); ByteArrayOutputStream fOut = new ByteArrayOutputStream(); PGPObjectFactory pgpF = new PGPObjectFactory(in); PGPEncryptedDataList enc;// www . ja v a 2 s . co m Object o = pgpF.nextObject(); // // the first object might be a PGP marker packet. // while (!(o instanceof PGPEncryptedDataList)) { o = pgpF.nextObject(); } if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } // // find the secret key // Iterator<?> it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); InputStream secretKeyringInputStream = encryptor.getStreamForPath(secretKeyringLocation); PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(secretKeyringInputStream)); PGPSecretKey pgpSecKey = pgpSec.getSecretKey(pbe.getKeyID()); if (pgpSecKey == null) { fail("could not find secret key"); } PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder( new BcPGPDigestCalculatorProvider()).build(LANDINGZONE_PASS); sKey = pgpSecKey.extractPrivateKey(decryptor); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey)); PGPObjectFactory plainFact = new PGPObjectFactory(clear); Object message = null; PGPOnePassSignatureList onePassSignatureList = null; PGPSignatureList signatureList = null; PGPCompressedData compressedData = null; message = plainFact.nextObject(); ByteArrayOutputStream actualOutput = new ByteArrayOutputStream(); while (message != null) { LOGGER.debug("decrypted message: " + message.toString()); if (message instanceof PGPCompressedData) { compressedData = (PGPCompressedData) message; plainFact = new PGPObjectFactory(compressedData.getDataStream()); message = plainFact.nextObject(); } if (message instanceof PGPLiteralData) { // have to read it and keep it somewhere. Streams.pipeAll(((PGPLiteralData) message).getInputStream(), actualOutput); } else if (message instanceof PGPOnePassSignatureList) { onePassSignatureList = (PGPOnePassSignatureList) message; } else if (message instanceof PGPSignatureList) { signatureList = (PGPSignatureList) message; } else { throw new PGPException("message unknown message type."); } message = plainFact.nextObject(); } actualOutput.close(); PGPPublicKey publicKey = null; output = actualOutput.toByteArray(); if (onePassSignatureList == null || signatureList == null) { throw new PGPException("Signatures not found."); } else { for (int i = 0; i < onePassSignatureList.size(); i++) { PGPOnePassSignature ops = onePassSignatureList.get(0); LOGGER.debug("verifier : " + ops.getKeyID()); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(publicKeyIn)); publicKey = pgpRing.getPublicKey(ops.getKeyID()); if (publicKey != null) { ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey); ops.update(output); PGPSignature signature = signatureList.get(i); // apparently the signature can only be verified once?? if the verify method is called a 2nd time it // will fail boolean signatureVerified = ops.verify(signature); assertThat(signatureVerified, is(true)); if (signatureVerified) { Iterator<?> userIds = publicKey.getUserIDs(); while (userIds.hasNext()) { String userId = (String) userIds.next(); LOGGER.debug("Signed by " + userId); } LOGGER.debug("Signature verified"); } else { throw new SignatureException("Signature verification failed"); } } } } if (pbe.isIntegrityProtected() && !pbe.verify()) { throw new PGPException("Data is integrity protected but integrity is lost."); } else if (publicKey == null) { throw new SignatureException("Signature not found"); } else { fOut.write(output); fOut.flush(); fOut.close(); LOGGER.debug("decrypt and verify output: " + fOut.toString()); } return output; }
From source file:org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.java
License:Open Source License
public CachingDataDecryptorFactory getCachingDecryptorFactory(CryptoInputParcel cryptoInput) { if (mPrivateKeyState == PRIVATE_KEY_STATE_LOCKED) { throw new PrivateKeyNotUnlockedException(); }//from w w w .j a va 2 s . c o m if (mPrivateKeyState == PRIVATE_KEY_STATE_DIVERT_TO_CARD) { return new CachingDataDecryptorFactory(Constants.BOUNCY_CASTLE_PROVIDER_NAME, cryptoInput.getCryptoData()); } else { return new CachingDataDecryptorFactory(new JcePublicKeyDataDecryptorFactoryBuilder() .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME).build(mPrivateKey), cryptoInput.getCryptoData()); } }
From source file:ubicrypt.core.crypto.PGPEC.java
License:Open Source License
public static InputStream decrypt(final PGPPrivateKey privateKey, final InputStream cipherText) throws PGPException { final JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(cipherText); try {// w ww. j ava 2s .c om final PGPEncryptedDataList encList = (PGPEncryptedDataList) pgpF.nextObject(); log.trace("decrypt with sk:{}", privateKey.getKeyID()); final PGPPublicKeyEncryptedData encP = toStream( (Iterator<PGPPublicKeyEncryptedData>) encList.iterator()) .filter((PGPPublicKeyEncryptedData ed) -> { log.debug("pgp message encrypted with key:{}", ed.getKeyID()); return ed.getKeyID() == privateKey.getKeyID(); }).findFirst().orElseThrow(() -> new PGPException( "the message is not encrypted with the related public key")); try (InputStream clear = encP.getDataStream( new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(privateKey))) { Object next = new JcaPGPObjectFactory(clear).nextObject(); if (next instanceof PGPCompressedData) { next = new JcaPGPObjectFactory(((PGPCompressedData) next).getDataStream()).nextObject(); } return ((PGPLiteralData) next).getInputStream(); } } catch (final PGPException e) { throw e; } catch (final Exception e) { Throwables.propagate(e); } return null; }