Example usage for org.bouncycastle.cms CMSSignedData getEncoded

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

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedData 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.protocol.scep.ScepResponseMessage.java

License:Open Source License

@Override
public boolean create() throws CertificateEncodingException, CRLException {
    boolean ret = false;
    try {/*from  ww  w  .  ja  va2 s  .  c o  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 signes the given data using the algorithm specified in the init method.
 * //  w  w w .j a  v  a  2 s  . co m
 * @param signKey, the key used to sign the data
 * @param signCert the certificate
 * @param data
 * @return the signed data or null if signature failed
 */
public static byte[] signData(PrivateKey signKey, X509Certificate signCert, byte[] data) {
    byte[] retdata = null;
    try {
        ArrayList certList = new ArrayList();
        certList.add(signCert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                provider);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addCertificatesAndCRLs(certs);
        gen.addSigner(signKey, signCert, signAlg);
        CMSSignedData signedData = gen.generate(new CMSProcessableByteArray(data), true, provider);
        retdata = signedData.getEncoded();
    } catch (Exception e) {
        log.error("Error signing data : ", e);
    }
    return retdata;
}

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

License:Open Source License

private byte[] createPKCS7(Certificate[] chain, PrivateKey pk, X509Certificate cert)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException,
        CertStoreException, CMSException, IOException {
    Collection<Certificate> certList = Arrays.asList(chain);
    CMSProcessable msg = new CMSProcessableByteArray(new byte[0]);
    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    gen.addCertificatesAndCRLs(certs);/*from   ww w  .  ja  v  a  2  s.  c  om*/
    // it is possible to sign the pkcs7, but it's not currently used
    CMSSignedData s = null;
    if ((pk != null) && (cert != null)) {
        gen.addSigner(pk, cert, CMSSignedDataGenerator.DIGEST_MD5);
        s = gen.generate(msg, true, "BC");
    } else {
        s = gen.generate(msg, "BC");
    }
    return s.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   ww w .  j av  a2s  .  co  m
    // 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.jnotary.crypto.Signer.java

License:Open Source License

public byte[] sign(UserKeyStore myStorage, byte[] content, Parameters parameters) throws Exception {

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder(algorithm).setProvider("BC")
            .build(myStorage.getPrivateKey());

    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer,
                    myStorage.getUserCertificate()));

    if (parameters.isAddSignerSertificate())
        gen.addCertificates(myStorage.getCertStore());

    CMSTypedData msg = new CMSProcessableByteArray(content);
    CMSSignedData sigData = gen.generate(msg, !parameters.isDetached());
    return sigData.getEncoded();
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

private static byte[] getEncoded(CMSSignedData obj) throws IOException {
    if (obj != null) {
        return obj.getEncoded();
    }//from ww w .  j a  va2  s .c om
    return new byte[] { '0', 0 };
}

From source file:org.jscep.content.NextCaCertificateContentHandler.java

License:Open Source License

/**
 * {@inheritDoc}/*from   ww w .  j  a v  a 2  s  . c o  m*/
 */
public List<X509Certificate> getContent(InputStream in, String mimeType) throws IOException {
    LOGGER.entering(getClass().getName(), "getContent", new Object[] { in, mimeType });

    if (mimeType.equals("application/x-x509-next-ca-cert")) {
        // http://tools.ietf.org/html/draft-nourse-scep-20#section-4.6.1

        // The response consists of a SignedData PKCS#7 [RFC2315], 
        // signed by the current CA (or RA) signing key.
        final List<X509Certificate> certs = new ArrayList<X509Certificate>();

        Collection<? extends Certificate> collection;
        try {
            CMSSignedData cmsMessageData = new CMSSignedData(getBytes(in));
            ContentInfo cmsContentInfo = ContentInfo
                    .getInstance(ASN1Object.fromByteArray(cmsMessageData.getEncoded()));

            // TODO: This must be signed by the current CA.
            final SignedData sd = SignedData.getInstance(cmsContentInfo.getContent());
            if (SignedDataUtil.isSignedBy(sd, issuer) == false) {
                IOException ioe = new IOException("Invalid Signer");

                LOGGER.throwing(getClass().getName(), "getContent", ioe);
                throw ioe;
            }
            // The content of the SignedData PKCS#7 [RFC2315] is a degenerate
            // certificates-only Signed-data (Section 3.3) message containing the
            // new CA certificate and any new RA certificates, as defined in
            // Section 5.2.1.1.2, to be used when the current CA certificate
            // expires.
            CertStore store = SignedDataUtil.extractCertStore(sd);
            collection = store.getCertificates(new X509CertSelector());
        } catch (GeneralSecurityException e) {
            final IOException ioe = new IOException(e);

            LOGGER.throwing(getClass().getName(), "getContent", ioe);
            throw ioe;
        } catch (CMSException e) {
            final IOException ioe = new IOException(e);

            LOGGER.throwing(getClass().getName(), "getContent", ioe);
            throw ioe;
        }

        for (Certificate cert : collection) {
            certs.add((X509Certificate) cert);
        }

        LOGGER.exiting(getClass().getName(), "getContent", certs);
        return certs;
    } else {
        IOException ioe = new IOException("Invalid Content Type");

        LOGGER.throwing(getClass().getName(), "getContent", ioe);
        throw ioe;
    }
}

From source file:org.jscep.server.ScepServlet.java

License:Open Source License

/**
 * {@inheritDoc}//from   w  w  w. ja  v a2  s  .  co m
 */
@SuppressWarnings("unchecked")
@Override
public final void service(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    byte[] body = getMessageBytes(req);

    final Operation op;
    try {
        op = getOperation(req);
        if (op == null) {
            // The operation parameter must be set.
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing \"operation\" parameter.");
            return;
        }
    } catch (IllegalArgumentException e) {
        // The operation was not recognised.
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid \"operation\" parameter.");
        return;
    }

    LOGGER.debug("Incoming Operation: " + op);

    final String reqMethod = req.getMethod();

    if (op == Operation.PKI_OPERATION) {
        if (!reqMethod.equals(POST) && !reqMethod.equals(GET)) {
            // PKIOperation must be sent using GET or POST

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET + ", " + POST);

            return;
        }
    } else {
        if (!reqMethod.equals(GET)) {
            // Operations other than PKIOperation must be sent using GET

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET);

            return;
        }
    }

    LOGGER.debug("Method " + reqMethod + " Allowed for Operation: " + op);

    if (op == Operation.GET_CA_CAPS) {
        try {
            LOGGER.debug("Invoking doGetCaCaps");
            doGetCaCaps(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetCaCert");
            doGetCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_NEXT_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetNextCaCert");
            doGetNextCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.PKI_OPERATION) {
        // PKIOperation

        res.setHeader("Content-Type", "application/x-pki-message");

        CMSSignedData sd;
        try {
            sd = new CMSSignedData(body);
        } catch (CMSException e) {
            throw new ServletException(e);
        }

        Store reqStore = sd.getCertificates();
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        CertificateFactory factory;
        try {
            factory = CertificateFactory.getInstance("X.509");
        } catch (CertificateException e) {
            throw new ServletException(e);
        }
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert;
        try {
            reqCert = (X509Certificate) factory.generateCertificate(bais);
        } catch (CertificateException e) {
            throw new ServletException(e);
        }

        PkiMessage<?> msg;
        try {
            PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(), getRecipientKey());
            PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder);
            msg = decoder.decode(sd);
        } catch (MessageDecodingException e) {
            LOGGER.error("Error decoding request", e);
            throw new ServletException(e);
        }

        LOGGER.debug("Processing message {}", msg);

        MessageType msgType = msg.getMessageType();
        Object msgData = msg.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = msg.getTransactionId();
        Nonce recipientNonce = msg.getSenderNonce();
        CertRep certRep;

        if (msgType == MessageType.GET_CERT) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name principal = iasn.getName();
            final BigInteger serial = iasn.getSerialNumber().getValue();

            try {
                List<X509Certificate> issued = doGetCert(principal, serial);
                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CERT_INITIAL) {
            final IssuerAndSubject ias = (IssuerAndSubject) msgData;
            final X500Name issuer = X500Name.getInstance(ias.getIssuer());
            final X500Name subject = X500Name.getInstance(ias.getSubject());

            try {
                List<X509Certificate> issued = doGetCertInitial(issuer, subject, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CRL) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name issuer = iasn.getName();
            final BigInteger serialNumber = iasn.getSerialNumber().getValue();

            try {
                LOGGER.debug("Invoking doGetCrl");
                CMSSignedData messageData = getMessageData(doGetCrl(issuer, serialNumber));

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            } catch (OperationFailureException e) {
                LOGGER.error("Error executing GetCRL request", e);
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                LOGGER.error("Error executing GetCRL request", e);
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.PKCS_REQ) {
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData;

            try {
                LOGGER.debug("Invoking doEnrol");
                List<X509Certificate> issued = doEnrol(certReq, reqCert, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else {
            throw new ServletException("Unknown Message for Operation");
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede");
        PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(), getSigner(),
                getSignerCertificateChain(), envEncoder);
        CMSSignedData signedData;
        try {
            signedData = encoder.encode(certRep);
        } catch (MessageEncodingException e) {
            LOGGER.error("Error decoding response", e);
            throw new ServletException(e);
        }

        res.getOutputStream().write(signedData.getEncoded());
        res.getOutputStream().close();
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation");
    }
}

From source file:org.jscep.server.ScepServlet.java

License:Open Source License

private void doGetNextCaCert(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
    res.setHeader("Content-Type", "application/x-x509-next-ca-cert");

    List<X509Certificate> certs = getNextCaCertificate(req.getParameter(MSG_PARAM));

    if (certs.size() == 0) {
        res.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "GetNextCACert Not Supported");
    } else {/*from w  w w  .jav a2  s . co  m*/
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        JcaCertStore store;
        try {
            store = new JcaCertStore(certs);
        } catch (CertificateEncodingException e) {
            IOException ioe = new IOException();
            ioe.initCause(e);

            throw ioe;
        }
        generator.addCertificates(store);
        DigestCalculatorProvider digestProvider = new JcaDigestCalculatorProviderBuilder().build();
        SignerInfoGeneratorBuilder infoGenBuilder = new SignerInfoGeneratorBuilder(digestProvider);
        X509CertificateHolder certHolder = new X509CertificateHolder(getRecipient().getEncoded());
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(getRecipientKey());
        SignerInfoGenerator infoGen = infoGenBuilder.build(contentSigner, certHolder);
        generator.addSignerInfoGenerator(infoGen);

        CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
        byte[] bytes = degenerateSd.getEncoded();

        res.getOutputStream().write(bytes);
        res.getOutputStream().close();
    }
}

From source file:org.jscep.server.ScepServlet.java

License:Open Source License

private void doGetCaCert(final HttpServletRequest req, final HttpServletResponse res) throws Exception {
    final List<X509Certificate> certs = doGetCaCertificate(req.getParameter(MSG_PARAM));
    final byte[] bytes;
    if (certs.size() == 0) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "GetCaCert failed to obtain CA from store");
        bytes = new byte[0];
    } else if (certs.size() == 1) {
        res.setHeader("Content-Type", "application/x-x509-ca-cert");
        bytes = certs.get(0).getEncoded();
    } else {//  ww  w  .ja v  a  2s .  co m
        res.setHeader("Content-Type", "application/x-x509-ca-ra-cert");
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        JcaCertStore store;
        try {
            store = new JcaCertStore(certs);
        } catch (CertificateEncodingException e) {
            IOException ioe = new IOException();
            ioe.initCause(e);

            throw ioe;
        }
        generator.addCertificates(store);
        CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
        bytes = degenerateSd.getEncoded();
    }

    res.getOutputStream().write(bytes);
    res.getOutputStream().close();
}