Example usage for org.bouncycastle.openpgp PGPPublicKeyEncryptedData getDataStream

List of usage examples for org.bouncycastle.openpgp PGPPublicKeyEncryptedData getDataStream

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPPublicKeyEncryptedData getDataStream.

Prototype

public InputStream getDataStream(PublicKeyDataDecryptorFactory dataDecryptorFactory) throws PGPException 

Source Link

Document

Open an input stream which will provide the decrypted data protected by this object.

Usage

From source file:alpha.offsync.security.OpenPGPSecurityUtility.java

License:Apache License

@Override
public void decrypt(final OutputStream outputStream, final InputStream inputStream) {

    try {//from  ww w .ja  v  a  2 s.  co  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 {//from   w w w. java 2  s . co  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.google.e2e.bcdriver.Decryptor.java

License:Apache License

private static final Result decryptSignedContent(PGPPublicKeyEncryptedData pked, PGPPrivateKey decryptKey,
        KeyChecker.PKR verify) throws IOException, PGPException, SignatureException {

    InputStream clear = pked.getDataStream(new BcPublicKeyDataDecryptorFactory(decryptKey));

    Result ret = verifySignedContent(clear, verify);
    // Also check the message integrity
    if (pked.isIntegrityProtected() && !pked.verify()) {
        throw new IOException("Integrity check failed");
    }/*from   w w  w. j a v  a 2  s .  c o m*/
    return ret;
}

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   ww w  . jav a  2  s  .c  om
        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);
        }
    }
}

From source file:google.registry.rde.BouncyCastleTest.java

License:Open Source License

@Test
public void testEncryptDecrypt_KeyRingStyle() throws Exception {
    int bufferSize = 64 * 1024;

    // Alice loads Bob's "publicKey" into memory from her public key ring.
    PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY)));
    PGPPublicKeyRing publicKeyRing = publicKeyRings.getKeyRings("eric@bouncycastle.org", true, true).next();
    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 chain of private keys into memory.
    PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY)));

    // 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);
        // Bob loads the private key to which the message is addressed.
        PGPPrivateKey privateKey = extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID()));
        try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
            assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
                    .isEqualTo(FALL_OF_HYPERION_A_DREAM);
        }
    }
}

From source file:google.registry.rde.BouncyCastleTest.java

License:Open Source License

@Test
public void testCompressEncryptDecryptDecompress_KeyRingStyle() throws Exception {
    int bufsz = 64 * 1024;

    // Alice loads Bob's "publicKey" into memory from her public key ring.
    PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY)));
    PGPPublicKeyRing publicKeyRing = publicKeyRings.getKeyRings("eric@bouncycastle.org", true, true).next();
    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[bufsz])) {
            PGPCompressedDataGenerator kompressor = new PGPCompressedDataGenerator(ZIP);
            try (OutputStream output3 = kompressor.open(output2, new byte[bufsz])) {
                output3.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
            }/*from  www  .  j  a v a 2s.c o  m*/
        }
        encryptedData = output.toByteArray();
    }
    logger.info("Encrypted data: " + dumpHex(encryptedData));

    // Bob loads his chain of private keys into memory.
    PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY)));

    // 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);
        // Bob loads the private key to which the message is addressed.
        PGPPrivateKey privateKey = extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID()));
        try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
            pgpFact = new BcPGPObjectFactory(original);
            PGPCompressedData kompressedData = (PGPCompressedData) pgpFact.nextObject();
            try (InputStream orig2 = kompressedData.getDataStream()) {
                assertThat(CharStreams.toString(new InputStreamReader(orig2, UTF_8)))
                        .isEqualTo(FALL_OF_HYPERION_A_DREAM);
            }
        }
    }
}

From source file:google.registry.rde.Ghostryde.java

License:Open Source License

/**
 * Opens a new {@link Decryptor} (Reading Step 1/3)
 *
 * <p>This is the first step in opening a ghostryde file. After this method, you'll want to
 * call {@link #openDecompressor(Decryptor)}.
 *
 * @param input is an {@link InputStream} of the ghostryde file data.
 * @param privateKey is the private encryption key of the recipient (which is us!)
 * @throws IOException// w w  w  .  ja  va  2s.c o  m
 * @throws PGPException
 */
@CheckReturnValue
public Decryptor openDecryptor(@WillNotClose InputStream input, PGPPrivateKey privateKey)
        throws IOException, PGPException {
    checkNotNull(privateKey, "privateKey");
    PGPObjectFactory fact = new BcPGPObjectFactory(checkNotNull(input, "input"));
    PGPEncryptedDataList crypts = pgpCast(fact.nextObject(), PGPEncryptedDataList.class);
    checkState(crypts.size() > 0);
    if (crypts.size() > 1) {
        logger.warningfmt("crypts.size() is %d (should be 1)", crypts.size());
    }
    PGPPublicKeyEncryptedData crypt = pgpCast(crypts.get(0), PGPPublicKeyEncryptedData.class);
    if (crypt.getKeyID() != privateKey.getKeyID()) {
        throw new PGPException(String.format("Message was encrypted for keyid %x but ours is %x",
                crypt.getKeyID(), privateKey.getKeyID()));
    }
    return new Decryptor(crypt.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey)), crypt);
}

From source file:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java

/**
 * decrypt the passed in message stream/*from w ww .  j a va2  s  . c  om*/
 */
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 w  w . ja  va2s.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 ww w . j  a v a 2s  . 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;
}