Example usage for org.bouncycastle.bcpg CompressionAlgorithmTags ZIP

List of usage examples for org.bouncycastle.bcpg CompressionAlgorithmTags ZIP

Introduction

In this page you can find the example usage for org.bouncycastle.bcpg CompressionAlgorithmTags ZIP.

Prototype

int ZIP

To view the source code for org.bouncycastle.bcpg CompressionAlgorithmTags ZIP.

Click Source Link

Document

ZIP (RFC 1951) compression.

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 www .j a  va 2 s  .  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:de.sandmage.opportunisticmail.crypto.OpenPGP.java

License:Open Source License

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

    try {// www .jav a 2 s. c  o  m

        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:dorkbox.util.crypto.CryptoPGP.java

License:Apache License

/**
 * Encrypt plaintext message using public key from publickeyFile.
 *
 * @param message// w  w w.  j  a  v a2s  .co 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:gr.abiss.calipso.util.PgpUtils.java

License:Open Source License

public static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, boolean armor,
        boolean withIntegrityCheck) throws IOException, NoSuchProviderException {
    if (armor) {//from w  w  w. ja va 2 s.  c  o m
        out = new ArmoredOutputStream(out);
    }

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

        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5,
                withIntegrityCheck, new SecureRandom(), "BC");
        encGen.addMethod(encKey);

        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: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   www. ja v  a  2  s  . 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.opentestsystem.delivery.testreg.transformer.GPGEncryptor.java

License:Open Source License

/**
 * Uses the Legion of the Bouncy Castle (aka BouncyCastle) PGP API to encrypt, compress, and sign the input.
 * /*from ww  w .j a  v a2s  .co  m*/
 * The configured landing zone public key is used to encrypt the input. Only the landing zone private key will be
 * able to decrypt.
 * 
 * The configured test registration private key is used to sign the input. This can be verified by the landing zone
 * to prove that this specific test registration instance created the data.
 * 
 * @param input
 *            A byte array
 * @return A byte array comprised of a PGP/GPG compatible binary encrypted and signed output
 */
@Transformer
public Message<File> encryptStream(final File input, final @Header("dwBatchUuid") String dwBatchUuid,
        final @Header("fileSuffix") String fileSuffix, final @Header("recordsSent") int recordsSent,
        final @Header("tempPaths") List<Path> tempPaths,
        final @Header("dwConfigType") DwConfigType dwConfigType) {

    String debugPrefix = dwConfigType + " DW Config: ";

    long curTime = System.currentTimeMillis();
    File tmpEncFile;

    try {

        PGPPublicKey landingZonePubKey = findLandingZonePublicKey(dwConfigType);
        PGPSecretKey testRegSecretKey = findTestRegSecretKey();

        PGPPrivateKey testRegPrivateKey = testRegSecretKey.extractPrivateKey(
                new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(getPassphrase()));

        // ////////////////////
        // setup encryptor

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

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

        // This outputstream, encryptedSignedOutputStream is the ultimate target that will contain the encrypted and
        // signed output
        Path tempEncPath = Files.createTempFile(DwBatchHandler.DW_ENC_TMP_PREFIX,
                (dwConfigType == DwConfigType.SBAC ? DwBatchHandler.SBAC_DW_NAME : DwBatchHandler.LOCAL_DW_NAME)
                        + fileSuffix);
        tempPaths.add(tempEncPath);
        tmpEncFile = tempEncPath.toFile();
        FileOutputStream encryptedSignedOutputStream = new FileOutputStream(tmpEncFile);

        LOGGER.debug(debugPrefix + "Created temp encrypted output file " + tmpEncFile.getAbsolutePath());

        OutputStream encryptOutStream = encGen.open(encryptedSignedOutputStream, new byte[BUFFER_SIZE]);

        // ////////////////////////////
        // setup data compression

        PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
        OutputStream compressOutStream = comData.open(encryptOutStream);

        // /////////////////////
        // sign encrypted file with test reg private key

        // create a signature generator
        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
                new JcaPGPContentSignerBuilder(testRegSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                        .setProvider("BC"));
        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, testRegPrivateKey);

        @SuppressWarnings("unchecked")
        Iterator<String> it = testRegSecretKey.getPublicKey().getUserIDs();

        if (it.hasNext()) {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID(false, it.next());
            signatureGenerator.setHashedSubpackets(spGen.generate());
        }

        // setup signature generator to encode the contents of the compressed output stream
        signatureGenerator.generateOnePassVersion(false).encode(compressOutStream);

        // create a PGP Literal Data Generator and open it to wrap the compression output stream
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();

        OutputStream signedOutStream = lGen.open(compressOutStream, PGPLiteralData.BINARY, "",
                new java.util.Date(), new byte[BUFFER_SIZE]);

        // create an input stream out of the input bytes
        FileInputStream clearInputStream = new FileInputStream(input);

        // read the input and write all data to the signing output stream, also update the signature
        // generator with the same input data
        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = clearInputStream.read(buf)) > 0) {
            signedOutStream.write(buf, 0, len);
            signatureGenerator.update(buf, 0, len);
        }

        // close everything and generate the final signature
        signedOutStream.close();
        lGen.close();
        signatureGenerator.generate().encode(compressOutStream);
        compressOutStream.close();
        comData.close();
        encryptOutStream.close();
        encGen.close();
        clearInputStream.close();

        encryptedSignedOutputStream.close();

    } catch (IOException | PGPException | SignatureException e) {
        throw new GPGEncryptionException(debugPrefix + "Failure to encrypt and sign input", e);
    }

    LOGGER.debug(debugPrefix + "Generated encrypted data in " + (System.currentTimeMillis() - curTime));

    return MessageBuilder.withPayload(tmpEncFile).setHeader("dwBatchUuid", dwBatchUuid)
            .setHeader("fileSuffix", fileSuffix).setHeader("recordsSent", recordsSent)
            .setHeader("tempPaths", tempPaths).setHeader("dwConfigType", dwConfigType).build();
}

From source file:org.sufficientlysecure.keychain.support.KeyringBuilder.java

License:Open Source License

private static SignaturePacket createSignaturePacket(BigInteger signature) {
    MPInteger[] signatureArray = new MPInteger[] { new MPInteger(signature) };

    int signatureType = PGPSignature.POSITIVE_CERTIFICATION;
    int keyAlgorithm = SignaturePacket.RSA_GENERAL;
    int hashAlgorithm = HashAlgorithmTags.SHA1;

    SignatureSubpacket[] hashedData = new SignatureSubpacket[] {
            new SignatureCreationTime(false, SIGNATURE_DATE),
            new KeyFlags(false, KeyFlags.CERTIFY_OTHER + KeyFlags.SIGN_DATA),
            new KeyExpirationTime(false, TimeUnit.DAYS.toSeconds(2)),
            new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_SYM_ALGS, false,
                    new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192,
                            SymmetricKeyAlgorithmTags.AES_128, SymmetricKeyAlgorithmTags.CAST5,
                            SymmetricKeyAlgorithmTags.TRIPLE_DES }),
            new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_HASH_ALGS, false,
                    new int[] { HashAlgorithmTags.SHA256, HashAlgorithmTags.SHA1, HashAlgorithmTags.SHA384,
                            HashAlgorithmTags.SHA512, HashAlgorithmTags.SHA224 }),
            new PreferredAlgorithms(SignatureSubpacketTags.PREFERRED_COMP_ALGS, false,
                    new int[] { CompressionAlgorithmTags.ZLIB, CompressionAlgorithmTags.BZIP2,
                            CompressionAlgorithmTags.ZIP }),
            new Features(false, Features.FEATURE_MODIFICATION_DETECTION),
            createPreferencesSignatureSubpacket() };
    SignatureSubpacket[] unhashedData = new SignatureSubpacket[] {
            new IssuerKeyID(false, false, KEY_ID.toByteArray()) };
    byte[] fingerPrint = new BigInteger("522c", 16).toByteArray();

    return new SignaturePacket(signatureType, KEY_ID.longValue(), keyAlgorithm, hashAlgorithm, hashedData,
            unhashedData, fingerPrint, signatureArray);
}