Example usage for org.bouncycastle.openpgp PGPEncryptedDataList size

List of usage examples for org.bouncycastle.openpgp PGPEncryptedDataList size

Introduction

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

Prototype

public int size() 

Source Link

Document

Gets the number of encryption methods in this list.

Usage

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

License:Open Source License

/**
 * Decrypt the specified (PKE) input file.
 * /*from   w  w w .j  a v a 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 w  w  . j av  a  2 s. com
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:google.registry.rde.BouncyCastleTest.java

License:Open Source License

@Test
public void testEncryptDecrypt_ExplicitStyle() throws Exception {
    int bufferSize = 64 * 1024;

    // Alice loads Bob's "publicKey" into memory.
    PGPPublicKeyRing publicKeyRing = new BcPGPPublicKeyRing(PUBLIC_KEY);
    PGPPublicKey publicKey = publicKeyRing.getPublicKey();

    // Alice encrypts the secret message for Bob using his "publicKey".
    PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(AES_128));
    encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
    byte[] encryptedData;
    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) {
            output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
        }/*ww w.jav  a2  s . c o m*/
        encryptedData = output.toByteArray();
    }
    logger.info("Encrypted data: " + dumpHex(encryptedData));

    // Bob loads his "privateKey" into memory.
    PGPSecretKeyRing privateKeyRing = new BcPGPSecretKeyRing(PRIVATE_KEY);
    PGPPrivateKey privateKey = extractPrivateKey(privateKeyRing.getSecretKey());

    // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
    try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
        PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
        PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
        assertThat(encDataList.size()).isEqualTo(1);
        PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
        assertThat(encData.getKeyID()).isEqualTo(publicKey.getKeyID());
        assertThat(encData.getKeyID()).isEqualTo(privateKey.getKeyID());
        try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
            assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
                    .isEqualTo(FALL_OF_HYPERION_A_DREAM);
        }
    }
}

From source file:google.registry.rde.BouncyCastleTest.java

License:Open Source License

@Test
public void testEncryptDecrypt_KeyRingStyle() throws Exception {
    int bufferSize = 64 * 1024;

    // Alice loads Bob's "publicKey" into memory from her public key ring.
    PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY)));
    PGPPublicKeyRing publicKeyRing = publicKeyRings.getKeyRings("eric@bouncycastle.org", true, true).next();
    PGPPublicKey publicKey = publicKeyRing.getPublicKey();

    // Alice encrypts the secret message for Bob using his "publicKey".
    PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(AES_128));
    encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
    byte[] encryptedData;
    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        try (OutputStream output2 = encryptor.open(output, new byte[bufferSize])) {
            output2.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
        }/*  w  w w.j a  v  a2s  .  c o  m*/
        encryptedData = output.toByteArray();
    }
    logger.info("Encrypted data: " + dumpHex(encryptedData));

    // Bob loads his chain of private keys into memory.
    PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY)));

    // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
    try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
        PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
        PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
        assertThat(encDataList.size()).isEqualTo(1);
        PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
        // Bob loads the private key to which the message is addressed.
        PGPPrivateKey privateKey = extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID()));
        try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
            assertThat(CharStreams.toString(new InputStreamReader(original, UTF_8)))
                    .isEqualTo(FALL_OF_HYPERION_A_DREAM);
        }
    }
}

From source file:google.registry.rde.BouncyCastleTest.java

License:Open Source License

@Test
public void testCompressEncryptDecryptDecompress_KeyRingStyle() throws Exception {
    int bufsz = 64 * 1024;

    // Alice loads Bob's "publicKey" into memory from her public key ring.
    PGPPublicKeyRingCollection publicKeyRings = new BcPGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PUBLIC_KEY)));
    PGPPublicKeyRing publicKeyRing = publicKeyRings.getKeyRings("eric@bouncycastle.org", true, true).next();
    PGPPublicKey publicKey = publicKeyRing.getPublicKey();

    // Alice encrypts the secret message for Bob using his "publicKey".
    PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(AES_128));
    encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
    byte[] encryptedData;
    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        try (OutputStream output2 = encryptor.open(output, new byte[bufsz])) {
            PGPCompressedDataGenerator kompressor = new PGPCompressedDataGenerator(ZIP);
            try (OutputStream output3 = kompressor.open(output2, new byte[bufsz])) {
                output3.write(FALL_OF_HYPERION_A_DREAM.getBytes(UTF_8));
            }//  www .ja v  a 2s.  co m
        }
        encryptedData = output.toByteArray();
    }
    logger.info("Encrypted data: " + dumpHex(encryptedData));

    // Bob loads his chain of private keys into memory.
    PGPSecretKeyRingCollection privateKeyRings = new BcPGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(PRIVATE_KEY)));

    // Bob decrypt's the OpenPGP message (w/ ciphertext) using his "privateKey".
    try (ByteArrayInputStream input = new ByteArrayInputStream(encryptedData)) {
        PGPObjectFactory pgpFact = new BcPGPObjectFactory(input);
        PGPEncryptedDataList encDataList = (PGPEncryptedDataList) pgpFact.nextObject();
        assertThat(encDataList.size()).isEqualTo(1);
        PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) encDataList.get(0);
        // Bob loads the private key to which the message is addressed.
        PGPPrivateKey privateKey = extractPrivateKey(privateKeyRings.getSecretKey(encData.getKeyID()));
        try (InputStream original = encData.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey))) {
            pgpFact = new BcPGPObjectFactory(original);
            PGPCompressedData kompressedData = (PGPCompressedData) pgpFact.nextObject();
            try (InputStream orig2 = kompressedData.getDataStream()) {
                assertThat(CharStreams.toString(new InputStreamReader(orig2, UTF_8)))
                        .isEqualTo(FALL_OF_HYPERION_A_DREAM);
            }
        }
    }
}

From source file:google.registry.rde.Ghostryde.java

License:Open Source License

/**
 * Opens a new {@link Decryptor} (Reading Step 1/3)
 *
 * <p>This is the first step in opening a ghostryde file. After this method, you'll want to
 * call {@link #openDecompressor(Decryptor)}.
 *
 * @param input is an {@link InputStream} of the ghostryde file data.
 * @param privateKey is the private encryption key of the recipient (which is us!)
 * @throws IOException/*from ww  w  .j a  v a  2 s  .c o m*/
 * @throws PGPException
 */
@CheckReturnValue
public Decryptor openDecryptor(@WillNotClose InputStream input, PGPPrivateKey privateKey)
        throws IOException, PGPException {
    checkNotNull(privateKey, "privateKey");
    PGPObjectFactory fact = new BcPGPObjectFactory(checkNotNull(input, "input"));
    PGPEncryptedDataList crypts = pgpCast(fact.nextObject(), PGPEncryptedDataList.class);
    checkState(crypts.size() > 0);
    if (crypts.size() > 1) {
        logger.warningfmt("crypts.size() is %d (should be 1)", crypts.size());
    }
    PGPPublicKeyEncryptedData crypt = pgpCast(crypts.get(0), PGPPublicKeyEncryptedData.class);
    if (crypt.getKeyID() != privateKey.getKeyID()) {
        throw new PGPException(String.format("Message was encrypted for keyid %x but ours is %x",
                crypt.getKeyID(), privateKey.getKeyID()));
    }
    return new Decryptor(crypt.getDataStream(new BcPublicKeyDataDecryptorFactory(privateKey)), crypt);
}

From source file:org.apache.camel.converter.crypto.PGPDataFormat.java

License:Apache License

@SuppressWarnings("resource")
public Object unmarshal(Exchange exchange, InputStream encryptedStream) throws Exception {
    if (encryptedStream == null) {
        return null;
    }//w  w  w .  j  a va2 s  .c  om
    InputStream in = PGPUtil.getDecoderStream(encryptedStream);
    PGPObjectFactory pgpFactory = new PGPObjectFactory(in);
    Object o = pgpFactory.nextObject();
    // the first object might be a PGP marker packet 
    PGPEncryptedDataList enc;
    if (o instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) o;
    } else {
        enc = (PGPEncryptedDataList) pgpFactory.nextObject();
    }

    PGPPublicKeyEncryptedData pbe = null;
    PGPPrivateKey key = null;
    // find encrypted data for which a private key exists in the secret key ring
    for (int i = 0; i < enc.size() && key == null; i++) {
        pbe = (PGPPublicKeyEncryptedData) enc.get(i);
        key = PGPDataFormatUtil.findPrivateKeyWithKeyId(exchange.getContext(), findKeyFileName(exchange),
                findEncryptionKeyRing(exchange), pbe.getKeyID(), findKeyPassword(exchange),
                getPassphraseAccessor(), getProvider());
    }
    if (key == null) {
        throw new PGPException("Provided input is encrypted with unknown pair of keys.");
    }

    InputStream encData = pbe
            .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(getProvider()).build(key));
    pgpFactory = new PGPObjectFactory(encData);
    PGPCompressedData comData = (PGPCompressedData) pgpFactory.nextObject();
    pgpFactory = new PGPObjectFactory(comData.getDataStream());
    Object object = pgpFactory.nextObject();

    PGPOnePassSignature signature;
    if (object instanceof PGPOnePassSignatureList) {
        signature = getSignature(exchange, (PGPOnePassSignatureList) object);
        object = pgpFactory.nextObject();
    } else {
        signature = null;
    }

    PGPLiteralData ld = (PGPLiteralData) object;
    InputStream litData = ld.getInputStream();

    // enable streaming via OutputStreamCache
    CachedOutputStream cos;
    ByteArrayOutputStream bos;
    OutputStream os;
    if (exchange.getContext().getStreamCachingStrategy().isEnabled()) {
        cos = new CachedOutputStream(exchange);
        bos = null;
        os = cos;
    } else {
        cos = null;
        bos = new ByteArrayOutputStream();
        os = bos;
    }

    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = litData.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
            if (signature != null) {
                signature.update(buffer, 0, bytesRead);
            }
            os.flush();
        }
    } finally {
        IOHelper.close(os, litData, encData, in);
    }

    if (signature != null) {
        PGPSignatureList sigList = (PGPSignatureList) pgpFactory.nextObject();
        if (!signature.verify(getSignatureWithKeyId(signature.getKeyID(), sigList))) {
            throw new SignatureException("Cannot verify PGP signature");
        }
    }

    if (cos != null) {
        return cos.newStreamCache();
    } else {
        return bos.toByteArray();
    }
}

From source file:org.apache.camel.converter.crypto.PGPKeyAccessDataFormat.java

License:Apache License

private InputStream getDecryptedData(Exchange exchange, InputStream encryptedStream)
        throws Exception, PGPException {
    PGPObjectFactory pgpFactory = new PGPObjectFactory(encryptedStream);
    Object firstObject = pgpFactory.nextObject();
    // the first object might be a PGP marker packet 
    PGPEncryptedDataList enc = getEcryptedDataList(pgpFactory, firstObject);

    if (enc == null) {
        throw getFormatException();
    }/* ww w  .  j  a v  a  2 s.  c  o m*/
    PGPPublicKeyEncryptedData pbe = null;
    PGPPrivateKey key = null;
    // find encrypted data for which a private key exists in the secret key ring
    for (int i = 0; i < enc.size() && key == null; i++) {
        Object encryptedData = enc.get(i);
        if (!(encryptedData instanceof PGPPublicKeyEncryptedData)) {
            throw getFormatException();
        }
        pbe = (PGPPublicKeyEncryptedData) encryptedData;
        key = secretKeyAccessor.getPrivateKey(exchange, pbe.getKeyID());
        if (key != null) {
            // take the first key
            break;
        }
    }
    if (key == null) {
        throw new PGPException(
                "PGP message is encrypted with a key which could not be found in the Secret Keyring.");
    }

    InputStream encData = pbe
            .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(getProvider()).build(key));
    return encData;
}