Example usage for org.bouncycastle.openpgp PGPLiteralData getInputStream

List of usage examples for org.bouncycastle.openpgp PGPLiteralData getInputStream

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPLiteralData getInputStream.

Prototype

public InputStream getInputStream() 

Source Link

Document

Return the raw input stream for the data 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  ww  .ja  v a2 s.  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 w ww. j a  va  2  s .co  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 {//  w ww . jav  a2s .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.
 * // www.j ava 2s. 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 ww . ja  va2 s  .co 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

/**
 * Check a one-pass signature/*from w  w w.  j  av a2  s . c  o  m*/
 */
private boolean checkOnePassSignature(OutputStream out, PGPOnePassSignatureList p1, PGPObjectFactory pgpFact,
        PGPPublicKeyRingCollection pgpRing) throws PGPException {
    try {
        PGPOnePassSignature ops = null;
        PGPPublicKey key = null;

        int count = 0;
        while (count < p1.size()) {
            ops = p1.get(count);
            key = pgpRing.getPublicKey(ops.getKeyID());
            if (key != null) {
                break;
            }

            count++;
        }

        if (key == null) {
            throw new PGPException("Corresponding public key not found");
        }

        if (key.isRevoked()) {
            String keyId = Long.toHexString(key.getKeyID()).substring(8);
            System.out.println("Warning: Signing key (0x" + keyId + ") has been revoked");
            // throw new PGPException("Signing key (0x"+keyId+") has been revoked");
        }

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

        //            if (outputFilename == null) {
        //                outputFilename = ld.getFileName();
        //            }
        //
        //            FileOutputStream out = new FileOutputStream(outputFilename);

        InputStream dataIn = ld.getInputStream();

        ops.initVerify(key, "BC");

        int ch;
        while ((ch = dataIn.read()) >= 0) {
            ops.update((byte) ch);
            out.write(ch);
        }

        out.close();

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

        return ops.verify(p3.get(0));
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in verification", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Check a signature/*w  ww. ja v a 2 s  .  c  o m*/
 */
private boolean checkSignature(OutputStream out, PGPSignatureList sigList, PGPObjectFactory pgpFact,
        PGPPublicKeyRingCollection pgpRing) throws PGPException {
    try {
        PGPSignature sig = null;
        PGPPublicKey key = null;

        int count = 0;
        while (count < sigList.size()) {
            sig = sigList.get(count);
            key = pgpRing.getPublicKey(sig.getKeyID());
            if (key != null) {
                break;
            }

            count++;
        }

        if (key == null) {
            throw new PGPException("Corresponding public key not found");
        }

        if (key.isRevoked()) {
            String keyId = Long.toHexString(key.getKeyID()).substring(8);
            System.out.println("Warning: Signing key (0x" + keyId + ") has been revoked");
            // throw new PGPException("Signing key (0x"+keyId+") has been revoked");
        }

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

        //            if (outputFilename == null) {
        //                outputFilename = ld.getFileName();
        //            }
        //
        //            FileOutputStream out = new FileOutputStream(outputFilename);

        InputStream dataIn = ld.getInputStream();

        sig.initVerify(key, "BC");

        int ch;
        while ((ch = dataIn.read()) >= 0) {
            sig.update((byte) ch);
            out.write(ch);
        }
        out.close();

        return sig.verify();
    } catch (PGPException e) {
        throw e;
    } 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  ww w.j  a v a2 s  .c  o  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.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();//w  ww  . j ava  2s.co 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.//from   w  ww  .  j a va  2s.c o  m
 *
 * @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();
}