Example usage for org.bouncycastle.cms CMSEnvelopedData getEncoded

List of usage examples for org.bouncycastle.cms CMSEnvelopedData getEncoded

Introduction

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

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Document

return the ASN.1 encoded representation of this object.

Usage

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

public byte[] encryptData(byte[] data, int keyPurpose) throws Exception {
    CryptoProviderTools.installBCProviderIfNotAvailable();
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
    CMSEnvelopedData ed;
    try {/*from  w  w w  .j  a va  2  s  .com*/
        edGen.addKeyTransRecipient(this.getCAToken().getPublicKey(keyPurpose), this.keyId);
        ed = edGen.generate(new CMSProcessableByteArray(data), CMSEnvelopedDataGenerator.AES256_CBC, "BC");
    } catch (Exception e) {
        log.error("-encryptKeys: ", e);
        throw new IOException(e.getMessage());
    }

    return ed.getEncoded();
}

From source file:org.ejbca.core.protocol.scep.ScepResponseMessage.java

License:Open Source License

@Override
public boolean create() throws CertificateEncodingException, CRLException {
    boolean ret = false;
    try {/*from ww  w  .j a v a  2s .co  m*/
        if (status.equals(ResponseStatus.SUCCESS)) {
            log.debug("Creating a STATUS_OK message.");
        } else {
            if (status.equals(ResponseStatus.FAILURE)) {
                log.debug("Creating a STATUS_FAILED message (or returning false).");
                if (failInfo.equals(FailInfo.WRONG_AUTHORITY)) {
                    return false;
                }
                if (failInfo.equals(FailInfo.INCORRECT_DATA)) {
                    return false;
                }
            } else {
                log.debug("Creating a STATUS_PENDING message.");
            }
        }

        CMSTypedData msg;
        // Create encrypted response if this is success and NOT a CRL response message
        if (status.equals(ResponseStatus.SUCCESS)) {

            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            // Add the issued certificate to the signed portion of the CMS (as signer, degenerate case)
            List<X509Certificate> certList = new ArrayList<X509Certificate>();
            if (cert != null) {
                log.debug("Adding certificates to response message");
                certList.add((X509Certificate) cert);
                // Add the CA cert, it's optional but Cisco VPN client complains if it isn't there
                if (includeCACert) {
                    if (caCert != null) {
                        // If we have an explicit CAcertificate
                        log.debug("Including explicitly set CA certificate in SCEP response.");
                        certList.add((X509Certificate) caCert);
                    } else {
                        // If we don't have an explicit caCert, we think that the signCert is the CA cert
                        // If we have an explicit caCert, the signCert is probably the RA certificate, and we don't include that one
                        log.debug("Including message signer certificate in SCEP response.");
                        certList.add((X509Certificate) signCertChain.iterator().next());
                    }
                }
            }
            // Create the signed CMS message to be contained inside the envelope
            // this message does not contain any message, and no signerInfo
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            gen.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(certList)));
            if (crl != null) {
                gen.addCRL(new JcaX509CRLHolder((X509CRL) crl));
            }

            CMSSignedData s = gen.generate(new CMSAbsentContent(), false);

            // Envelope the CMS message
            if (recipientKeyInfo != null) {
                try {
                    X509Certificate rec = (X509Certificate) CertTools.getCertfromByteArray(recipientKeyInfo);
                    log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec)
                            + "', serno: '" + CertTools.getSerialNumberAsString(rec));
                    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(rec)
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME));
                } catch (CertificateParsingException e) {
                    throw new IllegalArgumentException("Can not decode recipients self signed certificate!", e);
                }
            } else {
                edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            }
            try {
                JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                        SMIMECapability.dES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()),
                        jceCMSContentEncryptorBuilder.build());
                if (log.isDebugEnabled()) {
                    log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long");
                }
                msg = new CMSProcessableByteArray(ed.getEncoded());
            } catch (IOException e) {
                throw new IllegalStateException("Unexpected IOException caught", e);
            }
        } else {
            // Create an empty message here
            //msg = new CMSProcessableByteArray("PrimeKey".getBytes());
            msg = new CMSProcessableByteArray(new byte[0]);
        }

        // Create the outermost signed data
        CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();

        // add authenticated attributes...status, transactionId, sender- and recipientNonce and more...
        Hashtable<ASN1ObjectIdentifier, Attribute> attributes = new Hashtable<ASN1ObjectIdentifier, Attribute>();
        ASN1ObjectIdentifier oid;
        Attribute attr;
        DERSet value;

        // Message type (certrep)
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType);
        value = new DERSet(new DERPrintableString("3"));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        // TransactionId
        if (transactionId != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_transId);
            log.debug("Added transactionId: " + transactionId);
            value = new DERSet(new DERPrintableString(transactionId));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // status
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus);
        value = new DERSet(new DERPrintableString(status.getStringValue()));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        if (status.equals(ResponseStatus.FAILURE)) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo);
            log.debug("Added failInfo: " + failInfo.getValue());
            value = new DERSet(new DERPrintableString(failInfo.getValue()));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // senderNonce
        if (senderNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce);
            log.debug("Added senderNonce: " + senderNonce);
            value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // recipientNonce
        if (recipientNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce);
            log.debug("Added recipientNonce: " + recipientNonce);
            value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // Add our signer info and sign the message
        Certificate cacert = signCertChain.iterator().next();
        log.debug("Signing SCEP message with cert: " + CertTools.getSubjectDN(cacert));
        String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digestAlg,
                signKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(provider).build(signKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            builder.setSignedAttributeGenerator(
                    new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes)));
            gen1.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) cacert));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        // The un-encoded response message itself
        final CMSSignedData signedData = gen1.generate(msg, true);
        try {
            responseMessage = signedData.getEncoded();
        } catch (IOException e) {
            throw new IllegalStateException("Unexpected IOException caught.", e);
        }
        if (responseMessage != null) {
            ret = true;
        }
    } catch (CMSException e) {
        log.error("Error creating CMS message: ", e);
    }

    return ret;
}

From source file:org.ejbca.extra.db.ExtRAMsgHelper.java

License:Open Source License

/**
 * Method that should be used to encrypt data in a message.
 * /* w  w  w.  j  ava  2s.c  o m*/
 * Uses the algorithm specified in the init method.
 * 
 * @param encCert, the recepient to encrypt to.
 * @param data
 * @return encrypted byte[]
 * @throws IOException 
 */
public static byte[] encryptData(X509Certificate encCert, byte[] data) throws IOException {

    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    CMSEnvelopedData ed;
    try {
        edGen.addKeyTransRecipient(encCert);
        ed = edGen.generate(new CMSProcessableByteArray(data), encAlg, provider);
    } catch (Exception e) {
        log.error("Error Encryotin Keys:: ", e);
        throw new IOException(e.getMessage());
    }

    return ed.getEncoded();
}

From source file:org.ejbca.extra.ra.ScepRequestGenerator.java

License:Open Source License

private byte[] wrap(byte[] envBytes, String messageType) throws IOException, NoSuchAlgorithmException,
        NoSuchProviderException, CMSException, InvalidAlgorithmParameterException, CertStoreException {

    // /*from w w  w.  ja  va2s.  com*/
    // Create inner enveloped data
    //
    CMSEnvelopedData ed = envelope(new CMSProcessableByteArray(envBytes));
    log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long");
    CMSProcessable msg = new CMSProcessableByteArray(ed.getEncoded());
    //
    // Create the outer signed data
    //
    CMSSignedData s = sign(msg, messageType);

    byte[] ret = s.getEncoded();
    return ret;

}

From source file:org.jscep.message.PkiMessageEncoder.java

License:Open Source License

private CMSTypedData getContent(final PkiMessage<?> message) throws MessageEncodingException {
    CMSTypedData signable;/*from w  ww .  ja v  a  2s  .  com*/

    boolean hasMessageData = true;
    if (message instanceof CertRep) {
        CertRep response = (CertRep) message;
        if (response.getPkiStatus() != PkiStatus.SUCCESS) {
            hasMessageData = false;
        }
    }
    if (hasMessageData) {
        try {
            CMSEnvelopedData ed = encodeMessage(message);
            signable = new CMSProcessableByteArray(ed.getEncoded());
        } catch (IOException e) {
            throw new MessageEncodingException(e);
        }
    } else {
        signable = new CMSAbsentContent();
    }
    return signable;
}

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

License:Apache License

/**
 * Generate an EnvelopedData object by encrypting the content using the
 * partner's public certificate with the specified CipherSuite.
 * /*from w  w  w.  ja va  2s .co m*/
 * @param content
 *            the data to be encrypted
 * @param cipherSel
 *            ODETTE-FTP like cipher suite selection
 * @param cert
 *            partner's public certificate used to produce encrypted data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 * @throws IOException
 */
public static byte[] createEnvelopedData(byte[] content, CipherSuite cipherSel, X509Certificate cert)
        throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, IOException {

    installBouncyCastleProviderIfNecessary();

    byte[] encoded = null;

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

    gen.addKeyTransRecipient(cert);

    // create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray(content);

    String algorithm = asEncryptionAlgorithm(cipherSel);
    CMSEnvelopedData enveloped = gen.generate(data, algorithm, BC_PROVIDER);
    encoded = enveloped.getEncoded();

    return encoded;
}

From source file:org.silverpeas.core.security.encryption.cipher.CMSCipher.java

License:Open Source License

/**
 * Encrypts the specified data by using the specified cryptographic key.
 * <p>//from  w  w w.j  a v  a2  s .  co m
 * The String objects handled by the encryption is done according the UTF-8 charset.
 * @param data the data to encode.
 * @param keyFilePath the file in which is stored the public key to use in the encryption.
 * @return the encrypted data in bytes.
 */
@Override
public byte[] encrypt(String data, CipherKey keyFilePath) throws CryptoException {
    try {
        // Chargement de la chaine  crypter
        byte[] buffer = stringToByteArray(data);

        // 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
        if (!keyFilePath.isInFile()) {
            throw new FileNotFoundException("The PKS#12 file '" + keyFilePath + "' doesn't exist!");
        }
        PKS12KeyStoreWallet wallet = PKS12KeyStoreWallet.getInstance();
        PKS12KeyStore keyStore = wallet.getKeyStore(keyFilePath.getKeyFilePath());
        RecipientInfoGenerator generator = new JceKeyTransRecipientInfoGenerator(keyStore.getCertificate())
                .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);
        return envData.getEncoded();
    } catch (CryptoException e) {
        throw e;
    } catch (Exception e) {
        throw new CryptoException(CryptoException.ENCRYPTION_FAILURE, e);
    }
}

From source file:org.silverpeas.util.crypto.CMSCipher.java

License:Open Source License

/**
 * Encrypts the specified data by using the specified cryptographic key.
 * <p/>//from w  w w.j  a va 2 s .  c om
 * The String objects handled by the encryption is done according the UTF-8 charset.
 * @param data the data to encode.
 * @param keyFilePath the file in which is stored the public key to use in the encryption.
 * @return the encrypted data in bytes.
 */
@Override
public byte[] encrypt(String data, CipherKey keyFilePath) throws CryptoException {
    try {
        // Chargement de la chaine  crypter
        byte[] buffer = stringToByteArray(data);

        // 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
        if (!keyFilePath.isInFile()) {
            throw new FileNotFoundException("The PKS#12 file '" + keyFilePath + "' doesn't exist!");
        }
        PKS12KeyStoreWallet wallet = PKS12KeyStoreWallet.getInstance();
        PKS12KeyStore keyStore = wallet.getKeyStore(keyFilePath.getKeyFilePath());
        RecipientInfoGenerator generator = new JceKeyTransRecipientInfoGenerator(keyStore.getCertificate())
                .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);
        return envData.getEncoded();
    } catch (CryptoException e) {
        throw e;
    } catch (Exception e) {
        throw new CryptoException(CryptoException.ENCRYPTION_FAILURE, e);
    }
}

From source file:org.xipki.pki.scep.message.PkiMessage.java

License:Open Source License

public ContentInfo encode(final ContentSigner signer, final X509Certificate signerCert,
        final X509Certificate[] cmsCertSet, final X509Certificate recipientCert,
        final ASN1ObjectIdentifier encAlgId) throws MessageEncodingException {
    ParamUtil.requireNonNull("signer", signer);
    ParamUtil.requireNonNull("signerCert", signerCert);
    ParamUtil.requireNonNull("recipientCert", recipientCert);
    ParamUtil.requireNonNull("encAlgId", encAlgId);

    CMSTypedData content;//from  ww w . ja v a2s  . com
    if (messageData == null) {
        content = new CMSAbsentContent();
    } else {
        CMSEnvelopedData envelopedData = encrypt(recipientCert, encAlgId);
        byte[] encoded;
        try {
            encoded = envelopedData.getEncoded();
        } catch (IOException ex) {
            throw new MessageEncodingException(ex);
        }
        content = new CMSProcessableByteArray(CMSObjectIdentifiers.envelopedData, encoded);
    }

    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        // signerInfo
        JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder(
                new BcDigestCalculatorProvider());

        signerInfoBuilder
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(getSignedAttributes()));

        AttributeTable attrTable = getUnsignedAttributes();
        if (attrTable != null) {
            signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(attrTable));
        }

        // certificateSet
        ScepUtil.addCmsCertSet(generator, cmsCertSet);

        SignerInfoGenerator signerInfo;
        try {
            signerInfo = signerInfoBuilder.build(signer, signerCert);
        } catch (Exception ex) {
            throw new MessageEncodingException(ex);
        }

        generator.addSignerInfoGenerator(signerInfo);

        CMSSignedData signedData = generator.generate(content, true);
        return signedData.toASN1Structure();
    } catch (CMSException ex) {
        throw new MessageEncodingException(ex);
    } catch (Exception ex) {
        throw new MessageEncodingException(ex);
    }
}