Example usage for org.bouncycastle.openpgp PGPException PGPException

List of usage examples for org.bouncycastle.openpgp PGPException PGPException

Introduction

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

Prototype

public PGPException(String message) 

Source Link

Usage

From source file:genkeys.java

License:Open Source License

private static String symmetricCipherName(int algorithm) throws PGPException {
    switch (algorithm) {
    case SymmetricKeyAlgorithmTags.NULL:
        return null;
    case SymmetricKeyAlgorithmTags.TRIPLE_DES:
        return "DESEDE";
    case SymmetricKeyAlgorithmTags.IDEA:
        return "IDEA";
    case SymmetricKeyAlgorithmTags.CAST5:
        return "CAST5";
    case SymmetricKeyAlgorithmTags.BLOWFISH:
        return "Blowfish";
    case SymmetricKeyAlgorithmTags.SAFER:
        return "SAFER";
    case SymmetricKeyAlgorithmTags.DES:
        return "DES";
    case SymmetricKeyAlgorithmTags.AES_128:
        return "AES";
    case SymmetricKeyAlgorithmTags.AES_192:
        return "AES";
    case SymmetricKeyAlgorithmTags.AES_256:
        return "AES";
    case SymmetricKeyAlgorithmTags.TWOFISH:
        return "Twofish";
    default:/*from ww w  .j a  v a 2 s .  c  o m*/
        throw new PGPException("unknown symmetric algorithm: " + algorithm);
    }
}

From source file:genkeys.java

License:Open Source License

private static PublicKeyPacket publicKeyPacket(PublicKey key, int algorithm, Date time) throws PGPException {
    BCPGKey bcpgKey;//www .  j a  v  a  2 s  .  com
    if (key instanceof RSAPublicKey) {
        RSAPublicKey rK = (RSAPublicKey) key;
        bcpgKey = new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent());
    } else if (key instanceof DSAPublicKey) {
        DSAPublicKey dK = (DSAPublicKey) key;
        DSAParams dP = dK.getParams();
        bcpgKey = new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(), dK.getY());
    } else if (key instanceof ElGamalPublicKey) {
        ElGamalPublicKey eK = (ElGamalPublicKey) key;
        ElGamalParameterSpec eS = eK.getParameters();
        bcpgKey = new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY());
    } else {
        throw new PGPException("unknown key class");
    }

    return new PublicKeyPacket(algorithm, time, bcpgKey);
}

From source file:genkeys.java

License:Open Source License

private static SecretKeyPacket secretKeyPacket(KeyPair key, int cipher, boolean useSHA1, S2K s2k, String pass)
        throws NoSuchProviderException, PGPException {
    int algorithm;
    if (key.getPrivate().getAlgorithm() == "RSA") {
        algorithm = PGPPublicKey.RSA_GENERAL;
    } else {/*from www .  j av a  2 s .c  om*/
        algorithm = PGPPublicKey.DSA;
    }

    Date time = new Date();
    PGPKeyPair keyPair = new PGPKeyPair(algorithm, key.getPublic(), key.getPrivate(), time, "BC");

    PublicKeyPacket pubPk = publicKeyPacket(key.getPublic(), algorithm, time);
    BCPGObject secKey;
    switch (keyPair.getPublicKey().getAlgorithm()) {
    case PGPPublicKey.RSA_ENCRYPT:
    case PGPPublicKey.RSA_SIGN:
    case PGPPublicKey.RSA_GENERAL:
        RSAPrivateCrtKey rsK = (RSAPrivateCrtKey) keyPair.getPrivateKey().getKey();
        secKey = new RSASecretBCPGKey(rsK.getPrivateExponent(), rsK.getPrimeP(), rsK.getPrimeQ());
        break;
    case PGPPublicKey.DSA:
        DSAPrivateKey dsK = (DSAPrivateKey) keyPair.getPrivateKey().getKey();
        secKey = new DSASecretBCPGKey(dsK.getX());
        break;
    case PGPPublicKey.ELGAMAL_ENCRYPT:
    case PGPPublicKey.ELGAMAL_GENERAL:
        ElGamalPrivateKey esK = (ElGamalPrivateKey) keyPair.getPrivateKey().getKey();
        secKey = new ElGamalSecretBCPGKey(esK.getX());
        break;
    default:
        throw new PGPException("unknown key class");
    }

    Cipher c = cipher(cipher);

    SecretKeyPacket secPk;
    try {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        BCPGOutputStream pOut = new BCPGOutputStream(bOut);

        pOut.writeObject(secKey);

        byte[] keyData = bOut.toByteArray();

        pOut.write(checksum(useSHA1, keyData, keyData.length));

        if (c != null) {
            SecretKey skey = PGPUtil.makeKeyFromPassPhrase(cipher, s2k, pass.toCharArray(), "BC");

            c.init(Cipher.ENCRYPT_MODE, skey, new SecureRandom());
            byte[] iv = c.getIV();
            byte[] encData = c.doFinal(bOut.toByteArray());

            if (useSHA1) {
                secPk = new SecretKeyPacket(pubPk, cipher, SecretKeyPacket.USAGE_SHA1, s2k, iv, encData);
            } else {
                secPk = new SecretKeyPacket(pubPk, cipher, SecretKeyPacket.USAGE_CHECKSUM, s2k, iv, encData);
            }
        } else {
            secPk = new SecretKeyPacket(pubPk, cipher, null, null, bOut.toByteArray());
        }
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Exception encrypting key", e);
    }

    return secPk;
}

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.  j  av 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:bisq.desktop.main.overlays.windows.downloadupdate.BisqInstaller.java

License:Open Source License

/**
 * Verifies detached PGP signatures against GPG/openPGP RSA public keys. Does currently not work with openssl or JCA/JCE keys.
 *
 * @param pubKeyFile Path to file providing the public key to use
 * @param sigFile    Path to detached signature file
 * @param dataFile   Path to signed data file
 * @return {@code true} if signature is valid, {@code false} if signature is not valid
 * @throws Exception throws various exceptions in case something went wrong. Main reason should be that key or
 *                   signature could be extracted from the provided files due to a "bad" format.<br>
 *                   <code>FileNotFoundException, IOException, SignatureException, PGPException</code>
 *///  ww w. ja v a 2  s. c om
public static VerifyStatusEnum verifySignature(File pubKeyFile, File sigFile, File dataFile) throws Exception {
    InputStream inputStream;
    int bytesRead;
    PGPPublicKey publicKey;
    PGPSignature pgpSignature;
    boolean result;

    // Read keys from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(pubKeyFile));
    PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(inputStream,
            new JcaKeyFingerprintCalculator());
    inputStream.close();

    Iterator<PGPPublicKeyRing> iterator = publicKeyRingCollection.getKeyRings();
    PGPPublicKeyRing pgpPublicKeyRing;
    if (iterator.hasNext()) {
        pgpPublicKeyRing = iterator.next();
    } else {
        throw new PGPException("Could not find public keyring in provided key file");
    }

    // Would be the solution for multiple keys in one file
    //        Iterator<PGPPublicKey> kIt;
    //        kIt = pgpPublicKeyRing.getPublicKeys();
    //        publicKey = pgpPublicKeyRing.getPublicKey(0xF5B84436F379A1C6L);

    // Read signature from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(sigFile));
    PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(inputStream, new JcaKeyFingerprintCalculator());
    Object o = pgpObjectFactory.nextObject();
    if (o instanceof PGPSignatureList) {
        PGPSignatureList signatureList = (PGPSignatureList) o;
        checkArgument(!signatureList.isEmpty(), "signatureList must not be empty");
        pgpSignature = signatureList.get(0);
    } else if (o instanceof PGPSignature) {
        pgpSignature = (PGPSignature) o;
    } else {
        throw new SignatureException("Could not find signature in provided signature file");
    }
    inputStream.close();
    log.debug("KeyID used in signature: %X\n", pgpSignature.getKeyID());
    publicKey = pgpPublicKeyRing.getPublicKey(pgpSignature.getKeyID());

    // If signature is not matching the key used for signing we fail
    if (publicKey == null)
        return VerifyStatusEnum.FAIL;

    log.debug("The ID of the selected key is %X\n", publicKey.getKeyID());
    pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

    // Read file to verify
    byte[] data = new byte[1024];
    inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
    while (true) {
        bytesRead = inputStream.read(data, 0, 1024);
        if (bytesRead == -1)
            break;
        pgpSignature.update(data, 0, bytesRead);
    }
    inputStream.close();

    // Verify the signature
    result = pgpSignature.verify();
    return result ? VerifyStatusEnum.OK : VerifyStatusEnum.FAIL;
}

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 ava2 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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Encrypt and sign the specified input file.  If you pass in a seed, you
 * will get the same encrypted output for the same file + same seed + same signor.
 * //from   www . j  av  a 2 s.co  m
 * DANGER!  If you use the same seed for multiple different messages, you are
 * making your key stream vulnerable to hacking, and your encryption is near
 * meaningless!  Make sure to use different seeds for different contents!
 *  
 * @param seed 
 */
public void encryptAndSignFile(String outputFilename, File inFile, InputStream publicRing,
        InputStream secretRing, String recipient, String signor, char[] passwd, boolean armor,
        boolean withIntegrityCheck, boolean oldFormat, byte[] seed) throws PGPException {
    try {
        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing);

        // Find the recipient's key
        PGPPublicKey encKey = readPublicKey(pubRing, recipient, true);
        if (encKey.isRevoked()) {
            String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
            throw new PGPException("Encryption key (0x" + keyId + ") has been revoked");
        }

        // Find the signing key
        PGPPublicKey publicKey;
        PGPSecretKey secretKey;
        if (signor != null) {
            publicKey = readPublicKey(pubRing, signor, false);
            secretKey = findSecretKey(secRing, publicKey.getKeyID(), true);
        } else {
            // Just look for the first signing key on the secret keyring (if any)
            secretKey = findSigningKey(secRing);
            publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false);
        }
        if (publicKey.isRevoked()) {
            String keyId = Long.toHexString(publicKey.getKeyID()).substring(8);
            throw new PGPException("Signing key (0x" + keyId + ") has been revoked");
        }

        PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC");

        // Sign the data into an in-memory stream
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        if (oldFormat) {
            signDataV3(inFile, bOut, publicKey, privateKey);
        } else {
            signData(inFile, bOut, publicKey, privateKey);
        }

        SecureRandom secRand = makeSecureRandom(seed);

        PGPEncryptedDataGenerator cPk = oldFormat
                ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC")
                : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC");

        cPk.addMethod(encKey);

        byte[] bytes = bOut.toByteArray();

        OutputStream out = new FileOutputStream(outputFilename);
        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;
        OutputStream cOut = cPk.open(aOut, bytes.length);

        cOut.write(bytes);

        cPk.close();

        if (armor) {
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in encryption", e);
    }
}

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

License:Open Source License

/**
 * Encrypt the specified input file/*from www  .  j  a  v a  2 s. com*/
 * @param seed 
 */
public void encryptFile(OutputStream out, InputStream in, String inName, long inLength, Date inDate,
        PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck, boolean oldFormat, char[] passphrase,
        byte[] seed) throws PGPException {
    try {
        if (encKey.isRevoked()) {
            String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
            throw new PGPException("Encryption key (0x" + keyId + ") has been revoked");
        }

        // Compress the data into an in-memory stream
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        compressData(in, bOut, inName, inLength, inDate, oldFormat, Format.UNCOMPRESSED);

        // Now encrypt the result
        SecureRandom secRand = makeSecureRandom(seed);

        // Now encrypt the result
        PGPEncryptedDataGenerator cPk = oldFormat
                ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC")
                : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC");

        cPk.addMethod(encKey);

        byte[] bytes = bOut.toByteArray();

        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;
        OutputStream cOut = cPk.open(aOut, bytes.length);

        cOut.write(bytes);

        cPk.close();

        if (armor) {
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in encryption", e);
    }
}

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

License:Open Source License

/**
 * Sign the specified file/*from w w w  .j  a va 2  s.  c om*/
 */
public void signFile(String outputFilename, File inFile, InputStream publicRing, InputStream secretRing,
        String signor, char[] passwd, boolean armor, boolean oldFormat) throws PGPException {
    try {
        PGPPublicKey publicKey;
        PGPSecretKey secretKey;

        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing);

        // Find the signing key
        if (signor != null) {
            publicKey = readPublicKey(pubRing, signor, false);
            secretKey = findSecretKey(secRing, publicKey.getKeyID(), true);
        } else {
            // Just look for the first signing key on the secret keyring (if any)
            secretKey = findSigningKey(secRing);
            publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false);
        }
        if (publicKey.isRevoked()) {
            String keyId = Long.toHexString(publicKey.getKeyID()).substring(8);
            throw new PGPException("Signing key (0x" + keyId + ") has been revoked");
        }

        PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC");

        OutputStream out = new FileOutputStream(outputFilename);
        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;

        // Sign the data
        if (oldFormat) {
            signDataV3(inFile, aOut, publicKey, privateKey);
        } else {
            signData(inFile, aOut, publicKey, privateKey);
        }

        if (armor) {
            // close() just finishes and flushes the stream but does not close it
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in signing", e);
    }
}

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

License:Open Source License

/**
 * Decrypt the specified (PKE) input file.
 * /*from www  . ja 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);
    }
}