Example usage for org.bouncycastle.openpgp PGPLiteralData CONSOLE

List of usage examples for org.bouncycastle.openpgp PGPLiteralData CONSOLE

Introduction

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

Prototype

String CONSOLE

To view the source code for org.bouncycastle.openpgp PGPLiteralData CONSOLE.

Click Source Link

Document

The special name indicating a "for your eyes only" packet.

Usage

From source file:com.ginema.crypto.encryption.PGPEncryption.java

License:Apache License

/**
 * Simple PGP encryptor between byte[]./*from ww w .  ja v a 2  s .  c om*/
 * 
 * @param clearData The test to be encrypted
 * @param passPhrase The pass phrase (key). This method assumes that the key is a simple pass
 *        phrase, and does not yet support RSA or more sophisiticated keying.
 * @param fileName File name. This is used in the Literal Data Packet (tag 11) which is really
 *        inly important if the data is to be related to a file to be recovered later. Because
 *        this routine does not know the source of the information, the caller can set something
 *        here for file name use that will be carried. If this routine is being used to encrypt
 *        SOAP MIME bodies, for example, use the file name from the MIME type, if applicable. Or
 *        anything else appropriate.
 * 
 * @param armor
 * 
 * @return encrypted data.
 * @exception IOException
 * @exception PGPException
 * @exception NoSuchProviderException
 */
private static byte[] _doEncrypt(byte[] clearData, PGPPublicKey encKey, String fileName,
        boolean withIntegrityCheck, boolean armor) throws IOException, PGPException, NoSuchProviderException {
    if (fileName == null) {
        fileName = PGPLiteralData.CONSOLE;
    }

    ByteArrayOutputStream encOut = new ByteArrayOutputStream();

    OutputStream out = encOut;
    if (armor) {
        out = new ArmoredOutputStream(out);
    }

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
    OutputStream cos = comData.open(bOut); // open it with the final
    // destination
    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();

    // we want to generate compressed data. This might be a user option
    // later,
    // in which case we would pass in bOut.
    OutputStream pOut = lData.open(cos, // the compressed output stream
            PGPLiteralData.BINARY, fileName, // "filename" to store
            clearData.length, // length of clear data
            new Date() // current time
    );
    pOut.write(clearData);

    lData.close();
    comData.close();

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, withIntegrityCheck,
            new SecureRandom(), "BC");

    cPk.addMethod(encKey);

    byte[] bytes = bOut.toByteArray();

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

    cOut.write(bytes); // obtain the actual bytes from the compressed stream

    cOut.close();

    out.close();

    return encOut.toByteArray();
}

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.");
    }//w  ww.  ja  v  a  2  s .  c o  m

    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 ww.  j av  a 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.tramaci.onionmail.PGP.java

License:Open Source License

@SuppressWarnings({ "deprecation" })
public static byte[] encrypt(byte[] clearData, PGPPublicKey encKey, String fileName, boolean withIntegrityCheck,
        boolean armor, Date At, int PGPEncryptedDataAlgo) throws Exception {
    if (fileName == null)
        fileName = PGPLiteralData.CONSOLE;
    ByteArrayOutputStream encOut = new ByteArrayOutputStream();

    OutputStream out = encOut;/*from   ww  w . java2 s  .  co  m*/
    if (armor)
        out = new ArmoredOutputStream(out);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
    OutputStream cos = comData.open(bOut);
    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();

    OutputStream pOut = lData.open(cos, PGPLiteralData.BINARY, fileName, clearData.length, At);
    pOut.write(clearData);

    lData.close();
    comData.close();
    if (PGPEncryptedDataAlgo == 0)
        PGPEncryptedDataAlgo = PGPEncryptedData.CAST5;
    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataAlgo, withIntegrityCheck,
            new SecureRandom(), "BC");
    cPk.addMethod(encKey);

    byte[] bytes = bOut.toByteArray();
    OutputStream cOut = cPk.open(out, bytes.length);
    cOut.write(bytes);
    cOut.close();
    out.close();
    return encOut.toByteArray();
}

From source file:ubicrypt.core.crypto.PGPEC.java

License:Open Source License

public static InputStream encrypt(final List<PGPPublicKey> pks, final InputStream clearBytes) {
    final PipedInputStream pis = new PipedInputStream();
    final AtomicReference<PipedOutputStream> pos = new AtomicReference<>();
    final AtomicReference<OutputStream> pgpOut = new AtomicReference<>();
    final AtomicReference<OutputStream> lout = new AtomicReference<>();
    try {/*from w w w .  j a va  2s  . co m*/
        pos.set(new PipedOutputStream(pis));
        final PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();

        final PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256).setWithIntegrityPacket(true)
                        .setProvider("BC").setSecureRandom(new SecureRandom()));

        pks.stream().forEach(
                pk -> cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(pk).setProvider("BC")));
        pgpOut.set(cPk.open(pos.get(), new byte[1 << 16]));
        lout.set(lData.open(pgpOut.get(), PGPLiteralDataGenerator.BINARY, PGPLiteralData.CONSOLE, new Date(),
                new byte[1 << 64]));

        Observable.create(new OnSubscribeInputStream(clearBytes, 1 << 64)).subscribeOn(Schedulers.io())
                .doOnCompleted(() -> Utils.close(lout.get(), pgpOut.get(), pos.get())).doOnError(err -> {
                    log.error("error on encrypt", err);
                    Utils.close(clearBytes, lout.get(), pgpOut.get(), pos.get());
                }).subscribe(ConsumerExp.silent(lout.get()::write));
    } catch (final Exception e) {
        Utils.close(clearBytes, lout.get(), pgpOut.get(), pos.get());
        Throwables.propagate(e);
    }
    return pis;
}