Example usage for org.bouncycastle.openpgp.operator.bc BcPGPDataEncryptorBuilder BcPGPDataEncryptorBuilder

List of usage examples for org.bouncycastle.openpgp.operator.bc BcPGPDataEncryptorBuilder BcPGPDataEncryptorBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.bc BcPGPDataEncryptorBuilder BcPGPDataEncryptorBuilder.

Prototype

public BcPGPDataEncryptorBuilder(int encAlgorithm) 

Source Link

Document

Constructs a new data encryptor builder for a specified cipher type.

Usage

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

License:Apache License

@Override
public void encrypt(final OutputStream outputStream, final InputStream inputStream, final String[] keyInfo) {

    try {/*from   w  ww  .  j  a  va2s.  c om*/
        // =
        // this.readPublicKey(this.publicKeyRing);

        final ArmoredOutputStream out = new ArmoredOutputStream(outputStream);

        try {
            final BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(
                    SymmetricKeyAlgorithmTags.CAST5);
            builder.setSecureRandom(new SecureRandom());
            final PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(builder, true);
            for (final String info : keyInfo) {
                final PGPPublicKey encKey = this.getEncryptionKey(info);
                if (encKey != null) {
                    cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
                } else {
                    OpenPGPSecurityUtility.LOGGER
                            .info("Encryption key for recipient " + info + " could not be found!");
                }

            }

            final OutputStream cOut = cPk.open(out, new byte[1 << 16]);

            final PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
                    CompressionAlgorithmTags.ZIP);

            final PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
            final byte[] buffer = new byte[1 << 16];
            final OutputStream pOut = lData.open(comData.open(cOut), PGPLiteralData.BINARY, "", new Date(),
                    buffer);

            final byte[] buf = new byte[buffer.length];
            int len;

            while ((len = inputStream.read(buf)) > 0) {
                pOut.write(buf, 0, len);
            }

            lData.close();
            inputStream.close();

            comData.close();

            cOut.close();

            out.close();

        } catch (final PGPException e) {
            System.err.println(e);
            if (e.getUnderlyingException() != null) {
                e.getUnderlyingException().printStackTrace();
            }
        }
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.arcusx.simplepgp.PgpDataEncryptor.java

public void encryptAndSign(InputStream dataIn, InputStream recipientPublicKeyFileIn, String dataFileName,
        InputStream senderPrivateKeyFileIn, OutputStream dataOut, boolean isArmoredOutput)
        throws IOException, PGPException {
    PGPCompressedDataGenerator comData = null;
    try {/*from  w  w  w  . j av a 2 s  .c o m*/
        OutputStream out = dataOut;
        PGPPublicKey recipientPublicKey = PgpKeyUtils.readPublicKey(recipientPublicKeyFileIn);

        if (isArmoredOutput) {
            out = new ArmoredOutputStream(out);
        }

        BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
        dataEncryptor.setWithIntegrityPacket(true);
        dataEncryptor.setSecureRandom(new SecureRandom());

        PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
        encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(recipientPublicKey));

        OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);

        // Initialize compressed data generator
        PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(
                PGPCompressedData.ZIP);
        OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE]);

        // Initialize signature generator
        final PGPSecretKey senderSecretKey = PgpKeyUtils.findSecretKey(senderPrivateKeyFileIn);
        PGPPrivateKey privateKey = PgpKeyUtils.getPrivateKeyFrom(senderSecretKey);

        PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(
                senderSecretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1);

        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder);
        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);

        PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator();
        signatureSubpacketGenerator.setSignerUserID(false, PgpKeyUtils.getUserIdFrom(senderSecretKey));
        signatureGenerator.setHashedSubpackets(signatureSubpacketGenerator.generate());
        signatureGenerator.generateOnePassVersion(false).encode(compressedOut);

        // Initialize literal data generator
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, dataFileName,
                new Date(), new byte[BUFFER_SIZE]);

        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = dataIn.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            signatureGenerator.update(buf, 0, len);
        }
        dataIn.close();
        literalDataGenerator.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        signatureGenerator.generate().encode(compressedOut);
        compressedDataGenerator.close();
        encryptedDataGenerator.close();
        if (isArmoredOutput) {
            out.close();
        }
    } finally {
        if (comData != null) {
            comData.close();
        }
        IOUtils.closeQuietly(dataOut);
    }
}

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

public static byte[] encryptPGP(byte[] data, PGPPublicKey key, boolean armored, String name,
        int compressionAlgorithm, int encAlgorithm) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    OutputStream out = armored ? new ArmoredOutputStream(baos) : baos;

    BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(encAlgorithm);
    dataEncryptor.setWithIntegrityPacket(true);
    dataEncryptor.setSecureRandom(CryptoHelper.getSecureRandom());

    PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
    encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key));

    try {//from ww  w  . jav  a  2 s. c o m
        OutputStream encout = encryptedDataGenerator.open(out, 1024);

        PGPCompressedDataGenerator pgpcdg = new PGPCompressedDataGenerator(compressionAlgorithm);
        OutputStream compout = pgpcdg.open(encout);

        PGPLiteralDataGenerator pgpldg = new PGPLiteralDataGenerator(false);
        OutputStream ldout = pgpldg.open(compout, PGPLiteralData.BINARY, name, data.length, PGPLiteralData.NOW);

        ldout.write(data);
        ldout.close();
        compout.close();
        encout.close();
        out.close();
        baos.close();

        return baos.toByteArray();
    } catch (PGPException pgpe) {
        throw new IOException(pgpe);
    }
}

From source file:dorkbox.util.crypto.CryptoPGP.java

License:Apache License

/**
 * Encrypt plaintext message using public key from publickeyFile.
 *
 * @param message//  w ww  .j  a  v a2 s.c  o m
 *                 the message
 *
 * @return the string
 */
private String encrypt(InputStream publicKeyInputStream, String message)
        throws PGPException, IOException, NoSuchProviderException {
    // find the PGP key in the file
    PGPPublicKey publicKey = findPublicGPGKey(publicKeyInputStream);

    if (publicKey == null) {
        System.err.println("Did not find public GPG key");
        return null;
    }

    // Encode the string into bytes using utf-8
    byte[] utf8Bytes = message.getBytes(OS.UTF_8);

    ByteArrayOutputStream compressedOutput = new ByteArrayOutputStream();

    // compress bytes with zip
    PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();

    // the reason why we compress here is GPG not being able to decrypt our message input but if we do not compress.
    // I guess pkzip compression also encodes only to GPG-friendly characters.
    PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(
            CompressionAlgorithmTags.ZIP);
    try {
        OutputStream literalDataOutput = literalDataGenerator.open(compressedOutput, PGPLiteralData.BINARY,
                "_CONSOLE", utf8Bytes.length, new Date());
        // update bytes in the stream
        literalDataOutput.write(utf8Bytes);
    } catch (IOException e) {
        // catch but close the streams in finally
        throw e;
    } finally {
        compressedDataGenerator.close();
        IO.close(compressedOutput);
    }

    SecureRandom random = new SecureRandom();

    // now we have zip-compressed bytes
    byte[] compressedBytes = compressedOutput.toByteArray();

    BcPGPDataEncryptorBuilder bcPGPDataEncryptorBuilder = new BcPGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
            .setWithIntegrityPacket(true).setSecureRandom(random);

    PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(bcPGPDataEncryptorBuilder);

    // use public key to encrypt data

    BcPublicKeyKeyEncryptionMethodGenerator encKeyGen = new BcPublicKeyKeyEncryptionMethodGenerator(publicKey)
            .setSecureRandom(random);

    encryptedDataGenerator.addMethod(encKeyGen);

    // literalDataOutput --> compressedOutput --> ArmoredOutputStream --> ByteArrayOutputStream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ArmoredOutputStream armoredOut = new ArmoredOutputStream(byteArrayOutputStream);
    OutputStream encryptedOutput = null;
    try {
        encryptedOutput = encryptedDataGenerator.open(armoredOut, compressedBytes.length);
        encryptedOutput.write(compressedBytes);
    } catch (IOException e) {
        throw e;
    } catch (PGPException e) {
        throw e;
    } finally {
        IO.close(encryptedOutput);
        IO.close(armoredOut);
    }
    String encrypted = new String(byteArrayOutputStream.toByteArray());

    System.err.println("Message: " + message);
    System.err.println("Encrypted: " + encrypted);

    return encrypted;
}

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));
        }/*from   w  ww.jav a 2s. 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 ww  .  j  a  v a 2  s . 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));
            }/*w  w  w  . ja va  2s  . 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))) {
            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:net.tjado.passwdsafe.UsbGpgBackupActivity.java

License:Open Source License

public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey)
        throws IOException, PGPException {
    Security.addProvider(new BouncyCastleProvider());

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);

    PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
    comData.close();//from  ww  w .jav a  2 s. com

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
            new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256).setSecureRandom(new SecureRandom())
                    .setWithIntegrityPacket(true));
    cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));

    byte[] bytes = bOut.toByteArray();

    OutputStream cOut;
    cOut = cPk.open(out, bytes.length);
    cOut.write(bytes);
    cOut.close();

    out.close();
}

From source file:org.kontalk.crypto.Coder.java

License:Open Source License

/**
 * Creates encrypted and signed message body.
 * Errors that may occur are saved to the message.
 * @param message//from   w ww.  ja  v  a 2 s .  c  om
 * @return the encrypted and signed text.
 */
public static Optional<byte[]> processOutMessage(OutMessage message) {
    if (message.getCoderStatus().getEncryption() != Encryption.DECRYPTED) {
        LOGGER.warning("message does not want to be encrypted");
        return Optional.empty();
    }

    LOGGER.info("encrypting message...");

    // get keys
    KeysResult keys = getKeys(message.getUser());
    if (keys.myKey == null || keys.otherKey == null) {
        message.setSecurityErrors(keys.errors);
        return Optional.empty();
    }

    // secure the message against the most basic attacks using Message/CPIM
    String from = keys.myKey.getUserId();
    String to = keys.otherKey.userID + "; ";
    String mime = "text/plain";
    // TODO encrypt more possible content
    String text = message.getContent().getPlainText();
    CPIMMessage cpim = new CPIMMessage(from, to, new Date(), mime, text);
    byte[] plainText;
    try {
        plainText = cpim.toByteArray();
    } catch (UnsupportedEncodingException ex) {
        LOGGER.log(Level.WARNING, "UTF-8 not supported", ex);
        plainText = cpim.toString().getBytes();
    }

    // setup data encryptor & generator
    BcPGPDataEncryptorBuilder encryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_192);
    encryptor.setWithIntegrityPacket(true);
    encryptor.setSecureRandom(new SecureRandom());

    // add public key recipients
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptor);
    //for (PGPPublicKey rcpt : mRecipients)
    encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(keys.otherKey.encryptKey));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(plainText);
    try { // catch all io and pgp exceptions

        OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]);

        // setup compressed data generator
        PGPCompressedDataGenerator compGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        OutputStream compressedOut = compGen.open(encryptedOut, new byte[BUFFER_SIZE]);

        // setup signature generator
        int algo = keys.myKey.getPublicEncryptionKey().getAlgorithm();
        PGPSignatureGenerator sigGen = new PGPSignatureGenerator(
                new BcPGPContentSignerBuilder(algo, HashAlgorithmTags.SHA1));
        sigGen.init(PGPSignature.BINARY_DOCUMENT, keys.myKey.getPrivateEncryptionKey());

        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, keys.myKey.getUserId());
        sigGen.setUnhashedSubpackets(spGen.generate());

        sigGen.generateOnePassVersion(false).encode(compressedOut);

        // Initialize literal data generator
        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalGen.open(compressedOut, PGPLiteralData.BINARY, "", new Date(),
                new byte[BUFFER_SIZE]);

        // read the "in" stream, compress, encrypt and write to the "out" stream
        // this must be done if clear data is bigger than the buffer size
        // but there are other ways to optimize...
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            try {
                sigGen.update(buf, 0, len);
            } catch (SignatureException ex) {
                LOGGER.log(Level.WARNING, "can't read data for signature", ex);
                message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
                return Optional.empty();
            }
        }

        in.close();
        literalGen.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        try {
            sigGen.generate().encode(compressedOut);
        } catch (SignatureException ex) {
            LOGGER.log(Level.WARNING, "can't create signature", ex);
            message.setSecurityErrors(EnumSet.of(Error.INVALID_SIGNATURE_DATA));
            return Optional.empty();
        }
        compGen.close();
        encGen.close();

    } catch (IOException | PGPException ex) {
        LOGGER.log(Level.WARNING, "can't encrypt message", ex);
        message.setSecurityErrors(EnumSet.of(Error.UNKNOWN_ERROR));
        return Optional.empty();
    }

    LOGGER.info("encryption successful");
    return Optional.of(out.toByteArray());
}

From source file:org.pgptool.gui.encryption.implpgp.EncryptionServicePgpImpl.java

License:Open Source License

private static PGPEncryptedDataGenerator buildEncryptedDataGenerator(Collection<PGPPublicKey> encKeys) {
    BcPGPDataEncryptorBuilder builder = new BcPGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
            .setSecureRandom(new SecureRandom()).setWithIntegrityPacket(true);
    PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(builder);

    for (PGPPublicKey encKey : encKeys) {
        encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
    }//from  w w  w .  j av  a2s. c o  m
    return encryptedDataGenerator;
}