Example usage for org.bouncycastle.openpgp.operator.jcajce JcePGPDataEncryptorBuilder JcePGPDataEncryptorBuilder

List of usage examples for org.bouncycastle.openpgp.operator.jcajce JcePGPDataEncryptorBuilder JcePGPDataEncryptorBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp.operator.jcajce JcePGPDataEncryptorBuilder JcePGPDataEncryptorBuilder.

Prototype

public JcePGPDataEncryptorBuilder(int encAlgorithm) 

Source Link

Document

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

Usage

From source file:com.bekwam.resignator.util.CryptUtils.java

License:Apache License

private byte[] encrypt(byte[] clearData, char[] passPhrase)
        throws IOException, PGPException, NoSuchProviderException {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    //// w w  w.j  a  v  a  2s .  co m
    // armor makes the encrypted output more readable (includes header, footer, printable chars)
    //

    OutputStream out = bOut;
    out = new ArmoredOutputStream(out);

    //
    // The standard jre installation limits keysize to 128.  Use the unlimited jars to go higher.
    //
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_128)
                    .setSecureRandom(new SecureRandom()).setProvider("BC"));

    encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase).setProvider("BC"));

    OutputStream encOut = encGen.open(out, clearData.length);

    encOut.write(clearData);
    encOut.close();

    out.close();

    return bOut.toByteArray();
}

From source file:com.goodvikings.cryptim.api.KeyRing.java

License:BEER-WARE LICENSE

public void signEncryptMessage(InputStream in, OutputStream out, String jid)
        throws IOException, PGPException, SignatureException {
    out = new ArmoredOutputStream(out);

    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SYMM_ALG)
            .setWithIntegrityPacket(true).setSecureRandom(rand).setProvider(PROVIDER));
    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(keys.get(jid)).setProvider(PROVIDER));

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

    PGPSignatureGenerator sGen = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(kp.getPrivateKey().getPublicKeyPacket().getAlgorithm(), HASH_ALG)
                    .setProvider(PROVIDER));
    sGen.init(PGPSignature.BINARY_DOCUMENT, kp.getPrivateKey());
    sGen.generateOnePassVersion(false).encode(compressedData);

    OutputStream finalOut = new PGPLiteralDataGenerator().open(compressedData, PGPLiteralData.BINARY, "",
            new Date(), new byte[BUFFER_SIZE]);

    byte[] buf = new byte[BUFFER_SIZE];
    int len;/*  w w w.  j a va  2s  . c  o m*/
    while ((len = in.read(buf)) > 0) {
        finalOut.write(buf, 0, len);
        sGen.update(buf, 0, len);
    }

    in.close();

    finalOut.close();
    sGen.generate().encode(compressedData);
    compressedData.close();
    encryptedOut.close();
    out.close();
}

From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java

License:Open Source License

public String getEncryptedMessage(byte[] data) {
    Security.addProvider(new BouncyCastleProvider());

    try {/*from w  ww.j a  va  2  s  .  com*/

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        OutputStream out = new ArmoredOutputStream(baos);
        byte[] compressedData = compressFile(data, CompressionAlgorithmTags.ZIP);
        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(this.publicKey).setProvider("BC"));
        OutputStream cOut = encGen.open(out, compressedData.length);
        cOut.write(compressedData);
        cOut.close();
        out.close();
        baos.flush();
        return new String(baos.toByteArray());
    } catch (PGPException | IOException e) {
        e.printStackTrace();
    }
    return null;
}

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

License:Open Source License

/**
 * Opens a new {@link Encryptor} (Writing Step 1/3)
 *
 * <p>This is the first step in creating a ghostryde file. After this method, you'll want to
 * call {@link #openCompressor(Encryptor)}.
 *
 * @param os is the upstream {@link OutputStream} to which the result is written.
 * @param publicKey is the public encryption key of the recipient.
 * @throws IOException//www.ja  va2  s  .  co m
 * @throws PGPException
 */
@CheckReturnValue
public Encryptor openEncryptor(@WillNotClose OutputStream os, PGPPublicKey publicKey)
        throws IOException, PGPException {
    PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(CIPHER).setWithIntegrityPacket(USE_INTEGRITY_PACKET)
                    .setSecureRandom(getRandom()).setProvider(PROVIDER_NAME));
    encryptor.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
    return new Encryptor(encryptor.open(os, new byte[bufferSize]));
}

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

License:Open Source License

private static OutputStream createDelegate(int bufferSize, OutputStream os, PGPPublicKey receiverKey) {
    try {/*  ww w .ja  v a2s .co  m*/
        PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(CIPHER).setWithIntegrityPacket(USE_INTEGRITY_PACKET)
                        .setSecureRandom(SecureRandom.getInstance(RANDOM_SOURCE)).setProvider(PROVIDER_NAME));
        encryptor.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(receiverKey));
        return encryptor.open(os, new byte[bufferSize]);
    } catch (NoSuchAlgorithmException e) {
        throw new ProviderException(e);
    } catch (IOException | PGPException e) {
        throw new RuntimeException(e);
    }
}

From source file:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java

private static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor,
        boolean withIntegrityCheck) throws IOException, NoSuchProviderException {
    if (armor) {/*from ww w.j  a  v a  2s .c o m*/
        out = new ArmoredOutputStream(out);
    }

    try {
        byte[] bytes = MyPGPUtil.compressFile(fileName, CompressionAlgorithmTags.ZIP);

        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5)
                        .setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom())
                        .setProvider("BC"));

        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));

        OutputStream cOut = encGen.open(out, bytes.length);

        cOut.write(bytes);
        cOut.close();

        if (armor) {
            out.close();
        }
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    }
}

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

License:Apache License

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    List<String> userids = determineEncryptionUserIds(exchange);
    List<PGPPublicKey> keys = PGPDataFormatUtil.findPublicKeys(exchange.getContext(), findKeyFileName(exchange),
            findEncryptionKeyRing(exchange), userids, true);
    if (keys.isEmpty()) {
        throw new IllegalArgumentException(
                "Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids
                        + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring.");
    }/*from  www .  java2 s  .  com*/

    InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);

    if (armored) {
        outputStream = new ArmoredOutputStream(outputStream);
    }

    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity)
                    .setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    // several keys can be added
    for (PGPPublicKey key : keys) {
        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key));
    }
    OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]);

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange));
    OutputStream comOut = new BufferedOutputStream(comData.open(encOut));

    PGPSignatureGenerator sigGen = createSignatureGenerator(exchange, comOut);

    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
    if (ObjectHelper.isEmpty(fileName)) {
        // This marks the file as For Your Eyes Only... may cause problems for the receiver if they use
        // an automated process to decrypt as the filename is appended with _CONSOLE
        fileName = PGPLiteralData.CONSOLE;
    }
    OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(),
            new byte[BUFFER_SIZE]);

    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            litOut.write(buffer, 0, bytesRead);
            if (sigGen != null) {
                sigGen.update(buffer, 0, bytesRead);
            }
            litOut.flush();
        }
    } finally {
        IOHelper.close(litOut);
        if (sigGen != null) {
            sigGen.generate().encode(comOut);
        }
        IOHelper.close(comOut, encOut, outputStream, input);
    }
}

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

License:Apache License

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    List<String> userids = determineEncryptionUserIds(exchange);
    List<PGPPublicKey> keys = publicKeyAccessor.getEncryptionKeys(exchange, userids);
    if (keys.isEmpty()) {
        throw new IllegalArgumentException(
                "Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids
                        + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring.");
    }/*w w w  .java  2 s.c  o  m*/
    exchange.getOut().setHeader(NUMBER_OF_ENCRYPTION_KEYS, Integer.valueOf(keys.size()));

    InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);

    if (armored) {
        outputStream = new ArmoredOutputStream(outputStream);
    }

    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
            new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity)
                    .setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    // several keys can be added
    for (PGPPublicKey key : keys) {
        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key));
    }
    OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]);

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange));
    OutputStream comOut = new BufferedOutputStream(comData.open(encOut));

    List<PGPSignatureGenerator> sigGens = createSignatureGenerator(exchange, comOut);

    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
    if (ObjectHelper.isEmpty(fileName)) {
        // This marks the file as For Your Eyes Only... may cause problems for the receiver if they use
        // an automated process to decrypt as the filename is appended with _CONSOLE
        fileName = PGPLiteralData.CONSOLE;
    }
    OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(),
            new byte[BUFFER_SIZE]);

    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            litOut.write(buffer, 0, bytesRead);
            if (sigGens != null && !sigGens.isEmpty()) {
                for (PGPSignatureGenerator sigGen : sigGens) {
                    // not nested therefore it is the same for all
                    // can this be improved that we only do it for one sigGen and set the result on the others?
                    sigGen.update(buffer, 0, bytesRead);
                }
            }
            litOut.flush();
        }
    } finally {
        IOHelper.close(litOut);
        if (sigGens != null && !sigGens.isEmpty()) {
            // reverse order
            for (int i = sigGens.size() - 1; i > -1; i--) {
                PGPSignatureGenerator sigGen = sigGens.get(i);
                sigGen.generate().encode(comOut);
            }
        }
        IOHelper.close(comOut, encOut, outputStream, input);
    }
}

From source file:org.apache.gobblin.crypto.GPGFileEncryptor.java

License:Apache License

/**
 * Taking in an input {@link OutputStream} and a passPhrase, return an {@link OutputStream} that can be used to output
 * encrypted output to the input {@link OutputStream}.
 * @param outputStream the output stream to hold the ciphertext {@link OutputStream}
 * @param passPhrase pass phrase//from w  ww  . j  a v  a 2  s . c om
 * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used.
 * @return {@link OutputStream} to write content to for encryption
 * @throws IOException
 */
public OutputStream encryptFile(OutputStream outputStream, String passPhrase, String cipher)
        throws IOException {
    try {
        if (Security.getProvider(PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher))
                        .setSecureRandom(new SecureRandom()).setProvider(PROVIDER_NAME));
        cPk.addMethod(
                new JcePBEKeyEncryptionMethodGenerator(passPhrase.toCharArray()).setProvider(PROVIDER_NAME));

        OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]);

        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream _literalOut = literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME,
                new Date(), new byte[BUFFER_SIZE]);

        return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream);
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.gobblin.crypto.GPGFileEncryptor.java

License:Apache License

/**
 * Taking in an input {@link OutputStream}, keyring inputstream and a passPhrase, generate an encrypted {@link OutputStream}.
 * @param outputStream {@link OutputStream} that will receive the encrypted content
 * @param keyIn keyring inputstream. This InputStream is owned by the caller.
 * @param keyId key identifier/*  w ww .java2 s.co  m*/
 * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used.
 * @return an {@link OutputStream} to write content to for encryption
 * @throws IOException
 */
public OutputStream encryptFile(OutputStream outputStream, InputStream keyIn, long keyId, String cipher)
        throws IOException {
    try {
        if (Security.getProvider(PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher))
                        .setSecureRandom(new SecureRandom()).setProvider(PROVIDER_NAME));

        PGPPublicKey publicKey;
        PGPPublicKeyRingCollection keyRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
                new BcKeyFingerprintCalculator());
        publicKey = keyRings.getPublicKey(keyId);

        if (publicKey == null) {
            throw new IllegalArgumentException("public key for encryption not found");
        }

        cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER_NAME));

        OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]);

        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream _literalOut = literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME,
                new Date(), new byte[BUFFER_SIZE]);

        return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream);
    } catch (PGPException e) {
        throw new IOException(e);
    }
}