Example usage for org.bouncycastle.openpgp PGPEncryptedDataList iterator

List of usage examples for org.bouncycastle.openpgp PGPEncryptedDataList iterator

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPEncryptedDataList iterator.

Prototype

public Iterator iterator() 

Source Link

Document

Support method for Iterable where available.

Usage

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 {//from  w  w w.j a va 2 s .  c o m
        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;
}