Example usage for org.bouncycastle.openpgp PGPPublicKeyEncryptedData isIntegrityProtected

List of usage examples for org.bouncycastle.openpgp PGPPublicKeyEncryptedData isIntegrityProtected

Introduction

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

Prototype

public boolean isIntegrityProtected() 

Source Link

Document

Checks whether the packet is integrity protected.

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 {//from  ww  w.  j  a v a  2  s  .  c o  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 ww. j  a  v a 2 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.google.e2e.bcdriver.Decryptor.java

License:Apache License

private static final Result decryptSignedContent(PGPPublicKeyEncryptedData pked, PGPPrivateKey decryptKey,
        KeyChecker.PKR verify) throws IOException, PGPException, SignatureException {

    InputStream clear = pked.getDataStream(new BcPublicKeyDataDecryptorFactory(decryptKey));

    Result ret = verifySignedContent(clear, verify);
    // Also check the message integrity
    if (pked.isIntegrityProtected() && !pked.verify()) {
        throw new IOException("Integrity check failed");
    }//from   w w  w  .  ja va 2 s  .c  o  m
    return ret;
}

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

License:Apache License

/**
 * Decrypt a PGP encrypted stream.//from w w w  .  j ava2 s  . 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();
}

From source file:com.simple.sftpfetch.decrypt.PGPFileDecrypter.java

License:Apache License

private void decryptFile(InputStream in, OutputStream outputStream)
        throws IOException, NoSuchProviderException {
    in = PGPUtil.getDecoderStream(in);/* w  w w .  ja  va2  s  .  c  o  m*/

    try {
        PGPEncryptedDataList enc = getEncryptedDataList(in);

        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;

        while (sKey == null && it.hasNext()) {
            pbe = (PGPPublicKeyEncryptedData) it.next();
            sKey = getPrivateKey(sKey, pbe);
        }

        if (sKey == null) {
            throw new IllegalArgumentException("secret key for message not found.");
        }

        InputStream clear = pbe.getDataStream(sKey, "BC");
        Object message = new PGPObjectFactory(clear).nextObject();

        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());
            message = pgpFact.nextObject();
        }

        if (message instanceof PGPLiteralData) {
            PGPLiteralData ld = (PGPLiteralData) message;
            Streams.pipeAll(ld.getInputStream(), outputStream);
        } 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() && !pbe.verify()) {
            throw new PGPException("message failed integrity check");
        }
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    }
}

From source file:eu.mrbussy.security.crypto.pgp.PGPDecryptor.java

License:Open Source License

public InputStream decryptFile(InputStream in) throws Exception {
    InputStream is = null;//from   w  ww .  j  av a  2 s  . co  m
    byte[] bytes = null;
    InputStream keyIn = new FileInputStream(new File(privateKeyFilePath));
    char[] passwd = password.toCharArray();
    in = PGPUtil.getDecoderStream(in);

    PGPObjectFactory pgpF = new PGPObjectFactory(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<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects();
    PGPPrivateKey sKey = null;
    PGPPublicKeyEncryptedData pbe = null;
    while (sKey == null && it.hasNext()) {
        pbe = it.next();
        sKey = PGPUtils.findPrivateKey(keyIn, pbe.getKeyID(), passwd);
    }

    if (sKey == null) {
        throw new IllegalArgumentException("secret key for message not found.");
    }

    InputStream clear = pbe.getDataStream(sKey, "BC");
    PGPObjectFactory plainFact = new PGPObjectFactory(clear);
    Object message = plainFact.nextObject();
    PGPObjectFactory pgpFact = null;
    if (message instanceof PGPCompressedData) {
        PGPCompressedData cData = (PGPCompressedData) message;
        pgpFact = new PGPObjectFactory(cData.getDataStream());
        message = pgpFact.nextObject();
    }

    PGPOnePassSignature ops = null;
    if (message instanceof PGPOnePassSignatureList) {
        if (isSigned) {
            PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) message;
            ops = p1.get(0);
            long keyId = ops.getKeyID();
            PGPPublicKey signerPublicKey = PGPUtils.readPublicKey(signingPublicKeyFilePath, keyId);
            ops.initVerify(signerPublicKey, "BC");
        }
        message = pgpFact.nextObject();
    }

    if (message instanceof PGPLiteralData) {
        PGPLiteralData ld = (PGPLiteralData) message;
        if (pbe.isIntegrityProtected()) {
            if (!pbe.verify()) {
                throw new PGPException("message failed integrity check");
            }
        }
        is = ld.getInputStream();
        bytes = IOUtils.toByteArray(is);

        if (isSigned) {
            ops.update(bytes);
            PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
            if (!ops.verify(p3.get(0))) {
                throw new PGPException("Signature verification failed!");
            }
        }
    } else {
        throw new PGPException("message is not a simple encrypted file - type unknown.");
    }
    return new ByteArrayInputStream(bytes);
}

From source file:gr.abiss.calipso.util.PgpUtils.java

License:Open Source License

/**
 * decrypt the passed in message stream/*from  ww  w.j  av a  2s  .  c om*/
 */
private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName)
        throws IOException, NoSuchProviderException {
    in = PGPUtil.getDecoderStream(in);

    try {
        PGPObjectFactory pgpF = new PGPObjectFactory(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));

        while (sKey == null && it.hasNext()) {
            pbe = (PGPPublicKeyEncryptedData) it.next();

            sKey = findSecretKey(pgpSec, pbe.getKeyID(), passwd);
        }

        if (sKey == null) {
            throw new IllegalArgumentException("secret key for message not found.");
        }

        InputStream clear = pbe.getDataStream(sKey, "BC");

        PGPObjectFactory plainFact = new PGPObjectFactory(clear);

        Object message = plainFact.nextObject();

        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());

            message = pgpFact.nextObject();
        }

        if (message instanceof PGPLiteralData) {
            PGPLiteralData ld = (PGPLiteralData) message;

            String outFileName = ld.getFileName();
            if (outFileName.length() == 0) {
                outFileName = defaultFileName;
            }

            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:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java

/**
 * decrypt the passed in message stream//from  www .j  a  va  2  s  . c om
 */
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.kontalk.crypto.Coder.java

License:Open Source License

private static DecryptionResult decryptAndVerify(InputStream encryptedStream, PersonalKey myKey,
        PGPPublicKey senderKey) {/*from  w w  w .j a  v  a  2 s. c om*/
    // note: the signature is inside the encrypted data

    DecryptionResult result = new DecryptionResult();

    PGPObjectFactory pgpFactory = new PGPObjectFactory(encryptedStream);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try { // catch all IO and PGP exceptions

        // the first object might be a PGP marker packet
        Object o = pgpFactory.nextObject(); // nullable
        if (!(o instanceof PGPEncryptedDataList)) {
            o = pgpFactory.nextObject(); // nullable
        }

        if (!(o instanceof PGPEncryptedDataList)) {
            LOGGER.warning("can't find encrypted data list in data");
            result.errors.add(Error.INVALID_DATA);
            return result;
        }
        PGPEncryptedDataList encDataList = (PGPEncryptedDataList) o;

        // check if secret key matches our encryption keyID
        Iterator<?> it = encDataList.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;
        long myKeyID = myKey.getPrivateEncryptionKey().getKeyID();
        while (sKey == null && it.hasNext()) {
            Object i = it.next();
            if (!(i instanceof PGPPublicKeyEncryptedData))
                continue;
            pbe = (PGPPublicKeyEncryptedData) i;
            if (pbe.getKeyID() == myKeyID)
                sKey = myKey.getPrivateEncryptionKey();
        }
        if (sKey == null || pbe == null) {
            LOGGER.warning("private key for message not found");
            result.errors.add(Error.INVALID_PRIVATE_KEY);
            return result;
        }

        InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey));

        PGPObjectFactory plainFactory = new PGPObjectFactory(clear);

        Object object = plainFactory.nextObject(); // nullable

        if (!(object instanceof PGPCompressedData)) {
            LOGGER.warning("data packet not compressed");
            result.errors.add(Error.INVALID_DATA);
            return result;
        }

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

        object = pgpFact.nextObject(); // nullable

        // the first object could be the signature list
        // get signature from it
        PGPOnePassSignature ops = null;
        if (object instanceof PGPOnePassSignatureList) {
            PGPOnePassSignatureList signatureList = (PGPOnePassSignatureList) object;
            // there is a signature list, so we assume the message is signed
            // (makes sense)
            result.signing = Signing.SIGNED;

            if (signatureList.isEmpty()) {
                LOGGER.warning("signature list is empty");
                result.errors.add(Error.INVALID_SIGNATURE_DATA);
            } else {
                ops = signatureList.get(0);
                ops.init(new BcPGPContentVerifierBuilderProvider(), senderKey);
            }
            object = pgpFact.nextObject(); // nullable
        } else {
            LOGGER.warning("signature list not found");
            result.signing = Signing.NOT;
        }

        if (!(object instanceof PGPLiteralData)) {
            LOGGER.warning("unknown packet type: " + object.getClass().getName());
            result.errors.add(Error.INVALID_DATA);
            return result;
        }

        PGPLiteralData ld = (PGPLiteralData) object;
        InputStream unc = ld.getInputStream();
        int ch;
        while ((ch = unc.read()) >= 0) {
            outputStream.write(ch);
            if (ops != null)
                try {
                    ops.update((byte) ch);
                } catch (SignatureException ex) {
                    LOGGER.log(Level.WARNING, "can't read signature", ex);
                }
        }

        result.decryptedStream = Optional.of(outputStream);

        if (ops != null) {
            result = verifySignature(result, pgpFact, ops);
        }

        // verify message integrity
        if (pbe.isIntegrityProtected()) {
            if (!pbe.verify()) {
                LOGGER.warning("message integrity check failed");
                result.errors.add(Error.INVALID_INTEGRITY);
            }
        } else {
            LOGGER.warning("message is not integrity protected");
            result.errors.add(Error.NO_INTEGRITY);
        }

    } catch (IOException | PGPException ex) {
        LOGGER.log(Level.WARNING, "can't decrypt message", ex);
        result.errors.add(Error.UNKNOWN_ERROR);
    }

    return result;
}

From source file:org.opentestsystem.delivery.testreg.transformer.GpgVerifier.java

License:Open Source License

public byte[] decryptAndVerify(File encryptedSignedFile) throws IOException, SignatureException, PGPException {

    byte[] output = null;

    InputStream in = PGPUtil.getDecoderStream(new FileInputStream(encryptedSignedFile));
    InputStream publicKeyIn = encryptor.getStreamForPath(publicKeyringLocation);

    ByteArrayOutputStream fOut = new ByteArrayOutputStream();

    PGPObjectFactory pgpF = new PGPObjectFactory(in);
    PGPEncryptedDataList enc;/*from www .  j a  v  a  2s.c om*/

    Object o = pgpF.nextObject();
    //
    // the first object might be a PGP marker packet.
    //

    while (!(o instanceof PGPEncryptedDataList)) {
        o = pgpF.nextObject();
    }

    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;

    while (sKey == null && it.hasNext()) {
        pbe = (PGPPublicKeyEncryptedData) it.next();
        InputStream secretKeyringInputStream = encryptor.getStreamForPath(secretKeyringLocation);

        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
                PGPUtil.getDecoderStream(secretKeyringInputStream));
        PGPSecretKey pgpSecKey = pgpSec.getSecretKey(pbe.getKeyID());
        if (pgpSecKey == null) {
            fail("could not find secret key");
        }

        PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(
                new BcPGPDigestCalculatorProvider()).build(LANDINGZONE_PASS);

        sKey = pgpSecKey.extractPrivateKey(decryptor);
    }

    if (sKey == null) {
        throw new IllegalArgumentException("secret key for message not found.");
    }

    InputStream clear = pbe
            .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));

    PGPObjectFactory plainFact = new PGPObjectFactory(clear);

    Object message = null;

    PGPOnePassSignatureList onePassSignatureList = null;
    PGPSignatureList signatureList = null;
    PGPCompressedData compressedData = null;

    message = plainFact.nextObject();
    ByteArrayOutputStream actualOutput = new ByteArrayOutputStream();

    while (message != null) {
        LOGGER.debug("decrypted message: " + message.toString());
        if (message instanceof PGPCompressedData) {
            compressedData = (PGPCompressedData) message;
            plainFact = new PGPObjectFactory(compressedData.getDataStream());
            message = plainFact.nextObject();
        }

        if (message instanceof PGPLiteralData) {
            // have to read it and keep it somewhere.
            Streams.pipeAll(((PGPLiteralData) message).getInputStream(), actualOutput);
        } else if (message instanceof PGPOnePassSignatureList) {
            onePassSignatureList = (PGPOnePassSignatureList) message;
        } else if (message instanceof PGPSignatureList) {
            signatureList = (PGPSignatureList) message;
        } else {
            throw new PGPException("message unknown message type.");
        }
        message = plainFact.nextObject();
    }
    actualOutput.close();
    PGPPublicKey publicKey = null;
    output = actualOutput.toByteArray();

    if (onePassSignatureList == null || signatureList == null) {
        throw new PGPException("Signatures not found.");
    } else {

        for (int i = 0; i < onePassSignatureList.size(); i++) {
            PGPOnePassSignature ops = onePassSignatureList.get(0);
            LOGGER.debug("verifier : " + ops.getKeyID());
            PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(
                    PGPUtil.getDecoderStream(publicKeyIn));
            publicKey = pgpRing.getPublicKey(ops.getKeyID());
            if (publicKey != null) {
                ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
                ops.update(output);
                PGPSignature signature = signatureList.get(i);
                // apparently the signature can only be verified once?? if the verify method is called a 2nd time it
                // will fail
                boolean signatureVerified = ops.verify(signature);
                assertThat(signatureVerified, is(true));
                if (signatureVerified) {
                    Iterator<?> userIds = publicKey.getUserIDs();
                    while (userIds.hasNext()) {
                        String userId = (String) userIds.next();
                        LOGGER.debug("Signed by " + userId);
                    }
                    LOGGER.debug("Signature verified");
                } else {
                    throw new SignatureException("Signature verification failed");
                }
            }
        }

    }

    if (pbe.isIntegrityProtected() && !pbe.verify()) {
        throw new PGPException("Data is integrity protected but integrity is lost.");
    } else if (publicKey == null) {
        throw new SignatureException("Signature not found");
    } else {
        fOut.write(output);
        fOut.flush();
        fOut.close();

        LOGGER.debug("decrypt and verify output: " + fOut.toString());
    }

    return output;
}