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.neociclo.odetteftp.util.EnvelopingUtil.java

License:Apache License

/**
 * Generate a SignedData object using SHA-1 digest.
 * //from   w w  w. j a v  a 2 s .co  m
 * @param content
 *            the data to be signed
 * @param cipherSuite
 * @param cert
 *            private certificate used in conjunction with private key
 * @param key
 *            private key used to produce the signed-data object
 * @return the encoded signed-data object
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 * @throws IOException
 */
public static byte[] createSignedData(byte[] content, CipherSuite cipherSuite, X509Certificate cert,
        PrivateKey key) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, IOException {

    installBouncyCastleProviderIfNecessary();

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

    gen.addSigner(key, cert, asDigestAlgorithm(cipherSuite));

    // create the signed-data object
    CMSProcessable data = new CMSProcessableByteArray(content);
    CMSSignedData signed = gen.generate(data, BC_PROVIDER);

    return signed.getEncoded();
}

From source file:org.primeoservices.cfpass.PassUtils.java

License:Apache License

public static void createSignature(final String directoryPath, final String keyStoreFilePath,
        final String keyStorePassword) throws Exception {
    // Add BC provider
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }//from w w  w.j  ava 2s  .c  om

    // Check directory
    final File directory = new File(directoryPath);
    if (directory.exists() && !directory.isDirectory()) {
        throw new IllegalArgumentException(directoryPath + " is not a directory");
    }

    // Check manifest file
    final File manifest = new File(directory, "manifest.json");
    if (manifest.exists() && !manifest.isFile()) {
        throw new IllegalArgumentException("File manifest.json doesn't exists");
    }

    // Check key store
    final File keyStore = new File(keyStoreFilePath);
    if (keyStore.exists() && !keyStore.isFile()) {
        throw new IllegalArgumentException("Keystore not found");
    }

    // Load key store
    final FileInputStream clientStoreIn = new FileInputStream(keyStore);
    final KeyStore clientStore = KeyStore.getInstance("PKCS12");
    clientStore.load(clientStoreIn, keyStorePassword.toCharArray());

    // Extract private key and certificate
    final Enumeration<String> aliases = clientStore.aliases();
    String alias = "";
    while (aliases.hasMoreElements()) {
        alias = aliases.nextElement();
        if (clientStore.isKeyEntry(alias)) {
            break;
        }
    }
    final PrivateKey key = (PrivateKey) clientStore.getKey(alias, keyStorePassword.toCharArray());
    final X509Certificate cert = (X509Certificate) clientStore.getCertificate(alias);

    // Load Apple certificate
    final InputStream appleCertIn = PassUtils.class.getResourceAsStream("/AppleWWDRCA.cer");
    final CertificateFactory appleCertFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate appleCert = (X509Certificate) appleCertFactory.generateCertificate(appleCertIn);

    // Signature
    final ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(key);

    final ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
    final Attribute signingAttribute = new Attribute(CMSAttributes.signingTime,
            new DERSet(new DERUTCTime(new Date())));
    signedAttributes.add(signingAttribute);
    // Create the signing table
    final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
    // Create the table table generator that will added to the Signer builder
    final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
            signedAttributesTable);

    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(appleCert);
    certList.add(cert);
    Store certs = new JcaCertStore(certList);

    final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                    .setSignedAttributeGenerator(signedAttributeGenerator).build(sha1Signer, cert));
    generator.addCertificates(certs);

    final CMSSignedData sigData = generator.generate(new CMSProcessableFile(manifest), false);
    final byte[] signedDataBytes = sigData.getEncoded();

    // Write signature
    final File signatureFile = new File(directoryPath, "signature");
    final FileOutputStream signatureOutputStream = new FileOutputStream(signatureFile);
    signatureOutputStream.write(signedDataBytes);
    signatureOutputStream.close();
}

From source file:org.roda.common.certification.SignatureUtility.java

/**
 * Sign the file/*from  ww w  .j a  v  a  2s  .co m*/
 * 
 * @param file
 * 
 * @return an array of bytes with the signature
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 */
public byte[] sign(File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, CMSException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData data = signGenerator.generate(cmsFile);
    return data.getEncoded();
}

From source file:org.roda.core.plugins.plugins.characterization.SignatureUtility.java

/**
 * Sign the file/*from   w  w  w  .  j  a  va  2s  . co m*/
 * 
 * @param file
 * 
 * @return an array of bytes with the signature
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 */
public byte[] sign(File file) throws CMSException, IOException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData data = signGenerator.generate(cmsFile);
    return data.getEncoded();
}

From source file:org.signserver.module.cmssigner.CMSSigner.java

License:Open Source License

@Override
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext)
        throws IllegalRequestException, org.signserver.common.CryptoTokenOfflineException, SignServerException {

    ProcessResponse signResponse;//from  w w w  .  j av  a 2  s .  c o  m

    // Check that the request contains a valid GenericSignRequest object
    // with a byte[].
    if (!(signRequest instanceof GenericSignRequest)) {
        throw new IllegalRequestException("Recieved request wasn't a expected GenericSignRequest.");
    }

    final ISignRequest sReq = (ISignRequest) signRequest;

    if (!(sReq.getRequestData() instanceof byte[])) {
        throw new IllegalRequestException("Recieved request data wasn't a expected byte[].");
    }

    if (!configErrors.isEmpty()) {
        throw new SignServerException("Worker is misconfigured");
    }

    byte[] data = (byte[]) sReq.getRequestData();
    final String archiveId = createArchiveId(data, (String) requestContext.get(RequestContext.TRANSACTION_ID));

    ICryptoInstance crypto = null;
    try {
        crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext);
        final X509Certificate cert = (X509Certificate) getSigningCertificate(crypto);
        if (LOG.isDebugEnabled()) {
            LOG.debug("SigningCert: " + cert);
        }

        // Get certificate chain and signer certificate
        final List<Certificate> certs = this.getSigningCertificateChain(crypto);
        if (certs == null) {
            throw new IllegalArgumentException("Null certificate chain. This signer needs a certificate.");
        }

        final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        final String sigAlg = signatureAlgorithm == null ? getDefaultSignatureAlgorithm(crypto.getPublicKey())
                : signatureAlgorithm;
        final ContentSigner contentSigner = new JcaContentSignerBuilder(sigAlg)
                .setProvider(crypto.getProvider()).build(crypto.getPrivateKey());
        generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, cert));

        generator.addCertificates(new JcaCertStore(includedCertificates(certs)));
        final CMSTypedData content = new CMSProcessableByteArray(data);

        // Should the content be detached or not
        final boolean detached;
        final Boolean detachedRequested = getDetachedSignatureRequest(requestContext);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Detached signature configured: " + detachedSignature + "\n"
                    + "Detached signature requested: " + detachedRequested);
        }
        if (detachedRequested == null) {
            detached = detachedSignature;
        } else {
            if (detachedRequested) {
                if (!detachedSignature && !allowDetachedSignatureOverride) {
                    throw new IllegalRequestException("Detached signature requested but not allowed");
                }
            } else {
                if (detachedSignature && !allowDetachedSignatureOverride) {
                    throw new IllegalRequestException("Non detached signature requested but not allowed");
                }
            }
            detached = detachedRequested;
        }

        final CMSSignedData signedData = generator.generate(content, !detached);

        final byte[] signedbytes = signedData.getEncoded();
        final Collection<? extends Archivable> archivables = Arrays
                .asList(new DefaultArchivable(Archivable.TYPE_RESPONSE, CONTENT_TYPE, signedbytes, archiveId));

        if (signRequest instanceof GenericServletRequest) {
            signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables, CONTENT_TYPE);
        } else {
            signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables);
        }

        // Suggest new file name
        final Object fileNameOriginal = requestContext.get(RequestContext.FILENAME);
        if (fileNameOriginal instanceof String) {
            requestContext.put(RequestContext.RESPONSE_FILENAME, fileNameOriginal + ".p7s");
        }

        // The client can be charged for the request
        requestContext.setRequestFulfilledByWorker(true);

        return signResponse;
    } catch (OperatorCreationException ex) {
        LOG.error("Error initializing signer", ex);
        throw new SignServerException("Error initializing signer", ex);
    } catch (CertificateEncodingException ex) {
        LOG.error("Error constructing cert store", ex);
        throw new SignServerException("Error constructing cert store", ex);
    } catch (CMSException ex) {
        LOG.error("Error constructing CMS", ex);
        throw new SignServerException("Error constructing CMS", ex);
    } catch (IOException ex) {
        LOG.error("Error constructing CMS", ex);
        throw new SignServerException("Error constructing CMS", ex);
    } finally {
        releaseCryptoInstance(crypto, requestContext);
    }
}

From source file:org.signserver.module.renewal.worker.MockCA.java

License:Open Source License

public byte[] createPKCS7(final X509Certificate cert, final boolean includeChain) {

    final Collection<?> certs = includeChain ? Arrays.asList(cert, caCertificate) : Arrays.asList(cert);

    try {//from w w  w.j a va  2  s. c o m
        CMSProcessable msg = new CMSProcessableByteArray("EJBCA".getBytes());
        CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs),
                "BC");
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        gen.addSigner(keyPair.getPrivate(), caCertificate, CMSSignedGenerator.DIGEST_SHA1);
        gen.addCertificatesAndCRLs(certStore);
        CMSSignedData s = gen.generate(msg, true, "BC");

        return s.getEncoded();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.signserver.module.tsa.MSAuthCodeTimeStampSigner.java

License:Open Source License

/**
 * The main method performing the actual timestamp operation.
 * Expects the signRequest to be a GenericSignRequest contining a
 * TimeStampRequest//from  www. j a va 2  s . c  o  m
 *
 * @param signRequest
 * @param requestContext
 * @return the sign response
 * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext)
 */
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {

    // Log values
    final LogMap logMap = LogMap.getInstance(requestContext);

    try {
        final ISignRequest sReq = (ISignRequest) signRequest;
        final byte[] requestbytes = (byte[]) sReq.getRequestData();

        if (requestbytes == null || requestbytes.length == 0) {
            LOG.error("Request must contain data");
            throw new IllegalRequestException("Request must contain data");
        }

        // Check that the request contains a valid TimeStampRequest object.
        if (!(signRequest instanceof GenericSignRequest)) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request wasn't an expected GenericSignRequest. ");
            LOG.error("Received request wasn't an expected GenericSignRequest");
            throw exception;
        }

        if (!((sReq.getRequestData() instanceof TimeStampRequest)
                || (sReq.getRequestData() instanceof byte[]))) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request data wasn't an expected TimeStampRequest. ");
            LOG.error("Received request data wasn't an expected TimeStampRequest");
            throw exception;
        }

        if (!validChain) {
            LOG.error("Certificate chain not correctly configured");
            throw new CryptoTokenOfflineException("Certificate chain not correctly configured");
        }

        ASN1Primitive asn1obj = ASN1Primitive.fromByteArray(Base64.decode(requestbytes));
        ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj);

        if (asn1seq.size() != 2) {
            LOG.error("Wrong structure, should be an ASN1Sequence with 2 elements");
            throw new IllegalRequestException("Wrong structure, should be an ASN1Sequence with 2 elements");
        }

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1seq.getObjectAt(0));
        ASN1Sequence asn1seq1 = ASN1Sequence.getInstance(asn1seq.getObjectAt(1));

        final ContentInfo ci = new ContentInfo(asn1seq1);

        if (!oid.getId().equals(msOID)) {
            LOG.error("Invalid OID in request: " + oid.getId());
            throw new IllegalRequestException("Invalid OID in request: " + oid.getId());
        }

        if (asn1seq1.size() != 2) {
            LOG.error(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
            throw new IllegalRequestException(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
        }

        oid = ASN1ObjectIdentifier.getInstance(asn1seq1.getObjectAt(0));

        if (!oid.getId().equals(dataOID)) {
            throw new IllegalRequestException("Wrong contentType OID: " + oid.getId());
        }

        ASN1TaggedObject tag = ASN1TaggedObject.getInstance(asn1seq1.getObjectAt(1));

        if (tag.getTagNo() != 0) {
            throw new IllegalRequestException("Wrong tag no (should be 0): " + tag.getTagNo());
        }

        ASN1OctetString octets = ASN1OctetString.getInstance(tag.getObject());
        byte[] content = octets.getOctets();

        final ITimeSource timeSrc;
        final Date date;
        byte[] der;
        ICryptoInstance crypto = null;
        try {
            crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext);

            // get signing cert certificate chain and private key
            List<Certificate> certList = this.getSigningCertificateChain(crypto);
            if (certList == null) {
                throw new SignServerException("Null certificate chain. This signer needs a certificate.");
            }

            Certificate[] certs = (Certificate[]) certList.toArray(new Certificate[certList.size()]);

            // Sign
            X509Certificate x509cert = (X509Certificate) certs[0];

            timeSrc = getTimeSource();
            if (LOG.isDebugEnabled()) {
                LOG.debug("TimeSource: " + timeSrc.getClass().getName());
            }
            date = timeSrc.getGenTime();

            if (date == null) {
                throw new ServiceUnavailableException("Time source is not available");
            }

            ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
            signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(date))));

            if (includeSigningCertificateAttribute) {
                try {
                    final DERInteger serial = new DERInteger(x509cert.getSerialNumber());
                    final X509CertificateHolder certHolder = new X509CertificateHolder(x509cert.getEncoded());
                    final X500Name issuer = certHolder.getIssuer();
                    final GeneralName name = new GeneralName(issuer);
                    final GeneralNames names = new GeneralNames(name);
                    final IssuerSerial is = new IssuerSerial(names, ASN1Integer.getInstance(serial));

                    final ESSCertID essCertid = new ESSCertID(
                            MessageDigest.getInstance("SHA-1").digest(x509cert.getEncoded()), is);
                    signedAttributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate,
                            new DERSet(new SigningCertificate(essCertid))));
                } catch (NoSuchAlgorithmException e) {
                    LOG.error("Can't find SHA-1 implementation: " + e.getMessage());
                    throw new SignServerException("Can't find SHA-1 implementation", e);
                }
            }

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

            final String provider = cryptoToken.getProvider(ICryptoToken.PROVIDERUSAGE_SIGN);

            SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(
                    new JcaDigestCalculatorProviderBuilder().setProvider("BC").build());
            signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator);

            JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(signatureAlgo);
            contentSigner.setProvider(provider);

            final SignerInfoGenerator sig = signerInfoBuilder.build(contentSigner.build(crypto.getPrivateKey()),
                    new X509CertificateHolder(x509cert.getEncoded()));

            JcaCertStore cs = new JcaCertStore(certList);

            CMSTypedData cmspba = new CMSProcessableByteArray(content);
            CMSSignedData cmssd = MSAuthCodeCMSUtils.generate(cmspba, true, Arrays.asList(sig),
                    MSAuthCodeCMSUtils.getCertificatesFromStore(cs), Collections.emptyList(), ci);

            der = ASN1Primitive.fromByteArray(cmssd.getEncoded()).getEncoded();
        } finally {
            releaseCryptoInstance(crypto, requestContext);
        }

        // Log values
        logMap.put(ITimeStampLogger.LOG_TSA_TIME, String.valueOf(date.getTime()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName());

        final String archiveId = createArchiveId(requestbytes,
                (String) requestContext.get(RequestContext.TRANSACTION_ID));

        final GenericSignResponse signResponse;
        byte[] signedbytes = Base64.encode(der, false);

        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED, new String(signedbytes));

        final Collection<? extends Archivable> archivables = Arrays.asList(
                new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId),
                new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId));

        if (signRequest instanceof GenericServletRequest) {
            signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables,
                    RESPONSE_CONTENT_TYPE);
        } else {
            signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables);
        }

        // The client can be charged for the request
        requestContext.setRequestFulfilledByWorker(true);

        return signResponse;

    } catch (IOException e) {
        final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(),
                e);
        LOG.error("IOException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CMSException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CMSException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (OperatorCreationException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("OperatorCreationException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CertificateEncodingException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CertificateEncodingException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (ArrayIndexOutOfBoundsException e) {
        // the BC base64 decoder doesn't check the the base64 input length...
        final IllegalRequestException exception = new IllegalRequestException(
                "ArrayIndexOutOfBoundsException: " + e.getMessage(), e);
        LOG.error("ArrayIndexOutOfBoundsException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    }
}

From source file:org.structr.function.CreateJarFileFunction.java

License:Open Source License

private void writeSignatureBlock(final JarOutputStream jos, final String algorithm, final CMSTypedData data,
        final X509Certificate publicKey, final PrivateKey privateKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    final List<X509Certificate> certList = new ArrayList<>();
    certList.add(publicKey);/*w  w w .  j a va  2s. co  m*/

    final JcaCertStore certs = new JcaCertStore(certList);
    final CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    final ContentSigner signer = new JcaContentSignerBuilder(algorithm + "with" + privateKey.getAlgorithm())
            .build(privateKey);
    final SignerInfoGenerator infoGenerator = new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(signer, publicKey);

    gen.addSignerInfoGenerator(infoGenerator);
    gen.addCertificates(certs);

    final CMSSignedData sigData = gen.generate(data, false);
    final ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    final DEROutputStream dos = new DEROutputStream(jos);

    dos.writeObject(asn1.readObject());
}

From source file:org.structr.jar.CreateJarFileFunction.java

License:Open Source License

private void writeSignatureBlock(final JarOutputStream jos, final String algorithm, final CMSTypedData data,
        final X509Certificate publicKey, final PrivateKey privateKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    final List<X509Certificate> certList = new ArrayList<>();
    certList.add(publicKey);//from  w  w  w. j av a 2s  . c o m

    final JcaCertStore certs = new JcaCertStore(certList);
    final CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    final ContentSigner signer = new JcaContentSignerBuilder(algorithm + "with" + privateKey.getAlgorithm())
            .build(privateKey);
    final SignerInfoGenerator infoGenerator = new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(signer, publicKey);

    gen.addSignerInfoGenerator(infoGenerator);
    gen.addCertificates(certs);

    final CMSSignedData sigData = gen.generate(data, false);
    final ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    final DEROutputStream dos = new DEROutputStream(jos);
    final ASN1Primitive obj = asn1.readObject();

    dos.writeObject(obj);
}

From source file:org.structr.jar.SignedJarBuilder.java

License:Open Source License

/**
 * Write the certificate file with a digital signature.
 *//*from  w  w  w  . j  a  v  a  2s . c o  m*/
private void writeSignatureBlock(final JarOutputStream jos, final CMSTypedData data,
        final X509Certificate publicKey, final PrivateKey privateKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    final List<X509Certificate> certList = new ArrayList<>();
    certList.add(publicKey);

    final JcaCertStore certs = new JcaCertStore(certList);
    final CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    final ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm())
            .build(privateKey);

    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);

    final CMSSignedData sigData = gen.generate(data, false);
    final ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    final DEROutputStream dos = new DEROutputStream(jos);

    dos.writeObject(asn1.readObject());
}