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, boolean encapsulate) throws CMSException 

Source Link

Document

Generate a CMS Signed Data object which can be carrying a detached CMS signature, or have encapsulated data, depending on the value of the encapsulated parameter.

Usage

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

License:Open Source License

@Override
public InputStream toBeSigned(Document document, SignatureParameters parameters) throws IOException {
    try {//from w w w  . j a v  a  2 s  .c o m
        PAdESProfileEPES padesProfile = new PAdESProfileEPES();

        PDFSignatureService pdfSignatureService = getPDFService();
        byte[] messageDigest = pdfSignatureService.digest(document.openStream(), parameters);

        LOG.fine("Calculated digest on byterange " + Hex.encodeHexString(messageDigest));

        PreComputedContentSigner contentSigner = new PreComputedContentSigner(
                SignatureAlgorithm.RSA.getJavaSignatureAlgorithm(parameters.getDigestAlgorithm()));

        DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();
        CMSSignedDataGenerator generator = padesProfile.createCMSSignedDataGenerator(contentSigner,
                digestCalculatorProvider, parameters, messageDigest);

        CMSProcessableByteArray content = new CMSProcessableByteArray(
                pdfSignatureService.digest(document.openStream(), parameters));

        generator.generate(content, false);

        return new ByteArrayInputStream(contentSigner.getByteOutputStream().toByteArray());
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (DocumentException e) {
        throw new IOException(e);
    }

}

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

License:Open Source License

@Override
public Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue)
        throws IOException {
    try {//from   w w w .  j ava 2 s  .c  om

        PAdESProfileEPES padesProfile = new PAdESProfileEPES();

        PreComputedContentSigner contentSigner = new PreComputedContentSigner(
                SignatureAlgorithm.RSA.getJavaSignatureAlgorithm(parameters.getDigestAlgorithm()),
                signatureValue);
        DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();

        PDFSignatureService pdfSignatureService = getPDFService();
        byte[] messageDigest = pdfSignatureService.digest(document.openStream(), parameters);

        CMSSignedDataGenerator generator = padesProfile.createCMSSignedDataGenerator(contentSigner,
                digestCalculatorProvider, parameters, messageDigest);

        CMSProcessableByteArray content = new CMSProcessableByteArray(messageDigest);

        CMSSignedData data = generator.generate(content, false);
        if (tspSource != null) {
            CAdESProfileT t = new CAdESProfileT();
            t.setSignatureTsa(tspSource);
            data = t.extendCMSSignedData(data, null, parameters);
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        pdfSignatureService.sign(document.openStream(), data.getEncoded(), output, parameters);
        output.close();

        Document doc = new InMemoryDocument(output.toByteArray());

        PAdESProfileLTV extension = getExtensionProfile(parameters);
        if (extension != null) {
            return extension.extendSignatures(doc, null, parameters);
        } else {
            return doc;
        }

    } catch (DocumentException ex) {
        throw new IOException(ex);
    } catch (CMSException e) {
        throw new RuntimeException(e);
    }
}

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

License:Open Source License

protected CMSSignedData regenerateCMSSignedData(CMSSignedData cmsSignedData,
        CAdESSignatureParameters parameters, Store certificatesStore, Store attributeCertificatesStore,
        Store crlsStore, Store otherRevocationInfoFormatStoreBasic, Store otherRevocationInfoFormatStoreOcsp) {
    try {//from  w w  w. j av a2 s  . co m

        final CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
        cmsSignedDataGenerator.addSigners(cmsSignedData.getSignerInfos());
        cmsSignedDataGenerator.addAttributeCertificates(attributeCertificatesStore);
        cmsSignedDataGenerator.addCertificates(certificatesStore);
        cmsSignedDataGenerator.addCRLs(crlsStore);
        cmsSignedDataGenerator.addOtherRevocationInfo(id_pkix_ocsp_basic, otherRevocationInfoFormatStoreBasic);
        cmsSignedDataGenerator.addOtherRevocationInfo(id_ri_ocsp_response, otherRevocationInfoFormatStoreOcsp);
        final boolean encapsulate = cmsSignedData.getSignedContent() != null;
        if (!encapsulate) {
            final InputStream inputStream = parameters.getDetachedContent().openStream();
            final CMSProcessableByteArray content = new CMSProcessableByteArray(
                    DSSUtils.toByteArray(inputStream));
            IOUtils.closeQuietly(inputStream);
            cmsSignedData = cmsSignedDataGenerator.generate(content, encapsulate);
        } else {
            cmsSignedData = cmsSignedDataGenerator.generate(cmsSignedData.getSignedContent(), encapsulate);
        }
        return cmsSignedData;
    } catch (CMSException e) {
        throw new DSSException(e);
    }
}

From source file:fixture.pdfboxeg.CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation./*www.  j a  v  a2s .  co  m*/
 *
 * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
 * The given InputStream contains the bytes that are given by the byte range.
 *
 * This method is for internal use only.
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 *
 * @throws IOException
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    //TODO this method should be private
    try {
        List<Certificate> certList = new ArrayList<>();
        certList.add(certificate);
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate
                .getInstance(ASN1Primitive.fromByteArray(certificate.getEncoded()));
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
        gen.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                        .build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        if (tsaClient != null) {
            signedData = signTimeStamps(signedData);
        }
        return signedData.getEncoded();
    } catch (GeneralSecurityException | CMSException | TSPException | OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:id.govca.detachedsignature.CMSController.java

/**
 * Method to digitally sign a binary content in PKCS7 format.
 * Return the CMSSignedData object of a binary content
 *
 * @param content the binary content to be signed
 * @param pkcc the PrivateKey_CertChain object
 * @return/*from w w  w  .  j a  va 2  s . c  o  m*/
 */
public CMSSignedData CMSGenerator(byte[] content, PrivateKey_CertChain pkcc) {
    Security.addProvider(new BouncyCastleProvider());

    try {
        //Sign
        Signature signature = Signature.getInstance("SHA256WithRSA", "BC");
        signature.initSign(pkcc.getPriv_key());
        signature.update(content);
        byte[] signed = signature.sign();
        System.out.format("%-32s%s\n", "Signature of digest of content", Hex.toHexString(signed));

        //Digest of Signature
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(signed);
        System.out.format("%-32s%s\n", "Digest of Signature", Hex.toHexString(hash));

        //Build CMS
        X509Certificate cert = pkcc.getSingle_cert();
        List certList = new ArrayList();
        CMSTypedData msg = new CMSProcessableByteArray(signed);

        System.out.format("%-32s%s\n", "Length of Certificate Chain", pkcc.getChain().length);

        certList.addAll(Arrays.asList(pkcc.getChain()));

        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC")
                .build(pkcc.getPriv_key());
        gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));
        gen.addCertificates(certs);
        CMSSignedData sigData = gen.generate(msg, true);

        return sigData;

    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException
            | CertificateEncodingException | OperatorCreationException | CMSException ex) {
        Logger.getLogger(CMSController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:io.aos.crypto.spl09.SignedDataExample.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);
    CertStore certsAndCRLs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
    X509Certificate cert = (X509Certificate) chain[0];

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

    gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA224);

    gen.addCertificatesAndCRLs(certsAndCRLs);

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

    CMSSignedData signed = gen.generate(data, "BC");

    // recreate/*w ww . j  a  v  a2  s. c o m*/
    signed = new CMSSignedData(data, signed.getEncoded());

    // verification step
    X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

    if (isValid(signed, rootCert)) {
        System.out.println("verification succeeded");
    } else {
        System.out.println("verification failed");
    }
}

From source file:nDasJoWo.signapk.SignApk.java

License:Apache License

private static void writeSignatureBlock(CMSTypedData paramCMSTypedData, X509Certificate paramX509Certificate,
        PrivateKey paramPrivateKey, OutputStream paramOutputStream)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    ArrayList localArrayList = new ArrayList(1);
    localArrayList.add(paramX509Certificate);
    JcaCertStore localJcaCertStore = new JcaCertStore(localArrayList);

    CMSSignedDataGenerator localCMSSignedDataGenerator = new CMSSignedDataGenerator();
    ContentSigner localContentSigner = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(sBouncyCastleProvider).build(paramPrivateKey);

    localCMSSignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build())
                    .setDirectSignature(true).build(localContentSigner, paramX509Certificate));

    localCMSSignedDataGenerator.addCertificates(localJcaCertStore);
    CMSSignedData localCMSSignedData = localCMSSignedDataGenerator.generate(paramCMSTypedData, false);

    ASN1InputStream localASN1InputStream = new ASN1InputStream(localCMSSignedData.getEncoded());
    DEROutputStream localDEROutputStream = new DEROutputStream(paramOutputStream);
    localDEROutputStream.writeObject(localASN1InputStream.readObject());
}

From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectBuilder.java

License:BSD License

private byte[] doGenerate(X509Certificate signingCertificate, PrivateKey privateKey, String signatureProvider,
        ASN1ObjectIdentifier contentTypeOid, ASN1Encodable encodableContent)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertStoreException, CMSException,
        NoSuchProviderException, IOException, CertificateEncodingException, OperatorCreationException {
    byte[] subjectKeyIdentifier = X509CertificateUtil.getSubjectKeyIdentifier(signingCertificate);
    Validate.notNull(subjectKeyIdentifier, "certificate must contain SubjectKeyIdentifier extension");

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    addSignerInfo(generator, privateKey, signatureProvider, signingCertificate);
    generator.addCertificates(new JcaCertStore(Collections.singleton(signingCertificate)));

    byte[] content = Asn1Util.encode(encodableContent);
    CMSSignedData data = generator.generate(new CMSProcessableByteArray(contentTypeOid, content), true);
    return data.getEncoded();
}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilder.java

License:BSD License

private byte[] doGenerate(PrivateKey privateKey) throws CMSException, IOException, CertificateEncodingException,
        CRLException, OperatorCreationException {
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    addCertificateAndCrl(generator);/* w ww.j  a  va  2s  .co m*/
    addSignerInfo(generator, privateKey);

    CMSSignedData data = generator.generate(
            new CMSProcessableByteArray(CONTENT_TYPE, payloadContent.getBytes(Charset.forName("UTF-8"))), true);

    return data.getEncoded();
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

License:Open Source License

private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey,
        X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider)
        throws CryptoException {

    try {// w  ww . j  a v a2s .c o  m
        List<X509Certificate> certList = new ArrayList<X509Certificate>();

        Collections.addAll(certList, certificateChain);

        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC")
                .build();
        JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce())
                .setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
        if (provider != null) {
            csb.setProvider(provider);
        }
        JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);

        // remove cmsAlgorithmProtect for compatibility reasons
        SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
        final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
        sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {
            @Override
            public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
                AttributeTable ret = sAttrGen.getAttributes(parameters);
                return ret.remove(CMSAttributes.cmsAlgorithmProtect);
            }
        }, sigGen.getUnsignedAttributeTableGenerator());

        CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
        dataGen.addSignerInfoGenerator(sigGen);
        dataGen.addCertificates(new JcaCertStore(certList));

        CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);

        // now let TSA time-stamp the signature
        if (tsaUrl != null && !tsaUrl.isEmpty()) {
            signedData = addTimestamp(tsaUrl, signedData);
        }

        return signedData.getEncoded();
    } catch (Exception ex) {
        throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
    }
}