Example usage for org.bouncycastle.openpgp PGPCompressedData getDataStream

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

Introduction

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

Prototype

public InputStream getDataStream() throws PGPException 

Source Link

Document

Return an input stream that decompresses and returns data in the compressed packet.

Usage

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

License:Apache License

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

    try {/*from  w w  w . j  ava 2s.  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:alpha.offsync.security.OpenPGPSecurityUtility.java

License:Apache License

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

    try {/*from  ww w  .j  a v  a  2 s  .  c o  m*/
        final File keyFile = this.publicKeyRing;

        final InputStream in = PGPUtil.getDecoderStream(inputStream);

        PGPObjectFactory pgpFact = new PGPObjectFactory(in);

        final PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject();

        pgpFact = new PGPObjectFactory(c1.getDataStream());

        final PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) pgpFact.nextObject();

        final PGPOnePassSignature ops = p1.get(0);

        final PGPLiteralData p2 = (PGPLiteralData) pgpFact.nextObject();

        final InputStream dIn = p2.getInputStream();
        int ch;
        final PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(new FileInputStream(keyFile)));

        final PGPPublicKey key = pgpRing.getPublicKey(ops.getKeyID());

        ops.init(new BcPGPContentVerifierBuilderProvider(), key);

        while ((ch = dIn.read()) >= 0) {
            ops.update((byte) ch);
            outputStream.write(ch);
        }

        outputStream.close();

        final PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();

        if (!ops.verify(p3.get(0))) {
            outputStream = null;
        }
    } catch (final FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final SignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final PGPException 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.j a  v  a 2s  . 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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Decrypt the specified (PKE) input file.
 * //w  w w  .j  a  v  a2 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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Decrypt the specified (PBE) input file
 *///w  w  w . java  2 s  . c  o m
public void decryptPBEBasedFile(String outputFilename, InputStream in, char[] passPhrase, boolean mdcRequired)
        throws PGPException {
    try {
        //
        // we need to be able to reset the stream if we try a
        // wrong passphrase, we'll assume that all the mechanisms
        // appear in the first 10k for the moment...
        //
        int READ_LIMIT = 10 * 1024;

        in.mark(READ_LIMIT);

        PGPPBEEncryptedData pbe;
        InputStream clear;
        int count = 0;

        for (;;) {
            InputStream dIn = PGPUtil.getDecoderStream(in);

            PGPObjectFactory pgpF = new PGPObjectFactory(dIn);
            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();
            }

            while (count < enc.size()) {
                if (enc.get(count) instanceof PGPPBEEncryptedData) {
                    break;
                }

                count++;
            }

            if (count >= enc.size()) {
                throw new PGPException("Passphrase invalid");
            }

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

            try {
                clear = pbe.getDataStream(passPhrase, "BC");
            } catch (PGPKeyValidationException e) {
                in.reset();
                continue;
            }

            break;
        }

        PGPObjectFactory pgpFact = new PGPObjectFactory(clear);

        PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();

        pgpFact = new PGPObjectFactory(cData.getDataStream());

        PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();

        if (outputFilename == null) {
            outputFilename = ld.getFileName();
        }

        FileOutputStream fOut = new FileOutputStream(outputFilename);

        InputStream unc = ld.getInputStream();

        int ch;
        while ((ch = unc.read()) >= 0) {
            fOut.write(ch);
        }

        if (pbe.isIntegrityProtected()) {
            if (!pbe.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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Verify the passed in file as being correctly signed.
 *//* www.j a v a 2 s. co  m*/
public void verifyFile(OutputStream out, InputStream inFile, InputStream publicRing) throws PGPException {
    try {
        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        InputStream in = PGPUtil.getDecoderStream(inFile);

        //
        // a clear signed file
        //
        if (in instanceof ArmoredInputStream && ((ArmoredInputStream) in).isClearText()) {
            if (!checkClearsign(in, pubRing)) {
                throw new PGPException("Signature verification failed.");
            }

            if (_verbose) {
                System.out.println("Signature verified.");
            }
        } else {
            PGPObjectFactory pgpFact = new PGPObjectFactory(in);

            PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject();

            pgpFact = new PGPObjectFactory(c1.getDataStream());

            Object message = pgpFact.nextObject();

            if (message instanceof PGPOnePassSignatureList) {
                // One-pass signature list
                if (!checkOnePassSignature(out, (PGPOnePassSignatureList) message, pgpFact, pubRing)) {
                    throw new PGPException("Signature verification failed.");
                }
            } else if (message instanceof PGPSignatureList) {
                // Signature list
                if (!checkSignature(out, (PGPSignatureList) message, pgpFact, pubRing)) {
                    throw new PGPException("Signature verification failed.");
                }
            } else {
                // what?
                throw new PGPException("Unrecognised PGP message type");
            }
        }
        if (_verbose) {
            System.out.println("Signature verified.");
        }
    } catch (Exception e) {
        throw new PGPException("Error in verification", e);
    }
}

From source file:com.ginema.crypto.encryption.PGPEncryption.java

License:Apache License

/**
 * decrypt the passed in message stream/*from w  w  w .  j  a v  a2 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.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  www .  j  av a2s .  c o  m*/
        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:com.google.e2e.bcdriver.Decryptor.java

License:Apache License

private static final Result verifySignedContent(InputStream inp, KeyChecker.PKR verify)
        throws IOException, PGPException, SignatureException {
    PGPObjectFactory plainFact = new PGPObjectFactory(inp, new BcKeyFingerprintCalculator());

    Object msg = plainFact.nextObject();

    // swap in uncompressed data if necessary
    if (msg instanceof PGPCompressedData) {
        PGPCompressedData cData = (PGPCompressedData) msg;
        plainFact = new PGPObjectFactory(cData.getDataStream(), new BcKeyFingerprintCalculator());
        msg = plainFact.nextObject();//from w w w. ja va 2  s  .c  o m
    }

    PGPOnePassSignatureList onePassSigList;
    PGPLiteralData lData;
    if (msg instanceof PGPOnePassSignatureList) {
        onePassSigList = (PGPOnePassSignatureList) msg;
        lData = (PGPLiteralData) plainFact.nextObject();
    } else {
        onePassSigList = null;
        lData = (PGPLiteralData) msg;
    }

    if ((verify != null) && (onePassSigList == null)) {
        throw new IOException("Message is unsigned");
    }

    PGPOnePassSignature onePassSig = null;
    int onePassStartIndex = -1;
    PGPPublicKey verifyKey = null;
    if (verify != null) {
        for (int i = 0; i < onePassSigList.size(); i++) {
            List<PGPPublicKey> candidates = verify.getSigningKeysByKeyID(onePassSigList.get(i).getKeyID());
            if (candidates.size() == 1) {
                onePassSig = onePassSigList.get(i);
                onePassStartIndex = i;
                verifyKey = candidates.get(0);
                break;
            }
        }
    }

    if ((verify != null) && (onePassSig == null)) {
        throw new IOException("Failed to find a signature from verifying key");
    }

    if (onePassSig != null) {
        onePassSig.init(new BcPGPContentVerifierBuilderProvider(), verifyKey);
    }
    ByteArrayOutputStream baout = new ByteArrayOutputStream();
    InputStream lin = lData.getInputStream();
    byte buf[] = new byte[8192];
    int nread;
    while ((nread = lin.read(buf)) > 0) {
        baout.write(buf, 0, nread);
        if (onePassSig != null) {
            onePassSig.update(buf, 0, nread);
        }
    }
    baout.close();
    if (onePassSig != null) {
        PGPSignatureList sigList = (PGPSignatureList) plainFact.nextObject();
        // One pass signature trailers occur in LIFO order compared to their
        // location in the header.
        PGPSignature sig = sigList.get(sigList.size() - 1 - onePassStartIndex);
        if (!onePassSig.verify(sig)) {
            throw new IOException("Invalid signature in message");
        }
    }
    return new Result(baout.toByteArray(), lData.getFileName());
}

From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * Decrypt a PGP encrypted stream.//  w w  w. j  av a  2 s. c om
 *
 * @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();
}