Example usage for org.bouncycastle.openpgp PGPLiteralData BINARY

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

Introduction

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

Prototype

char BINARY

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

Click Source Link

Document

Format tag for binary literal data

Usage

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

License:Apache License

/**
 * Encrypt plaintext message using public key from publickeyFile.
 *
 * @param message/*from  ww  w. ja  v a 2  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:eu.mrbussy.security.crypto.pgp.PGPEncryptor.java

License:Open Source License

public void encryptFile(File inputFile, File outputFile)
        throws IOException, NoSuchProviderException, PGPException {
    if (pedg == null) {
        pedg = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, checkIntegrity, new SecureRandom(), "BC");

        try {/* www  . j  av a2s .  co  m*/
            pedg.addMethod(publicKey);
        } catch (PGPException e) {
            throw new PGPException("Error when creating PGP encryptino data generator.");
        }
    }
    OutputStream fileOutStream = new FileOutputStream(outputFile);
    if (isArmored) {
        fileOutStream = new ArmoredOutputStream(fileOutStream);
    }

    OutputStream encryptdOutStream = pedg.open(fileOutStream, new byte[1 << 16]);
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    OutputStream compressedOutStream = comData.open(encryptdOutStream);

    try {
        PGPSignatureGenerator sg = null;
        if (isSigning) {
            InputStream keyInputStream = new FileInputStream(new File(signingPrivateKeyFilePath));
            PGPSecretKey secretKey = PGPUtils.findSecretKey(keyInputStream);
            PGPPrivateKey privateKey = secretKey.extractPrivateKey(signingPrivateKeyPassword.toCharArray(),
                    "BC");
            sg = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
            sg.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);
            Iterator it = secretKey.getPublicKey().getUserIDs();
            if (it.hasNext()) {
                PGPSignatureSubpacketGenerator ssg = new PGPSignatureSubpacketGenerator();
                ssg.setSignerUserID(false, (String) it.next());
                sg.setHashedSubpackets(ssg.generate());
            }
            sg.generateOnePassVersion(false).encode(compressedOutStream);
        }

        PGPLiteralDataGenerator lg = new PGPLiteralDataGenerator();
        OutputStream literalDataOutStream = lg.open(compressedOutStream, PGPLiteralData.BINARY, inputFile);

        byte[] bytes = IOUtils.toByteArray(new FileInputStream(inputFile));

        literalDataOutStream.write(bytes);
        if (isSigning) {
            sg.update(bytes);
            sg.generate().encode(compressedOutStream);
        }
        literalDataOutStream.close();
        lg.close();
        compressedOutStream.close();
        comData.close();
        pedg.close();
        fileOutStream.close();
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    }
}

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

License:Open Source License

static byte[] compressFile(String fileName, int algorithm) throws IOException {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm);
    PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
    comData.close();/*w  w  w .  j  a va2 s  . c o m*/
    return bOut.toByteArray();
}

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

public static byte[] compressFile(String fileName, int algorithm) throws IOException {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm);
    PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
    comData.close();/*w  w w  .j a  va2 s. co  m*/
    return bOut.toByteArray();
}

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  w  ww .j a  v a2s .c  o m

    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.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   ww w  . j  a  va  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.");
    }//  www  .  j  a v a 2s.c om
    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.nifi.processors.standard.util.PGPUtil.java

License:Apache License

public static void encrypt(InputStream in, OutputStream out, String algorithm, String provider, int cipher,
        String filename, PGPKeyEncryptionMethodGenerator encryptionMethodGenerator)
        throws IOException, PGPException {
    if (StringUtils.isEmpty(algorithm)) {
        throw new IllegalArgumentException("The algorithm must be specified");
    }/*ww  w.  j  a  v  a  2  s  .com*/
    final boolean isArmored = EncryptContent.isPGPArmoredAlgorithm(algorithm);
    OutputStream output = out;
    if (isArmored) {
        output = new ArmoredOutputStream(out);
    }

    // Default value, do not allow null encryption
    if (cipher == PGPEncryptedData.NULL) {
        logger.warn("Null encryption not allowed; defaulting to AES-128");
        cipher = PGPEncryptedData.AES_128;
    }

    try {
        // TODO: Can probably hard-code provider to BC and remove one method parameter
        PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(cipher).setWithIntegrityPacket(true)
                        .setSecureRandom(new SecureRandom()).setProvider(provider));

        encryptedDataGenerator.addMethod(encryptionMethodGenerator);

        try (OutputStream encryptedOut = encryptedDataGenerator.open(output, new byte[BUFFER_SIZE])) {
            PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(
                    PGPCompressedData.ZIP, Deflater.BEST_SPEED);
            try (OutputStream compressedOut = compressedDataGenerator.open(encryptedOut,
                    new byte[BUFFER_SIZE])) {
                PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
                try (OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY,
                        filename, new Date(), new byte[BUFFER_SIZE])) {

                    final byte[] buffer = new byte[BLOCK_SIZE];
                    int len;
                    while ((len = in.read(buffer)) > -1) {
                        literalOut.write(buffer, 0, len);
                    }
                }
            }
        }
    } finally {
        if (isArmored) {
            output.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// w w w  .jav  a2 s.  c  o m
 * @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.mule.module.pgp.EncryptStreamTransformer.java

License:Open Source License

/**
 * {@inheritDoc}//w  w  w . j  a v a 2 s.c o m
 */
@Override
public void initialize(OutputStream out) throws Exception {
    armoredOut = new ArmoredOutputStream(out);
    PGPEncryptedDataGenerator encrDataGen = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, false,
            new SecureRandom(), "BC");
    encrDataGen.addMethod(this.publicKey);
    encryptedOutputStream = encrDataGen.open(armoredOut, new byte[1 << 16]);

    PGPCompressedDataGenerator comprDataGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    compressedEncryptedOutputStream = comprDataGen.open(encryptedOutputStream);

    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
    pgpOutputStream = lData.open(compressedEncryptedOutputStream, PGPLiteralData.BINARY, "stream", new Date(),
            new byte[1 << 16]);
}