Example usage for org.bouncycastle.openpgp.jcajce JcaPGPObjectFactory nextObject

List of usage examples for org.bouncycastle.openpgp.jcajce JcaPGPObjectFactory nextObject

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.jcajce JcaPGPObjectFactory nextObject.

Prototype

public Object nextObject() throws IOException 

Source Link

Document

Return the next object in the stream, or null if the end of stream is reached.

Usage

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 ww  . jav a2  s.  c om
        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:gobblin.crypto.GPGFileDecryptor.java

License:Apache License

public static InputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from  w ww .j ava 2  s  .c o m*/
    inputStream = PGPUtil.getDecoderStream(inputStream);

    JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(inputStream);
    PGPEncryptedDataList enc;
    Object pgpfObject = pgpF.nextObject();

    if (pgpfObject instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) pgpfObject;
    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }

    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);

    InputStream clear;
    try {
        clear = pbe
                .getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                                .build(passPhrase.toCharArray()));

        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);
        pgpfObject = pgpFact.nextObject();
        if (pgpfObject instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) pgpfObject;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
            pgpfObject = pgpFact.nextObject();
        }

        PGPLiteralData ld = (PGPLiteralData) pgpfObject;
        return ld.getInputStream();
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

From source file:gobblin.util.GPGFileDecrypter.java

License:Open Source License

public static FSDataInputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from www.  j a  v  a2 s .c o  m*/
    inputStream = PGPUtil.getDecoderStream(inputStream);

    JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(inputStream);
    PGPEncryptedDataList enc;
    Object pgpfObject = pgpF.nextObject();

    if (pgpfObject instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) pgpfObject;
    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }

    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);

    InputStream clear;
    try {
        clear = pbe
                .getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                                .build(passPhrase.toCharArray()));

        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);
        pgpfObject = pgpFact.nextObject();
        if (pgpfObject instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) pgpfObject;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
            pgpfObject = pgpFact.nextObject();
        }

        PGPLiteralData ld = (PGPLiteralData) pgpfObject;
        return StreamUtils.convertStream(ld.getInputStream());
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

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

/**
 * decrypt the passed in message stream/*from  w  w w  . ja v  a 2  s  .  com*/
 */
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.gobblin.crypto.GPGFileDecryptor.java

License:Apache License

/**
 * Generate a PGPEncryptedDataList from an inputstream
 * @param inputStream file inputstream that needs to be decrypted
 * @throws IOException//from   w  w w  . j  av  a  2  s .  c o m
 */
private PGPEncryptedDataList getPGPEncryptedDataList(InputStream inputStream) throws IOException {

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    inputStream = PGPUtil.getDecoderStream(inputStream);

    JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(inputStream);
    PGPEncryptedDataList enc;
    Object pgpfObject = pgpF.nextObject();

    if (pgpfObject instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) pgpfObject;
    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }
    return enc;
}

From source file:org.elasticsearch.plugins.InstallPluginCommand.java

License:Apache License

/**
 * Verify the signature of the downloaded plugin ZIP. The signature is obtained from the source of the downloaded plugin by appending
 * ".asc" to the URL. It is expected that the plugin is signed with the Elastic signing key with ID D27D666CD88E42B4.
 *
 * @param zip       the path to the downloaded plugin ZIP
 * @param urlString the URL source of the downloade plugin ZIP
 * @throws IOException  if an I/O exception occurs reading from various input streams
 * @throws PGPException if the PGP implementation throws an internal exception during verification
 *///from w w  w.  j a v  a2  s  .c o m
void verifySignature(final Path zip, final String urlString) throws IOException, PGPException {
    final String ascUrlString = urlString + ".asc";
    final URL ascUrl = openUrl(ascUrlString);
    try (
            // fin is a file stream over the downloaded plugin zip whose signature to verify
            InputStream fin = pluginZipInputStream(zip);
            // sin is a URL stream to the signature corresponding to the downloaded plugin zip
            InputStream sin = urlOpenStream(ascUrl);
            // ain is a input stream to the public key in ASCII-Armor format (RFC4880)
            InputStream ain = new ArmoredInputStream(getPublicKey())) {
        final JcaPGPObjectFactory factory = new JcaPGPObjectFactory(PGPUtil.getDecoderStream(sin));
        final PGPSignature signature = ((PGPSignatureList) factory.nextObject()).get(0);

        // validate the signature has key ID matching our public key ID
        final String keyId = Long.toHexString(signature.getKeyID()).toUpperCase(Locale.ROOT);
        if (getPublicKeyId().equals(keyId) == false) {
            throw new IllegalStateException(
                    "key id [" + keyId + "] does not match expected key id [" + getPublicKeyId() + "]");
        }

        // compute the signature of the downloaded plugin zip
        final PGPPublicKeyRingCollection collection = new PGPPublicKeyRingCollection(ain,
                new JcaKeyFingerprintCalculator());
        final PGPPublicKey key = collection.getPublicKey(signature.getKeyID());
        signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(new BouncyCastleProvider()), key);
        final byte[] buffer = new byte[1024];
        int read;
        while ((read = fin.read(buffer)) != -1) {
            signature.update(buffer, 0, read);
        }

        // finally we verify the signature of the downloaded plugin zip matches the expected signature
        if (signature.verify() == false) {
            throw new IllegalStateException("signature verification for [" + urlString + "] failed");
        }
    }
}

From source file:org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing.java

License:Open Source License

public CanonicalizedSecretKeyRing(byte[] blob, boolean isRevoked, int verified) {
    super(verified);
    JcaPGPObjectFactory factory = new JcaPGPObjectFactory(blob);
    PGPKeyRing keyRing = null;/*from   ww  w.  j a  v  a 2 s .com*/
    try {
        if ((keyRing = (PGPKeyRing) factory.nextObject()) == null) {
            Log.e(Constants.TAG, "No keys given!");
        }
    } catch (IOException e) {
        Log.e(Constants.TAG, "Error while converting to PGPKeyRing!", e);
    }

    mRing = (PGPSecretKeyRing) keyRing;
}

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  .  ja 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;
}

From source file:uk.co.platosys.dinigma.CryptoEngine.java

License:GNU General Public License

/**
 *  Decrypts an InputStream to a Document
 *
 * @param inputStream/*www. java2s  .  co m*/
 * @param key
 * @param passphrase
 * @return
 * @throws Exception
 */

public static String decrypt(InputStream inputStream, Key key, char[] passphrase)
        throws MinigmaException, DecryptionException, java.io.IOException {
    InputStream in;
    PGPObjectFactory pgpObjectFactory;
    PGPEncryptedDataList pgpEncryptedDataList = null;
    PGPPrivateKey privateKey = null;
    PGPPublicKeyEncryptedData pgpPublicKeyEncryptedData = null;
    Object compressedObject = null;
    PGPLiteralData literalData = null;
    //First get a  PGPEncryptedDataList from the input stream.
    try {
        in = PGPUtil.getDecoderStream(inputStream);
        pgpObjectFactory = new PGPObjectFactory(in, new JcaKeyFingerprintCalculator());
        Object object = pgpObjectFactory.nextObject();
        if (object instanceof PGPEncryptedDataList) {
            //the EncryptedDataList is either the first object;
            pgpEncryptedDataList = (PGPEncryptedDataList) object;
        } else {
            //or the next
            pgpEncryptedDataList = (PGPEncryptedDataList) pgpObjectFactory.nextObject();
        }

        if (pgpEncryptedDataList == null) {
            throw new MinigmaException("couldn't find encrypted data list");
        }
    } catch (Exception e) {
        //Log.d(TAG,"Minigma-unLock() 1: error reading encrypted data list", e);
        throw new MinigmaException("error reading encrypted data list", e);
    }
    // now get encrypted objects from the list.
    try {
        //Log.d(TAG, "Minigma-unLock() 2 start");
        @SuppressWarnings("unchecked")
        Iterator<PGPPublicKeyEncryptedData> it = pgpEncryptedDataList.getEncryptedDataObjects();
        //Log.d(TAG, "Minigma-unLock() 2: EncryptedDataList size = "+Integer.toString(pgpEncryptedDataList.size())+", now got its iterator");
        JcePBESecretKeyDecryptorBuilder keyDecryptorBuilder = new JcePBESecretKeyDecryptorBuilder();
        keyDecryptorBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
        while (it.hasNext() && privateKey == null) {
            pgpPublicKeyEncryptedData = it.next();
            long keyID = pgpPublicKeyEncryptedData.getKeyID();
            //Log.d(TAG, "Minigma-unLock() 2: data was encrypted with key:"+ Long.toHexString(keyID));
            PGPSecretKey secretKey = key.getDecryptionKey(keyID);
            if (secretKey == null) {
                //Log.d(TAG, "Minigma-unLock() 2: bad key, no decryption key");
                throw new DecryptionException("2: bad key, no decryption key");
            }
            if (secretKey.getKeyID() == keyID) {
                privateKey = key.getDecryptionKey(keyID)
                        .extractPrivateKey(keyDecryptorBuilder.build(passphrase));
                //Log.d(TAG,"Minigma-unLock() 2: got private key");
            } else {
                //Log.d(TAG, "Engima-unLock() 2: not this time, round again.");
            }
        }
        if (privateKey == null) {

            throw new DecryptionException("Minigma-unLock() 2: decryption key doesn't fit any of the locks");
        }
    } catch (Exception e) {

        throw new MinigmaException("A problem arose during decryption", e);
    }

    try {

        PublicKeyDataDecryptorFactory dataDecryptorFactory = new BcPublicKeyDataDecryptorFactory(privateKey);
        InputStream decryptedStream = pgpPublicKeyEncryptedData.getDataStream(dataDecryptorFactory);
        JcaPGPObjectFactory compressedFactory = new JcaPGPObjectFactory(decryptedStream);
        compressedObject = compressedFactory.nextObject();

    } catch (Exception e) {

        throw new MinigmaException("Minigma-unLock() 3: error reading encrypted data stream", e);
    }
    try {

        PGPCompressedData clearCompressedData = (PGPCompressedData) compressedObject;
        Object uncompressedObject = null;
        JcaPGPObjectFactory uncompressedFactory = null;

        InputStream inputStream2 = clearCompressedData.getDataStream();

        uncompressedFactory = new JcaPGPObjectFactory(inputStream2);

        uncompressedObject = uncompressedFactory.nextObject();

        if (uncompressedObject instanceof PGPOnePassSignatureList) {
            // and the next object should be literal data:
            uncompressedObject = uncompressedFactory.nextObject();
            if (uncompressedObject instanceof PGPLiteralData) {
                literalData = (PGPLiteralData) uncompressedObject;
            } else {
                //unrecognised object;
                throw new MinigmaException("Minigma-unLock() 4: unrecognised object: A "
                        + uncompressedObject.getClass().getName());

            }
            uncompressedObject = uncompressedFactory.nextObject();
            if (uncompressedObject instanceof PGPSignatureList) {
            } else {
                //unrecognised object;
                throw new MinigmaException(
                        "Minigma-unlock() 4: unrecognised object B " + uncompressedObject.getClass().getName());
            }
        } else if (uncompressedObject instanceof PGPLiteralData) {
            literalData = (PGPLiteralData) uncompressedObject;
        } else {
            //unrecognised object
            throw new MinigmaException(
                    "Minigma-unLock() 4: unrecognised object C " + uncompressedObject.getClass().getName());

        }
    } catch (Exception e) {
        throw new MinigmaException("Minigma-unLock() 4: error getting decompressed object", e);

    }

    InputStream inputStream1 = literalData.getDataStream();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream1.read(buffer)) != -1) {
        result.write(buffer, 0, length);
    }
    return result.toString("UTF-8");
}