Example usage for org.bouncycastle.cms CMSEnvelopedDataGenerator CMSEnvelopedDataGenerator

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

Introduction

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

Prototype

public CMSEnvelopedDataGenerator() 

Source Link

Document

base constructor

Usage

From source file:be.e_contract.mycarenet.etee.Sealer.java

License:Open Source License

private byte[] encrypt(byte[] data) throws CertificateEncodingException, CMSException, IOException {
    CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
    for (X509Certificate destinationCertificate : this.destinationCertificates) {
        cmsEnvelopedDataGenerator/*from  w ww.  java  2  s  .  c  o m*/
                .addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(destinationCertificate)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME));
    }
    CMSTypedData cmsTypedData = new CMSProcessableByteArray(data);
    CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(cmsTypedData,
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).build());
    return cmsEnvelopedData.getEncoded();
}

From source file:chapter9.KEKEnvelopedDataExample.java

/**
 *
 * @param args/*from   w w  w  . ja  v  a2  s.  co  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance(CryptoDefs.Algorithm.DESede.getName(),
            CryptoDefs.Provider.BC.getName());
    SecretKey key = keyGen.generateKey();

    //1.- Set up the generator
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    byte[] kekID = new byte[] { 1, 2, 3, 4, 5 };

    edGen.addKEKRecipient(key, kekID);

    //2.- Create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes());
    CMSEnvelopedData enveloped = edGen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC,
            CryptoDefs.Provider.BC.getName());

    //3.- Re-create
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    //4.- Look for our recipient identifier
    RecipientId recId = new KEKRecipientId(kekID);

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        //5.- Decrypt the data
        byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

        //6.- Compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData))
            System.out.println("\t data recovery succeeded!!");
        else
            System.out.println("\t data recovery failed!!");
    } else
        System.out.println("\t Could not find a matching recipient!!");
}

From source file:chapter9.KeyTransEnvelopedDataExample.java

/**
 *
 * @param args/*from w w w  . j  ava2s .  c o  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);

    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);

    X509Certificate cert = (X509Certificate) chain[0];

    //1.- Set up the generator
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

    gen.addKeyTransRecipient(cert);

    //2.- Create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes());
    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC,
            CryptoDefs.Provider.BC.getName());

    //3.- Re-create
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    //4.- Look for our recipient identifier
    RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()),
            cert.getSerialNumber());

    recId.setSerialNumber(cert.getSerialNumber());
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        //5.- Decrypt the data
        byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

        //6.- Compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData))
            System.out.println("\t data recovery succeeded!!");
        else
            System.out.println("\t data recovery failed!!");
    } else
        System.out.println("\t Could not find a matching recipient!!");
}

From source file:chapter9.KeyTransEnvelopedDataExample2.java

/**
 *
 * @param args//from w  w w. j  av a 2 s .c o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);

    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);

    X509Certificate cert = (X509Certificate) chain[0];

    //1.- Set up the generator
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

    gen.addKeyTransRecipient(cert);

    //2.- Create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes());
    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC,
            CryptoDefs.Provider.BC.getName());

    //3.- Re-create
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    //4.- Look for our recipient identifier
    //    Set up to iterate through the recipients
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    CertStore certStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Collections.singleton(cert)), CryptoDefs.Provider.BC.getName());

    RecipientInformation recipient = null;
    for (Object o : recipients.getRecipients()) {
        recipient = (RecipientInformation) o;

        if (recipient instanceof KeyTransRecipientInformation) {
            //5.- Match the recipient ID
            Collection<?> matches = certStore.getCertificates(recipient.getRID());

            if (matches.isEmpty() == false) {
                //6.- Decrypt the data
                byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

                //7.- Compare recovered data to the original data
                if (Arrays.equals((byte[]) data.getContent(), recData) == true) {
                    System.out.println("\t data recovery succeeded!!");
                    break;
                } else {
                    System.out.println("\t data recovery failed!!");
                    break;
                }
            }
        }
    }

    if (recipient == null) {
        System.out.println("\t Could not find a matching recipient!!");
    }
}

From source file:com.maiereni.host.web.util.impl.BouncyCastleEncryptorImpl.java

License:Apache License

public byte[] encryptData(@Nonnull final byte[] data) throws Exception {
    CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
    JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(certificate);
    cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
    CMSTypedData msg = new CMSProcessableByteArray(data);
    OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC")
            .build();/*from  w ww.j av a2  s .com*/
    CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
    return cmsEnvelopedData.getEncoded();
}

From source file:com.pieframework.runtime.utils.CertificateUtils.java

License:Apache License

public static String encryptPassword(String rdpPassword, X509Certificate certificate) {
    Security.addProvider(new BouncyCastleProvider());
    String encryptedPassword = "";
    //get PrivateKey And certificate from pfx file
    try {//from  www. j  a v  a2 s .c  o  m

        certificate.checkValidity();

        CMSEnvelopedDataGenerator envDataGen = new CMSEnvelopedDataGenerator();
        envDataGen.addKeyTransRecipient(certificate);
        CMSProcessable envData = new CMSProcessableByteArray(rdpPassword.getBytes());
        CMSEnvelopedData enveloped = envDataGen.generate(envData, CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC");
        byte[] data = enveloped.getEncoded();
        encryptedPassword = new String(Base64.encodeBase64(data));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return encryptedPassword;
}

From source file:com.silverpeas.util.cryptage.SilverCryptFactoryAsymetric.java

License:Open Source License

public byte[] goCrypting(String stringUnCrypted, String fileName) throws CryptageException {
    try {//from www.j a va2s. co m
        // Chargement de la chaine  crypter
        byte[] buffer = stringToByteArray(stringUnCrypted);

        // Chiffrement du document
        CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
        // La variable cert correspond au certificat du destinataire
        // La cl publique de ce certificat servira  chiffrer la cl
        // symtrique
        RecipientInfoGenerator generator = new JceKeyTransRecipientInfoGenerator(getKeys(fileName).getCert())
                .setProvider("BC");
        gen.addRecipientInfoGenerator(generator);

        // Choix de l'algorithme  cl symtrique pour chiffrer le document.
        // AES est un standard. Vous pouvez donc l'utiliser sans crainte.
        // Il faut savoir qu'en france la taille maximum autorise est de 128
        // bits pour les cls symtriques (ou cls secrtes)    
        OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC")
                .build();
        CMSEnvelopedData envData = gen.generate(new CMSProcessableByteArray(buffer), encryptor);
        byte[] pkcs7envelopedData = envData.getEncoded();
        return pkcs7envelopedData;
    } catch (CryptageException e) {
        throw e;
    } catch (Exception e) {

        throw new CryptageException("SilverCryptFactory.goCrypting", SilverpeasException.ERROR,
                "util.CRYPT_FAILED", e);
    }
}

From source file:eu.inn.biometric.signature.crypto.BCCryptoProvider.java

License:Open Source License

@Override
public byte[] encrypt(byte[] toEncrypt, List<X509Certificate> certs, Integer maxKeyLength) throws Exception {
    int keySize = Cipher.getMaxAllowedKeyLength("AES");
    if (maxKeyLength != null)
        if (keySize > maxKeyLength)
            keySize = maxKeyLength;/*from ww  w  . j  a v a2s.  co m*/
    String algIdentifier = CMSAlgorithm.AES128_CBC.getId();
    if (keySize >= 256)
        algIdentifier = CMSAlgorithm.AES256_CBC.getId();
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
    for (X509Certificate cert : certs)
        gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cert));
    CMSTypedData data = new CMSProcessableByteArray(toEncrypt);
    CMSEnvelopedData enveloped = gen.generate(data,
            new JceCMSContentEncryptorBuilder(new ASN1ObjectIdentifier(algIdentifier)).build());
    return enveloped.getEncoded();
}

From source file:io.aos.crypto.spl09.KEKEnvelopedDataExample.java

License:Apache License

public static void main(String... args) throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("DESEDE", "BC");
    SecretKey key = keyGen.generateKey();

    // set up the generator
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    byte[] kekID = new byte[] { 1, 2, 3, 4, 5 };

    edGen.addKEKRecipient(key, kekID);//from   ww w .j  ava2 s.c om

    // create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSEnvelopedData enveloped = edGen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, "BC");
    // recreate
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    // look for our recipient
    RecipientId recId = new KEKRecipientId(kekID);

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        // decrypt the data
        byte[] recData = recipient.getContent(key, "BC");

        // compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData)) {
            System.out.println("data recovery succeeded");
        } else {
            System.out.println("data recovery failed");
        }
    } else {
        System.out.println("could not find a matching recipient");
    }
}

From source file:io.aos.crypto.spl09.KeyTransEnvelopedDataExample.java

License:Apache License

public static void main(String... args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
    X509Certificate cert = (X509Certificate) chain[0];

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

    gen.addKeyTransRecipient(cert);//from   w ww  .  j av a 2 s  .  com

    // create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, "BC");

    // recreate
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    // look for our recipient identifier
    RecipientId recId = new KEKRecipientId(null);

    recId.setSerialNumber(cert.getSerialNumber());
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        // decrypt the data
        byte[] recData = recipient.getContent(key, "BC");

        // compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData)) {
            System.out.println("data recovery succeeded");
        } else {
            System.out.println("data recovery failed");
        }
    } else {
        System.out.println("could not find a matching recipient");
    }
}