Example usage for org.bouncycastle.openpgp PGPEncryptedDataGenerator open

List of usage examples for org.bouncycastle.openpgp PGPEncryptedDataGenerator open

Introduction

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

Prototype

public OutputStream open(OutputStream out, byte[] buffer) throws IOException, PGPException 

Source Link

Document

Create an OutputStream which will encrypt the data as it is written to it.

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 w  ww  .j  av  a2s  .  c o m
        // =
        // 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:com.arcusx.simplepgp.PgpDataEncryptor.java

public void encryptAndSign(InputStream dataIn, InputStream recipientPublicKeyFileIn, String dataFileName,
        InputStream senderPrivateKeyFileIn, OutputStream dataOut, boolean isArmoredOutput)
        throws IOException, PGPException {
    PGPCompressedDataGenerator comData = null;
    try {// w w w. j  a  v a 2 s  .  co  m
        OutputStream out = dataOut;
        PGPPublicKey recipientPublicKey = PgpKeyUtils.readPublicKey(recipientPublicKeyFileIn);

        if (isArmoredOutput) {
            out = new ArmoredOutputStream(out);
        }

        BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
        dataEncryptor.setWithIntegrityPacket(true);
        dataEncryptor.setSecureRandom(new SecureRandom());

        PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
        encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(recipientPublicKey));

        OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);

        // Initialize compressed data generator
        PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(
                PGPCompressedData.ZIP);
        OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BUFFER_SIZE]);

        // Initialize signature generator
        final PGPSecretKey senderSecretKey = PgpKeyUtils.findSecretKey(senderPrivateKeyFileIn);
        PGPPrivateKey privateKey = PgpKeyUtils.getPrivateKeyFrom(senderSecretKey);

        PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(
                senderSecretKey.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1);

        PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder);
        signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);

        PGPSignatureSubpacketGenerator signatureSubpacketGenerator = new PGPSignatureSubpacketGenerator();
        signatureSubpacketGenerator.setSignerUserID(false, PgpKeyUtils.getUserIdFrom(senderSecretKey));
        signatureGenerator.setHashedSubpackets(signatureSubpacketGenerator.generate());
        signatureGenerator.generateOnePassVersion(false).encode(compressedOut);

        // Initialize literal data generator
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, dataFileName,
                new Date(), new byte[BUFFER_SIZE]);

        byte[] buf = new byte[BUFFER_SIZE];
        int len;
        while ((len = dataIn.read(buf)) > 0) {
            literalOut.write(buf, 0, len);
            signatureGenerator.update(buf, 0, len);
        }
        dataIn.close();
        literalDataGenerator.close();

        // generate the signature, compress, encrypt and write to the "out" stream
        signatureGenerator.generate().encode(compressedOut);
        compressedDataGenerator.close();
        encryptedDataGenerator.close();
        if (isArmoredOutput) {
            out.close();
        }
    } finally {
        if (comData != null) {
            comData.close();
        }
        IOUtils.closeQuietly(dataOut);
    }
}

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();

    ///*ww w  .j  ava 2s  .  com*/
    // 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.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Encrypt and sign the specified input file.  If you pass in a seed, you
 * will get the same encrypted output for the same file + same seed + same signor.
 * //w ww . j  av a2  s  . c o m
 * DANGER!  If you use the same seed for multiple different messages, you are
 * making your key stream vulnerable to hacking, and your encryption is near
 * meaningless!  Make sure to use different seeds for different contents!
 *  
 * @param seed 
 */
public void encryptAndSignFile(String outputFilename, File inFile, InputStream publicRing,
        InputStream secretRing, String recipient, String signor, char[] passwd, boolean armor,
        boolean withIntegrityCheck, boolean oldFormat, byte[] seed) throws PGPException {
    try {
        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing);

        // Find the recipient's key
        PGPPublicKey encKey = readPublicKey(pubRing, recipient, true);
        if (encKey.isRevoked()) {
            String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
            throw new PGPException("Encryption key (0x" + keyId + ") has been revoked");
        }

        // Find the signing key
        PGPPublicKey publicKey;
        PGPSecretKey secretKey;
        if (signor != null) {
            publicKey = readPublicKey(pubRing, signor, false);
            secretKey = findSecretKey(secRing, publicKey.getKeyID(), true);
        } else {
            // Just look for the first signing key on the secret keyring (if any)
            secretKey = findSigningKey(secRing);
            publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false);
        }
        if (publicKey.isRevoked()) {
            String keyId = Long.toHexString(publicKey.getKeyID()).substring(8);
            throw new PGPException("Signing key (0x" + keyId + ") has been revoked");
        }

        PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC");

        // Sign the data into an in-memory stream
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        if (oldFormat) {
            signDataV3(inFile, bOut, publicKey, privateKey);
        } else {
            signData(inFile, bOut, publicKey, privateKey);
        }

        SecureRandom secRand = makeSecureRandom(seed);

        PGPEncryptedDataGenerator cPk = oldFormat
                ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC")
                : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC");

        cPk.addMethod(encKey);

        byte[] bytes = bOut.toByteArray();

        OutputStream out = new FileOutputStream(outputFilename);
        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;
        OutputStream cOut = cPk.open(aOut, bytes.length);

        cOut.write(bytes);

        cPk.close();

        if (armor) {
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in encryption", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Encrypt the specified input file/*ww w. j  a v  a 2s  . c  om*/
 * @param seed 
 */
public void encryptFile(OutputStream out, InputStream in, String inName, long inLength, Date inDate,
        PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck, boolean oldFormat, char[] passphrase,
        byte[] seed) throws PGPException {
    try {
        if (encKey.isRevoked()) {
            String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
            throw new PGPException("Encryption key (0x" + keyId + ") has been revoked");
        }

        // Compress the data into an in-memory stream
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        compressData(in, bOut, inName, inLength, inDate, oldFormat, Format.UNCOMPRESSED);

        // Now encrypt the result
        SecureRandom secRand = makeSecureRandom(seed);

        // Now encrypt the result
        PGPEncryptedDataGenerator cPk = oldFormat
                ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC")
                : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC");

        cPk.addMethod(encKey);

        byte[] bytes = bOut.toByteArray();

        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;
        OutputStream cOut = cPk.open(aOut, bytes.length);

        cOut.write(bytes);

        cPk.close();

        if (armor) {
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in encryption", e);
    }
}

From source file:com.geoxp.oss.CryptoHelper.java

License:Apache License

public static byte[] encryptPGP(byte[] data, PGPPublicKey key, boolean armored, String name,
        int compressionAlgorithm, int encAlgorithm) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    OutputStream out = armored ? new ArmoredOutputStream(baos) : baos;

    BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(encAlgorithm);
    dataEncryptor.setWithIntegrityPacket(true);
    dataEncryptor.setSecureRandom(CryptoHelper.getSecureRandom());

    PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
    encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key));

    try {//from w  w w .  j  a v a2 s.  com
        OutputStream encout = encryptedDataGenerator.open(out, 1024);

        PGPCompressedDataGenerator pgpcdg = new PGPCompressedDataGenerator(compressionAlgorithm);
        OutputStream compout = pgpcdg.open(encout);

        PGPLiteralDataGenerator pgpldg = new PGPLiteralDataGenerator(false);
        OutputStream ldout = pgpldg.open(compout, PGPLiteralData.BINARY, name, data.length, PGPLiteralData.NOW);

        ldout.write(data);
        ldout.close();
        compout.close();
        encout.close();
        out.close();
        baos.close();

        return baos.toByteArray();
    } catch (PGPException pgpe) {
        throw new IOException(pgpe);
    }
}

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

License:Apache License

/**
 * Simple PGP encryptor between byte[].//from  www  .jav  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: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;//from   ww w .java2  s .  co 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:com.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * PGP Encrypt a stream./*from w  ww  .  ja va 2 s. co m*/
 *
 * @param plainTextStream The stream that contains the plain-text data.
 * @param publicKey       The public key to use for encryption.
 * @param armoured        {@code true}: ASCII armor the encrypted data.
 *
 * @return The encrypted data stream.
 *
 * @throws NoSuchProviderException
 * @throws IOException
 * @throws PGPException
 */
public static InputStream encrypt(final InputStream plainTextStream, final PGPPublicKey publicKey,
        final boolean armoured) throws IOException, NoSuchProviderException, PGPException {

    /* Compress and extract literal data packets that can be encrypted. */
    PGPEncryptedDataGenerator encryptedDataGenerator = null;
    try (ByteArrayOutputStream decryptedStream = new ByteArrayOutputStream();
            ByteArrayOutputStream encryptedByteStream = new ByteArrayOutputStream()) {
        PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
        PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB);
        OutputStream literalStream = literalDataGenerator.open(compressor.open(decryptedStream),
                PGPLiteralData.BINARY, "", new Date(), new byte[4096]);
        ByteStreams.copy(plainTextStream, literalStream);
        compressor.close();

        /* Encrypt compressed data. */
        encryptedDataGenerator = new PGPEncryptedDataGenerator(SymmetricKeyAlgorithmTags.CAST5,
                new SecureRandom(), BouncyCastleProvider.PROVIDER_NAME);
        encryptedDataGenerator.addMethod(publicKey);

        /* Create the encrypted output stream, armour if necessary. */
        OutputStream encryptedStream = encryptedByteStream;
        if (armoured)
            encryptedStream = new ArmoredOutputStream(encryptedStream);

        /* Create and write out the encrypted file. */
        OutputStream encryptionStream = encryptedDataGenerator.open(encryptedStream, new byte[4096]);
        ByteStreams.copy(new ByteArrayInputStream(decryptedStream.toByteArray()), encryptionStream);

        return new ByteArrayInputStream(encryptedByteStream.toByteArray());
    } finally {
        if (encryptedDataGenerator != null)
            encryptedDataGenerator.close();
    }
}

From source file:de.jtheuer.diki.lib.pgp.PGPHandler.java

License:Open Source License

/**
 * Encryptes the given input and writes into the output. If the key doesn't exist nothing will happen.
 * @param input input content//from w ww  . j a v  a 2s.com
 * @param output output as {@link ArmoredOutputStream} (BASE64)
 * @param keyID the keyID of the PublicKey that should be used
 * @throws PGPException
 * @throws IOException
 * @throws NoSuchProviderException
 */
public void encrypt(InputStream input, OutputStream output, long keyID) throws PGPException, IOException {
    PGPPublicKey encryptkey = null;

    /* take the own key if that is the ID... */
    if (keyID == publickey.getKeyID()) {
        encryptkey = publickey;
    } else {
        encryptkey = keyring.getPublicKey(keyID);
    }

    if (encryptkey != null) {

        PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
                PGPEncryptedDataGenerator.TRIPLE_DES, new SecureRandom(), "BC");

        try {
            encryptor.addMethod(encryptkey);
        } catch (NoSuchProviderException e) {
            LOGGER.log(Level.SEVERE,
                    "provider hasn't been loaded successfully! There is a problem with the Bouncycastle system!",
                    e);
        }
        ArmoredOutputStream armoredOut = new ArmoredOutputStream(output);
        OutputStream encryptedOut = encryptor.open(armoredOut, new byte[256]);
        PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
        OutputStream compressedOut = compressor.open(encryptedOut);

        PGPLiteralDataGenerator literalor = new PGPLiteralDataGenerator();
        OutputStream literalOut = literalor.open(compressedOut, PGPLiteralDataGenerator.TEXT, "internal",
                new Date(), new byte[256]);

        /* copy from input to output */
        IOUtils.copy(input, literalOut);

        literalor.close();
        compressor.close();
        encryptor.close();
        armoredOut.close();
    }
}