Example usage for org.bouncycastle.openpgp PGPCompressedDataGenerator PGPCompressedDataGenerator

List of usage examples for org.bouncycastle.openpgp PGPCompressedDataGenerator PGPCompressedDataGenerator

Introduction

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

Prototype

public PGPCompressedDataGenerator(int algorithm, int compression) 

Source Link

Document

Construct a new compressed data generator.

Usage

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");
    }//  www .  jav  a 2 s  .  c  o m
    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();
        }
    }
}