Example usage for org.bouncycastle.cms CMSEnvelopedDataStreamGenerator CMSEnvelopedDataStreamGenerator

List of usage examples for org.bouncycastle.cms CMSEnvelopedDataStreamGenerator CMSEnvelopedDataStreamGenerator

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSEnvelopedDataStreamGenerator CMSEnvelopedDataStreamGenerator.

Prototype

public CMSEnvelopedDataStreamGenerator() 

Source Link

Document

base constructor

Usage

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**
 * Encrypts a byte array and returns it//from   w ww .jav  a  2  s  .  c  om
 */
private void encryptDataToMessage(AS2Message message, String receiverCryptAlias, int encryptionType,
        Partner receiver) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    X509Certificate certificate = this.encryptionCertManager.getX509Certificate(receiverCryptAlias);
    CMSEnvelopedDataStreamGenerator dataGenerator = new CMSEnvelopedDataStreamGenerator();
    dataGenerator
            .addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(certificate).setProvider("BC"));
    DeferredFileOutputStream encryptedOutput = null;
    OutputStream out = null;
    try {
        //if the data is less then 3MB perform the operaion in memory else stream to disk
        encryptedOutput = new DeferredFileOutputStream(3 * 1024 * 1024, "as2encryptdata_", ".mem", null);
        if (encryptionType == AS2Message.ENCRYPTION_3DES) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_DES) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_WRAP, 56).setProvider("BC")
                            .build());
        } else if (encryptionType == AS2Message.ENCRYPTION_RC2_40) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC, 40).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_RC2_64) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC, 64).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_RC2_128) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC, 128).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_RC2_196) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC, 196).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_AES_128) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_AES_192) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES192_CBC).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_AES_256) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_RC4_40) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(
                            cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_RC4)), 40)
                                    .setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_RC4_56) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(
                            cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_RC4)), 56)
                                    .setProvider("BC").build());
        } else if (encryptionType == AS2Message.ENCRYPTION_RC4_128) {
            out = dataGenerator.open(encryptedOutput,
                    new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(
                            cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_RC4)), 128)
                                    .setProvider("BC").build());
        }
        if (out == null) {
            throw new Exception("Internal failure: unsupported encryption type " + encryptionType);
        }
        InputStream in = null;
        try {
            in = message.getDecryptedRawDataInputStream();
            this.copyStreams(in, out);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    } finally {
        if (out != null) {
            out.close();
        }
        if (encryptedOutput != null) {
            encryptedOutput.close();
        }
    }
    //size of the data was < than the threshold
    if (encryptedOutput.isInMemory()) {
        message.setRawData(encryptedOutput.getData());
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        encryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = encryptedOutput.getFile().delete();
        message.setRawData(memOut.toByteArray());
    }
    if (this.logger != null) {
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.logger.log(Level.INFO, this.rb.getResourceString("message.encrypted",
                new Object[] { info.getMessageId(), cryptAlias,
                        this.rbMessage.getResourceString("encryption." + receiver.getEncryptionType()) }),
                info);
    }
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Encrypts data to a stream/*from  ww w  . ja  va 2 s . c o  m*/
 */
public void encryptCMS(InputStream rawStream, OutputStream encryptedStream, final String ALGORITHM_NAME,
        Certificate cert, boolean inMemory) throws Exception {
    X509Certificate x509Cert = this.castCertificate(cert);
    CMSEnvelopedDataStreamGenerator dataStreamGenerator = new CMSEnvelopedDataStreamGenerator();
    dataStreamGenerator
            .addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(x509Cert).setProvider("BC"));
    String oid = this.convertAlgorithmNameToOID(ALGORITHM_NAME);
    if (inMemory) {
        ByteArrayOutputStream memBuffer = new ByteArrayOutputStream();
        OutputStream cmsEnveloped = null;
        try {
            ASN1ObjectIdentifier objectIdentifier = new ASN1ObjectIdentifier(oid);
            OutputEncryptor outputEncryptor = new JceCMSContentEncryptorBuilder(objectIdentifier).build();
            cmsEnveloped = dataStreamGenerator.open(memBuffer, outputEncryptor);
            this.copyStreams(rawStream, cmsEnveloped);
        } finally {
            if (cmsEnveloped != null) {
                cmsEnveloped.flush();
                cmsEnveloped.close();
            }
        }
        encryptedStream.write(memBuffer.toByteArray());
    } else {
        File tempFile = File.createTempFile("encrypt", ".temp");
        FileOutputStream fileBuffer = null;
        OutputStream cmsEnveloped = null;
        try {
            fileBuffer = new FileOutputStream(tempFile);
            ASN1ObjectIdentifier objectIdentifier = new ASN1ObjectIdentifier(oid);
            OutputEncryptor outputEncryptor = new JceCMSContentEncryptorBuilder(objectIdentifier).build();
            cmsEnveloped = dataStreamGenerator.open(fileBuffer, outputEncryptor);
            this.copyStreams(rawStream, cmsEnveloped);
        } finally {
            if (cmsEnveloped != null) {
                cmsEnveloped.flush();
                cmsEnveloped.close();
            }
            if (fileBuffer != null) {
                fileBuffer.flush();
                fileBuffer.close();
            }
        }
        FileInputStream fileIn = null;
        try {
            fileIn = new FileInputStream(tempFile);
            this.copyStreams(fileIn, encryptedStream);
        } finally {
            if (fileIn != null) {
                fileIn.close();
            }
        }
        boolean deleted = tempFile.delete();
    }
}

From source file:org.dihedron.crypto.operations.encrypt.EncryptZipFile.java

License:Open Source License

public void encrypt(InputStream plaintext, OutputStream encrypted, String provider, String url, String name,
        String filter) {/*from w w w  .  ja  v  a 2  s . c  om*/

    logger.info("starting encryption");

    X509Certificate certificate = null;

    boolean okCertificato = true;
    try {
        logger.info("starting encryption process...");
        Properties configuration = new Properties();
        configuration.setProperty("provider", provider);
        configuration.setProperty("ldap.url", url);
        CertificateLoader loader = CertificateLoaderFactory.makeCertificateLoader(configuration);

        Properties parameters = new Properties();
        parameters.put("name", name);
        parameters.put("filter", filter);
        certificate = (X509Certificate) loader.loadCertificate(parameters);
        logger.info("certificate algorithm: " + certificate.getPublicKey().getAlgorithm());

        String[] issuerInfo = certificate.getIssuerDN().getName().split("(=|, )", -1);
        String[] subjectInfo = certificate.getSubjectDN().getName().split("(=|, )", -1);

        logger.debug("common name (CN) : " + subjectInfo[3]);
        logger.debug("address          : " + subjectInfo[1] + "\n");

        for (int i = 0; i < issuerInfo.length; i += 2) {
            if (issuerInfo[i].equals("C"))
                logger.debug("CountryName : " + issuerInfo[i + 1]);
            if (issuerInfo[i].equals("O"))
                logger.debug("OrganizationName : " + issuerInfo[i + 1]);
            if (issuerInfo[i].equals("CN"))
                logger.debug("CommonName : " + issuerInfo[i + 1]);
        }
        logger.info("valid from: " + certificate.getNotBefore() + " until: " + certificate.getNotAfter());
    } catch (Exception e) {
        logger.error("couldn't instantiate X.509 certificate. ", e);
        okCertificato = false;
    }

    if (!okCertificato) {
        logger.info("no certificate, ending process");
        return;
    }
    try {
        logger.info("encrypting data");

        CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator();
        edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(certificate).setProvider("BC"));
        OutputStream out = edGen.open(encrypted,
                new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build());
        Streams.copy(plaintext, out);
        out.close();

    } catch (CMSException ex) {
        logger.error("CMSException: ", ex.getUnderlyingException());
    } catch (IOException e) {
        logger.error("couldn't generate enveloped signature");
    } catch (CertificateEncodingException e) {
        logger.error("certificate encoding error", e);
        //      } catch (OperatorCreationException e) {
        //         logger.error("operator creation error", e);
    }

    logger.info("encryption ending");
}

From source file:org.dihedron.crypto.operations.encrypt.pkcs7.PKCS7EncryptingStream.java

License:Open Source License

/**
 * Constructor.//from  www  .  ja  va2s . c o m
 * 
 * @param output
 *   the output stream, to which encrypted data will be written.
 * @param certificate
 *   the certificate to be used for encryption.
 */
public PKCS7EncryptingStream(OutputStream output, Certificate certificate) {
    super(output, certificate);

    logger.info("encrypting data through certificate supporting algorithm: '{}'",
            certificate.getPublicKey().getAlgorithm());

    if (certificate instanceof X509Certificate) {
        String[] issuerInfo = ((X509Certificate) certificate).getIssuerDN().getName().split("(=|, )", -1);
        String[] subjectInfo = ((X509Certificate) certificate).getSubjectDN().getName().split("(=|, )", -1);

        logger.debug("common name (CN) : '{}'", subjectInfo[3]);
        logger.debug("address          : '{}'", subjectInfo[1]);

        for (int i = 0; i < issuerInfo.length; i += 2) {
            if (issuerInfo[i].equals("C")) {
                logger.debug("CountryName : '{}'", issuerInfo[i + 1]);
            }
            if (issuerInfo[i].equals("O")) {
                logger.debug("OrganizationName : '{}'", issuerInfo[i + 1]);
            }
            if (issuerInfo[i].equals("CN")) {
                logger.debug("CommonName : '{}'", issuerInfo[i + 1]);
            }
        }
        logger.debug("certificate is valid from {} until {}", ((X509Certificate) certificate).getNotBefore(),
                ((X509Certificate) certificate).getNotAfter());
    }

    try {
        logger.info("preparing encrypting stream...");
        CMSEnvelopedDataStreamGenerator generator = new CMSEnvelopedDataStreamGenerator();
        generator.addRecipientInfoGenerator(
                new JceKeyTransRecipientInfoGenerator((X509Certificate) certificate).setProvider("BC"));
        stream = generator.open(output,
                new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build());
        logger.info("encrypting stream ready!");
    } catch (CMSException ex) {
        logger.error("CMSException: ", ex.getUnderlyingException());
    } catch (IOException e) {
        logger.error("couldn't generate enveloped signature");
    } catch (CertificateEncodingException e) {
        logger.error("certificate encoding error", e);
    }
}

From source file:org.ejbca.util.CMS.java

License:Open Source License

/**
 * @param is data to be encrypted/*from   w  w  w. j a  v  a  2s.  c o m*/
 * @param os encrypted data
 * @param cert certificate with the public key to be used for the encryption
 * @param symmAlgOid the symmetric encryption algorithm to use, for example CMSEnvelopedGenerator.AES128_CBC
 * @throws Exception
 */
public static void encrypt(final InputStream is, final OutputStream os, final X509Certificate cert,
        final String symmAlgOid) throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    final CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator();
    edGen.addRecipientInfoGenerator(
            new JceKeyTransRecipientInfoGenerator("hej".getBytes(), cert.getPublicKey()));
    BcCMSContentEncryptorBuilder bcCMSContentEncryptorBuilder = new BcCMSContentEncryptorBuilder(
            new ASN1ObjectIdentifier(symmAlgOid));
    final OutputStream out = edGen.open(bos, bcCMSContentEncryptorBuilder.build());
    fromInToOut(bis, out);
    bos.close();
    os.close();
}

From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java

License:Apache License

public static OutputStream openEnvelopedDataStreamGenerator(OutputStream outStream, CipherSuite cipherSel,
        X509Certificate cert)/*from   w w w. ja v  a  2s  .  c  o  m*/
        throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, IOException {

    installBouncyCastleProviderIfNecessary();

    // set up the generator
    CMSEnvelopedDataStreamGenerator gen = new CMSEnvelopedDataStreamGenerator();

    gen.addKeyTransRecipient(cert);

    String algorithm = asEncryptionAlgorithm(cipherSel);

    // create the enveloped-data stream
    OutputStream enveloped = gen.open(outStream, algorithm, BC_PROVIDER);

    return enveloped;
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

public static byte[] encryptToCMS(byte[] dataToEncrypt, X509Certificate receptorCert) throws Exception {
    CMSEnvelopedDataStreamGenerator dataStreamGen = new CMSEnvelopedDataStreamGenerator();
    dataStreamGen.addRecipientInfoGenerator(
            new JceKeyTransRecipientInfoGenerator(receptorCert).setProvider(ContextVS.PROVIDER));
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    OutputStream out = dataStreamGen.open(bOut, new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC)
            .setProvider(ContextVS.PROVIDER).build());
    out.write(dataToEncrypt);/*  www .j  ava 2 s.  co  m*/
    out.close();
    return Base64.getEncoder().encode(bOut.toByteArray());
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

public static byte[] encryptToCMS(byte[] dataToEncrypt, PublicKey receptorPublicKey) throws Exception {
    CMSEnvelopedDataStreamGenerator dataStreamGen = new CMSEnvelopedDataStreamGenerator();
    dataStreamGen//from  w  ww .j a va2  s .  c  o  m
            .addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator("".getBytes(), receptorPublicKey)
                    .setProvider(ContextVS.PROVIDER));
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    OutputStream out = dataStreamGen.open(bOut, new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC)
            .setProvider(ContextVS.PROVIDER).build());
    out.write(dataToEncrypt);
    out.close();
    return Base64.getEncoder().encode(bOut.toByteArray());
}