Example usage for org.bouncycastle.cms CMSSignedDataGenerator generate

List of usage examples for org.bouncycastle.cms CMSSignedDataGenerator generate

Introduction

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

Prototype

public CMSSignedData generate(CMSTypedData content) throws CMSException 

Source Link

Document

Generate a CMS Signed Data object carrying a detached CMS signature.

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 ww .j av  a2 s  . c  o m
 * @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.CAdESService.java

License:Open Source License

/**
 * This method countersigns a signature identified through its SignerId
 *
 * @param toCounterSignDocument the original signature document containing the signature to countersign
 * @param parameters            the signature parameters
 * @param selector              the SignerId identifying the signature to countersign
 * @return the updated signature document, in which the countersignature has been embedded
 *///ww w.ja  v a  2  s .c  o  m
public DSSDocument counterSignDocument(final DSSDocument toCounterSignDocument,
        final SignatureParameters parameters, SignerId selector) {

    final SignatureTokenConnection token = parameters.getSigningToken();
    if (token == null) {

        throw new DSSNullException(SignatureTokenConnection.class, "",
                "The connection through available API to the SSCD must be set.");
    }

    try {
        //Retrieve the original signature
        final InputStream inputStream = toCounterSignDocument.openStream();
        final CMSSignedData cmsSignedData = new CMSSignedData(inputStream);
        DSSUtils.closeQuietly(inputStream);

        SignerInformationStore signerInfos = cmsSignedData.getSignerInfos();
        SignerInformation signerInformation = signerInfos.get(selector);

        //Generate a signed digest on the contents octets of the signature octet String in the identified SignerInfo value
        //of the original signature's SignedData
        byte[] dataToSign = signerInformation.getSignature();
        byte[] signatureValue = token.sign(dataToSign, parameters.getDigestAlgorithm(),
                parameters.getPrivateKeyEntry());

        //Set the countersignature builder
        CounterSignatureBuilder builder = new CounterSignatureBuilder(certificateVerifier);
        builder.setCmsSignedData(cmsSignedData);
        builder.setSelector(selector);

        final SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm();
        final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(),
                signatureValue);

        SignerInfoGeneratorBuilder signerInformationGeneratorBuilder = builder
                .getSignerInfoGeneratorBuilder(parameters, true);
        CMSSignedDataGenerator cmsSignedDataGenerator = builder.createCMSSignedDataGenerator(parameters,
                customContentSigner, signerInformationGeneratorBuilder, null);
        CMSTypedData content = cmsSignedData.getSignedContent();
        CMSSignedData signedData = cmsSignedDataGenerator.generate(content);
        final CMSSignedData countersignedCMSData = builder.signDocument(signedData);
        final CMSSignedDocument signature = new CMSSignedDocument(countersignedCMSData);
        return signature;

    } catch (CMSException e) {
        throw new DSSException("Cannot parse CMS data", e);
    }
}

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.  ja va2  s  .c o  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.apache.felix.deploymentadmin.itest.util.DPSigner.java

License:Apache License

private byte[] calculateSignatureBlock(PrivateKey privKey, X509Certificate cert, byte[] sfRawBytes)
        throws Exception {
    String signatureAlgorithm = getSignatureAlgorithm(privKey);

    DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().build();
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider).build(signer, cert));
    gen.addCertificates(new JcaCertStore(Arrays.asList(cert)));

    CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(sfRawBytes));

    return sigData.getEncoded();
}

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

License:Open Source License

private CMSSignedData getMessageData(final List<X509Certificate> certs)
        throws IOException, CMSException, GeneralSecurityException {
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    JcaCertStore store;/*ww w .  j  a  va2 s  .  co m*/
    try {
        store = new JcaCertStore(certs);
    } catch (CertificateEncodingException e) {
        IOException ioe = new IOException();
        ioe.initCause(e);

        throw ioe;
    }
    generator.addCertificates(store);
    return generator.generate(new CMSAbsentContent());
}

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

License:Open Source License

private CMSSignedData getMessageData(final X509CRL crl)
        throws IOException, CMSException, GeneralSecurityException {
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    JcaCRLStore store;//from   ww w  .j  av  a  2s  .com
    if (crl == null) {
        store = new JcaCRLStore(Collections.emptyList());
    } else {
        store = new JcaCRLStore(Collections.singleton(crl));
    }
    generator.addCRLs(store);
    return generator.generate(new CMSAbsentContent());
}

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 {/*ww  w  .  ja  v a2s . c  om*/
        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 {//from  w  w w .j  a  v a 2s  . c  o  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();
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

License:Open Source License

private CMSSignedData getMessageData(final List<X509Certificate> certs) throws KeystoreException {

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    JcaCertStore store;//  w  w w . j a  v  a 2 s.c o m
    try {
        store = new JcaCertStore(certs);
        generator.addCertificates(store);

        return generator.generate(new CMSAbsentContent());
    } catch (CertificateEncodingException e) {
        String errorMsg = "Certificate encoding issue occurred when generating getMessageData";
        throw new KeystoreException(errorMsg, e);
    } catch (CMSException e) {
        String errorMsg = "Message decoding issue occurred when generating getMessageData";
        throw new KeystoreException(errorMsg, e);
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

License:Open Source License

public SCEPResponse getCACert() throws KeystoreException {

    try {/* w w w. j a  v  a2 s  . c  o  m*/
        SCEPResponse scepResponse = new SCEPResponse();
        KeyStoreReader keyStoreReader = new KeyStoreReader();

        byte[] caBytes = keyStoreReader.getCACertificate().getEncoded();
        byte[] raBytes = keyStoreReader.getRACertificate().getEncoded();

        final List<X509Certificate> certs = getRootCertificates(caBytes, raBytes);

        byte[] bytes;
        if (certs.size() == 0) {
            scepResponse.setResultCriteria(CAStatus.CA_CERT_FAILED);
            bytes = new byte[0];
        } else if (certs.size() == 1) {
            scepResponse.setResultCriteria(CAStatus.CA_CERT_RECEIVED);
            bytes = certs.get(0).getEncoded();
        } else {
            scepResponse.setResultCriteria(CAStatus.CA_RA_CERT_RECEIVED);
            CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
            JcaCertStore store = new JcaCertStore(certs);
            generator.addCertificates(store);
            CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent());
            bytes = degenerateSd.getEncoded();
        }
        scepResponse.setEncodedResponse(bytes);

        return scepResponse;
    } catch (CertificateEncodingException e) {
        String errorMsg = "Certificate encoding issue occurred in getCACert";
        throw new KeystoreException(errorMsg, e);
    } catch (CMSException e) {
        String errorMsg = "CMS issue occurred in getCACert";
        throw new KeystoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Input output issue occurred in getCACert";
        throw new KeystoreException(errorMsg, e);
    }
}