Example usage for org.bouncycastle.cms SignerInfoGeneratorBuilder build

List of usage examples for org.bouncycastle.cms SignerInfoGeneratorBuilder build

Introduction

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

Prototype

public SignerInfoGenerator build(ContentSigner contentSigner, byte[] subjectKeyIdentifier)
        throws OperatorCreationException 

Source Link

Document

Build a generator with the passed in subjectKeyIdentifier as the signerIdentifier.

Usage

From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to create exCap's signature with the issuer certificate detached 
 * from the signed data // w w w . j  av  a 2s .  com
 * @param credentials: the credential that contains private key to sign the
 * data
 * @param content: the data or content to be signed
 * @return: signed data in byte[]
 * @throws OperatorCreationException
 * @throws CMSException
 * @throws IOException
 */
public static byte[] createCapSignature(BcCredential credentials, String content)
        throws OperatorCreationException, CMSException, IOException {

    AsymmetricKeyParameter key = credentials.getPrivateKey();
    X509CertificateHolder[] chain = credentials.getCertificateChain();

    X509CertificateHolder cert = chain[0];
    //    Store certs = new CollectionStore(Arrays.asList(chain));

    // construct SignerInfoGenerator manually --> to deal with signingTime issue
    SignerInfoGeneratorBuilder sigBuilder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider());

    Hashtable<ASN1ObjectIdentifier, Attribute> signedAttr = new Hashtable<ASN1ObjectIdentifier, Attribute>();

    Attribute attr = new Attribute(CMSAttributes.signingTime, new DERSet(new Time(new java.util.Date())));

    signedAttr.put(attr.getAttrType(), attr);
    AttributeTable signedAttributeTable = new AttributeTable(signedAttr);

    sigBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttributeTable));

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

    AlgorithmIdentifier sigAlg = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withECDSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    SignerInfoGenerator signerInfoGen = sigBuilder
            .build(new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(key), cert);

    gen.addSignerInfoGenerator(signerInfoGen);

    //    gen.addSignerInfoGenerator(new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()).build(new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(key), cert));
    // do not store the certificate with signed data (i.e. detached signature)
    //    gen.addCertificates(certs);

    // create the signed-data object
    CMSTypedData data = new CMSProcessableByteArray(content.getBytes());

    CMSSignedData signed = gen.generate(data);

    // recreate
    //    signed = new CMSSignedData(data, signed.getEncoded());

    return signed.getEncoded();
}

From source file:eu.europa.ec.markt.dss.signature.cades.CMSSignedDataBuilder.java

License:Open Source License

/**
 * Note:/*from  w w w.  j  a  va2 s .  com*/
 * Section 5.1 of RFC 3852 [4] requires that, the CMS SignedData version be set to 3 if certificates from
 * SignedData is present AND (any version 1 attribute certificates are present OR any SignerInfo structures
 * are version 3 OR eContentType from encapContentInfo is other than id-data). Otherwise, the CMS
 * SignedData version is required to be set to 1.
 * ---> CMS SignedData Version is handled automatically by BouncyCastle.
 *
 * @param parameters                 set of the driving signing parameters
 * @param contentSigner              the contentSigned to get the hash of the data to be signed
 * @param signerInfoGeneratorBuilder true if the unsigned attributes must be included
 * @param originalSignedData         the original signed data if extending an existing signature. null otherwise.  @return the bouncycastle signed data generator which will
 *                                   sign
 *                                   the document and add the required signed and unsigned CMS attributes
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
protected CMSSignedDataGenerator createCMSSignedDataGenerator(final SignatureParameters parameters,
        final ContentSigner contentSigner, final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder,
        final CMSSignedData originalSignedData) throws DSSException {
    try {

        final X509Certificate signingCertificate = parameters.getSigningCertificate();

        final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        final X509CertificateHolder certHolder = DSSUtils.getX509CertificateHolder(signingCertificate);
        final SignerInfoGenerator signerInfoGenerator = signerInfoGeneratorBuilder.build(contentSigner,
                certHolder);

        generator.addSignerInfoGenerator(signerInfoGenerator);

        final Set<X509Certificate> newCertificateChain = new HashSet<X509Certificate>();

        if (originalSignedData != null) {

            generator.addSigners(originalSignedData.getSignerInfos());
            generator.addAttributeCertificates(originalSignedData.getAttributeCertificates());
            generator.addCRLs(originalSignedData.getCRLs());
            generator.addOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic,
                    originalSignedData.getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic));
            generator.addOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response,
                    originalSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response));

            final Store certificates = originalSignedData.getCertificates();
            final Collection<X509CertificateHolder> certificatesMatches = certificates.getMatches(null);
            for (final X509CertificateHolder certificatesMatch : certificatesMatches) {
                newCertificateChain.add(DSSUtils.getCertificate(certificatesMatch));
            }
        }
        final List<X509Certificate> certificateChain = parameters.getCertificateChain();
        newCertificateChain.addAll(certificateChain);
        final Store jcaCertStore = getJcaCertStore(signingCertificate, newCertificateChain);
        generator.addCertificates(jcaCertStore);
        return generator;

    } catch (CMSException e) {
        throw new DSSException(e);
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.pades.PAdESProfileEPES.java

License:Open Source License

CMSSignedDataGenerator createCMSSignedDataGenerator(ContentSigner contentSigner,
        DigestCalculatorProvider digestCalculatorProvider, final SignatureParameters parameters,
        final byte[] messageDigest) throws IOException {
    try {/*from www  .  j a  va  2 s  .c o  m*/

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        X509Certificate signerCertificate = parameters.getSigningCertificate();

        X509CertificateHolder certHolder = new X509CertificateHolder(signerCertificate.getEncoded());

        SignerInfoGeneratorBuilder sigenb = new SignerInfoGeneratorBuilder(digestCalculatorProvider);

        final CAdESProfileEPES profile = new CAdESProfileEPES(true);

        sigenb = sigenb.setSignedAttributeGenerator(new CMSAttributeTableGenerator() {
            @Override
            public AttributeTable getAttributes(Map params) throws CMSAttributeTableGenerationException {
                Hashtable clone = (Hashtable) profile.getSignedAttributes(parameters).clone();

                if (!clone.containsKey(CMSAttributes.contentType)) {
                    DERObjectIdentifier contentType = (DERObjectIdentifier) params
                            .get(CMSAttributeTableGenerator.CONTENT_TYPE);

                    // contentType will be null if we're trying to generate a counter signature.
                    if (contentType != null) {
                        Attribute attr = new Attribute(CMSAttributes.contentType, new DERSet(contentType));
                        clone.put(attr.getAttrType(), attr);
                    }
                }

                if (!clone.containsKey(CMSAttributes.messageDigest)) {
                    System.out.println("Digest propos : "
                            + org.apache.commons.codec.binary.Hex.encodeHexString(messageDigest));
                    // byte[] messageDigest = (byte[]) params.get(CMSAttributeTableGenerator.DIGEST);
                    Attribute attr = new Attribute(CMSAttributes.messageDigest,
                            new DERSet(new DEROctetString(messageDigest)));
                    clone.put(attr.getAttrType(), attr);
                }

                if (parameters.getCommitmentTypeIndication() != null
                        && !parameters.getCommitmentTypeIndication().isEmpty()) {
                    ASN1EncodableVector vector = new ASN1EncodableVector();
                    for (String id : parameters.getCommitmentTypeIndication()) {
                        vector.add(new DERObjectIdentifier(id));
                    }
                    DERSet set = new DERSet(new DERSequence(vector));
                    Attribute attr = new Attribute(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.16"), set);
                    clone.put(attr.getAttrType(), attr);
                }

                return new AttributeTable(clone);
            }
        });

        // sigenb.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(new AttributeTable(
        // new Hashtable<ASN1ObjectIdentifier, ASN1Encodable>())));

        /*
         * We don't include a unsigned attribute table if not needed : a unsignedAttrs of signerInfo includes no
         * Attribute, UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute(defined in RFC3852).
         */
        SignerInfoGenerator sigen = sigenb.build(contentSigner, certHolder);

        generator.addSignerInfoGenerator(sigen);

        Collection<X509Certificate> certs = new ArrayList<X509Certificate>();
        if (parameters.getCertificateChain() == null
                || !parameters.getCertificateChain().contains(parameters.getSigningCertificate())) {
            certs.add(parameters.getSigningCertificate());
        }
        certs.addAll(parameters.getCertificateChain());
        JcaCertStore certStore = new JcaCertStore(certs);
        generator.addCertificates(certStore);

        System.out.println("Gnrator cr");
        return generator;

    } catch (CertificateException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    }

}

From source file:eu.europa.esig.dss.cades.signature.CMSSignedDataBuilder.java

License:Open Source License

/**
 * Note:/*from w  w w  .j a  va2 s.c o m*/
 * Section 5.1 of RFC 3852 [4] requires that, the CMS SignedData version be set to 3 if certificates from
 * SignedData is present AND (any version 1 attribute certificates are present OR any SignerInfo structures
 * are version 3 OR eContentType from encapContentInfo is other than id-data). Otherwise, the CMS
 * SignedData version is required to be set to 1.
 * ---> CMS SignedData Version is handled automatically by BouncyCastle.
 *
 * @param parameters                 set of the driving signing parameters
 * @param contentSigner              the contentSigned to get the hash of the data to be signed
 * @param signerInfoGeneratorBuilder true if the unsigned attributes must be included
 * @param originalSignedData         the original signed data if extending an existing signature. null otherwise.
 * @return the bouncycastle signed data generator which signs the document and adds the required signed and unsigned CMS attributes
 * @throws eu.europa.esig.dss.DSSException
 */
protected CMSSignedDataGenerator createCMSSignedDataGenerator(final CAdESSignatureParameters parameters,
        final ContentSigner contentSigner, final SignerInfoGeneratorBuilder signerInfoGeneratorBuilder,
        final CMSSignedData originalSignedData) throws DSSException {
    try {

        final CertificateToken signingCertificate = parameters.getSigningCertificate();

        final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        final X509CertificateHolder certHolder = DSSASN1Utils.getX509CertificateHolder(signingCertificate);
        final SignerInfoGenerator signerInfoGenerator = signerInfoGeneratorBuilder.build(contentSigner,
                certHolder);

        generator.addSignerInfoGenerator(signerInfoGenerator);

        final Set<CertificateToken> certificateChain = new HashSet<CertificateToken>();

        if (originalSignedData != null) {

            generator.addSigners(originalSignedData.getSignerInfos());
            generator.addAttributeCertificates(originalSignedData.getAttributeCertificates());
            generator.addCRLs(originalSignedData.getCRLs());
            generator.addOtherRevocationInfo(id_pkix_ocsp_basic,
                    originalSignedData.getOtherRevocationInfo(id_pkix_ocsp_basic));
            generator.addOtherRevocationInfo(id_ri_ocsp_response,
                    originalSignedData.getOtherRevocationInfo(id_ri_ocsp_response));

            final Store certificates = originalSignedData.getCertificates();
            final Collection<X509CertificateHolder> certificatesMatches = certificates.getMatches(null);
            for (final X509CertificateHolder certificatesMatch : certificatesMatches) {

                final CertificateToken x509Certificate = DSSASN1Utils.getCertificate(certificatesMatch);
                certificateChain.add(x509Certificate);
            }
        }
        certificateChain.add(parameters.getSigningCertificate());
        certificateChain.addAll(parameters.getCertificateChain());

        final boolean trustAnchorBPPolicy = parameters.bLevel().isTrustAnchorBPPolicy();
        final Store jcaCertStore = getJcaCertStore(certificateChain, trustAnchorBPPolicy);
        generator.addCertificates(jcaCertStore);
        return generator;
    } catch (CMSException e) {
        throw new DSSException(e);
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.esig.dss.cookbook.mock.MockTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {

    final String signatureAlgorithm = getSignatureAlgorithm(digestAlgorithm, digest);

    final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);/*w w w.j av a 2 s  . c  om*/

    /**
     * The code below guarantee that the dates of the two successive
     * timestamps are different. This is activated only if timestampDate is provided at
     * construction time
     */
    Date timestampDate_ = new Date();

    if (policyOid != null) {
        tsqGenerator.setReqPolicy(policyOid);
    }

    TimeStampRequest tsRequest = null;
    if (useNonce) {
        final BigInteger nonce = BigInteger.valueOf(random.nextLong());
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest, nonce);
    } else {
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest);
    }

    try {
        final ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).build(key);
        final JcaX509CertificateHolder certHolder = new JcaX509CertificateHolder(cert.getCertificate());

        // that to make sure we generate the same timestamp data for the
        // same timestamp date
        AttributeTable signedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        signedAttributes = signedAttributes.add(PKCSObjectIdentifiers.pkcs_9_at_signingTime,
                new Time(timestampDate_));
        final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributes);
        AttributeTable unsignedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        final SimpleAttributeTableGenerator unsignedAttributeGenerator = new SimpleAttributeTableGenerator(
                unsignedAttributes);

        final DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();
        SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
                digestCalculatorProvider);
        sigInfoGeneratorBuilder.setSignedAttributeGenerator(signedAttributeGenerator);
        sigInfoGeneratorBuilder.setUnsignedAttributeGenerator(unsignedAttributeGenerator);
        final SignerInfoGenerator sig = sigInfoGeneratorBuilder.build(sigGen, certHolder);

        final DigestCalculator sha1DigestCalculator = DSSRevocationUtils.getSHA1DigestCalculator();

        final TimeStampTokenGenerator tokenGenerator = new TimeStampTokenGenerator(sig, sha1DigestCalculator,
                policyOid);
        final Set<X509Certificate> singleton = new HashSet<X509Certificate>();
        singleton.add(cert.getCertificate());
        tokenGenerator.addCertificates(new JcaCertStore(singleton));
        final TimeStampResponseGenerator generator = new TimeStampResponseGenerator(tokenGenerator,
                TSPAlgorithms.ALLOWED);

        Date responseDate = new Date();
        TimeStampResponse tsResponse = generator.generate(tsRequest, BigInteger.ONE, responseDate);
        final TimeStampToken timeStampToken = tsResponse.getTimeStampToken();
        return timeStampToken;
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    } catch (CertificateEncodingException e) {
        throw new DSSException(e);
    } catch (TSPException e) {
        throw new DSSException(e);
    }
}

From source file:mitm.common.security.smime.SMIMEBuilderImpl.java

License:Open Source License

private void addSigner(PrivateKey privateKey, X509Certificate signer, SMIMESigningAlgorithm algorithm,
        AttributeTable signedAttr, AttributeTable unsignedAttr) throws SMIMEBuilderException {
    try {//from   w  w  w  .  j  a v a 2  s  .  c  om
        JcaDigestCalculatorProviderBuilder digestBuilder = new JcaDigestCalculatorProviderBuilder();

        digestBuilder.setProvider(nonSensitiveProvider);

        SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(digestBuilder.build());

        if (signedAttr != null) {
            signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttr));
        }

        if (unsignedAttr != null) {
            signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(unsignedAttr));
        }

        JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(algorithm.getAlgorithm());

        contentSignerBuilder.setProvider(sensitiveProvider);

        SignerInfoGenerator signerInfoGenerator = signerInfoBuilder
                .build(contentSignerBuilder.build(privateKey), new JcaX509CertificateHolder(signer));

        signedGenerator.addSignerInfoGenerator(signerInfoGenerator);
    } catch (OperatorCreationException e) {
        throw new SMIMEBuilderException(e);
    } catch (CertificateEncodingException e) {
        throw new SMIMEBuilderException(e);
    }
}

From source file:mitm.common.security.smime.SMIMEBuilderImpl.java

License:Open Source License

public void addSigner(PrivateKey privateKey, byte[] subjectKeyIdentifier, SMIMESigningAlgorithm algorithm,
        AttributeTable signedAttr, AttributeTable unsignedAttr) throws SMIMEBuilderException {
    try {/*from   w ww.  j a v  a  2 s  .com*/
        JcaDigestCalculatorProviderBuilder digestBuilder = new JcaDigestCalculatorProviderBuilder();

        digestBuilder.setProvider(nonSensitiveProvider);

        SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(digestBuilder.build());

        if (signedAttr != null) {
            signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttr));
        }

        if (unsignedAttr != null) {
            signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(unsignedAttr));
        }

        JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(algorithm.getAlgorithm());

        contentSignerBuilder.setProvider(sensitiveProvider);

        SignerInfoGenerator signerInfoGenerator = signerInfoBuilder
                .build(contentSignerBuilder.build(privateKey), subjectKeyIdentifier);

        signedGenerator.addSignerInfoGenerator(signerInfoGenerator);
    } catch (OperatorCreationException e) {
        throw new SMIMEBuilderException(e);
    }
}

From source file:net.jsign.PESigner.java

License:Apache License

private CMSSignedData createSignature(PEFile file)
        throws IOException, CMSException, OperatorCreationException, CertificateEncodingException {
    byte[] sha = file.computeDigest(algo);

    AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(algo.oid, DERNull.INSTANCE);
    DigestInfo digestInfo = new DigestInfo(algorithmIdentifier, sha);
    SpcAttributeTypeAndOptionalValue data = new SpcAttributeTypeAndOptionalValue(
            AuthenticodeObjectIdentifiers.SPC_PE_IMAGE_DATA_OBJID, new SpcPeImageData());
    SpcIndirectDataContent spcIndirectDataContent = new SpcIndirectDataContent(data, digestInfo);

    ContentSigner shaSigner = new JcaContentSignerBuilder(algo + "with" + privateKey.getAlgorithm())
            .build(privateKey);//w w  w  .ja  v a 2  s. c o  m
    DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().build();

    // prepare the authenticated attributes
    CMSAttributeTableGenerator attributeTableGenerator = new DefaultSignedAttributeTableGenerator(
            createAuthenticatedAttributes());

    // fetch the signing certificate
    X509CertificateHolder certificate = new JcaX509CertificateHolder((X509Certificate) chain[0]);

    // prepare the signerInfo with the extra authenticated attributes
    SignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
            digestCalculatorProvider);
    signerInfoGeneratorBuilder.setSignedAttributeGenerator(attributeTableGenerator);
    SignerInfoGenerator signerInfoGenerator = signerInfoGeneratorBuilder.build(shaSigner, certificate);

    AuthenticodeSignedDataGenerator generator = new AuthenticodeSignedDataGenerator();
    generator.addCertificates(new JcaCertStore(removeRoot(chain)));
    generator.addSignerInfoGenerator(signerInfoGenerator);

    return generator.generate(AuthenticodeObjectIdentifiers.SPC_INDIRECT_DATA_OBJID, spcIndirectDataContent);
}

From source file:no.difi.oxalis.as2.util.SMimeBC.java

License:EUPL

public static byte[] createSignature(byte[] digest, SMimeDigestMethod digestMethod, PrivateKey privateKey,
        X509Certificate certificate) throws OxalisSecurityException {
    try {//from  w w  w. j  av  a  2 s.  co m
        ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
        signedAttributes.add(new Attribute(CMSAttributes.contentType, new DERSet(digestMethod.getOid())));
        signedAttributes
                .add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest))));
        signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));

        AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
        signedAttributesTable.toASN1EncodableVector();
        DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        /* Build the SignerInfo generator builder, that will build the generator... that will generate the SignerInformation... */
        SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .build());
        signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator);
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(digestMethod.getMethod())
                .setProvider(BouncyCastleProvider.PROVIDER_NAME);

        generator.addSignerInfoGenerator(signerInfoBuilder.build(contentSigner.build(privateKey),
                new X509CertificateHolder(certificate.getEncoded())));
        generator.addCertificates(new JcaCertStore(Collections.singletonList(certificate)));

        return generator.generate(new CMSAbsentContent()).getEncoded();
    } catch (CMSException | IOException | CertificateEncodingException | OperatorCreationException e) {
        throw new OxalisSecurityException(e.getMessage(), e);
    }
}

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 ww .  ja v  a2s.c o 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();
    }
}