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:assinaBc.java

byte[] signPkcs7(final byte[] content, final CMSSignedDataGenerator generator) throws Exception {

    CMSTypedData cmsdata = new CMSProcessableByteArray(content);
    CMSSignedData signeddata = generator.generate(cmsdata, true);
    return signeddata.getEncoded();
}

From source file:CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation./*w w  w .  jav a  2 s  . 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. <-- TODO this method should be private
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    try {
        List<Certificate> certList = new ArrayList<Certificate>();
        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 e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:be.e_contract.mycarenet.certra.cms.CMSSigner.java

License:Open Source License

private byte[] sign(byte[] data) throws SignatureException {
    CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
    try {/* w  w  w.j  av a2 s .com*/
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(this.privateKey);
        cmsSignedDataGenerator.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build()).build(contentSigner,
                                this.certificateChain.get(0)));
        for (X509Certificate certificate : this.certificateChain) {
            cmsSignedDataGenerator.addCertificate(new X509CertificateHolder(certificate.getEncoded()));
        }
        CMSTypedData cmsTypedData = new CMSProcessableByteArray(data);
        CMSSignedData cmsSignedData = cmsSignedDataGenerator.generate(cmsTypedData, true);
        return cmsSignedData.getEncoded();
    } catch (Exception e) {
        throw new SignatureException(e);
    }
}

From source file:be.e_contract.mycarenet.etee.Sealer.java

License:Open Source License

private byte[] sign(byte[] data, boolean includeCertificate)
        throws OperatorCreationException, CertificateEncodingException, CMSException, IOException {
    CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory
            .createKey(this.authenticationPrivateKey.getEncoded());
    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privKeyParams);
    cmsSignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                    .build(contentSigner, this.authenticationCertificate));
    if (includeCertificate) {
        cmsSignedDataGenerator/*from   w ww.  ja v  a  2  s .  c o  m*/
                .addCertificate(new X509CertificateHolder(this.authenticationCertificate.getEncoded()));
    }
    CMSTypedData cmsTypedData = new CMSProcessableByteArray(data);
    CMSSignedData cmsSignedData = cmsSignedDataGenerator.generate(cmsTypedData, true);
    return cmsSignedData.getEncoded();
}

From source file:chapter9.SignedDataExample.java

/**
 *
 * @param args// w  w w.  j  ava  2 s. c om
 * @throws Exception
 */
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)), CryptoDefs.Provider.BC.getName());

    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, CryptoDefs.Provider.BC.getName());

    // Re-create
    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:cn.ieclipse.pde.signer.util.BcpSigner.java

License:Apache License

/** Sign data and write the digital signature to 'out'. */
private static void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey,
        OutputStream out)/* w w w .  j ava 2s  . com*/
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(1);
    certList.add(publicKey);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(sBouncyCastleProvider)
            .build(privateKey);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(out);
    dos.writeObject(asn1.readObject());
}

From source file:com.ackpdfbox.app.CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation./*from   ww  w . j a  v  a2  s  .  com*/
 *
 * 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.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    //TODO this method should be private
    try {
        List<Certificate> certList = new ArrayList<Certificate>();
        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 e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:com.android.apksigner.core.internal.apk.v1.V1SchemeSigner.java

License:Apache License

private static byte[] generateSignatureBlock(SignerConfig signerConfig, byte[] signatureFileBytes)
        throws InvalidKeyException, CertificateEncodingException, SignatureException {
    JcaCertStore certs = new JcaCertStore(signerConfig.certificates);
    X509Certificate signerCert = signerConfig.certificates.get(0);
    String jcaSignatureAlgorithm = getJcaSignatureAlgorithm(signerCert.getPublicKey(),
            signerConfig.signatureDigestAlgorithm);
    try {/*from   w w w .  j a  v  a2s .  c o m*/
        ContentSigner signer = new JcaContentSignerBuilder(jcaSignatureAlgorithm)
                .build(signerConfig.privateKey);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addSignerInfoGenerator(
                new SignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build(),
                        SignerInfoSignatureAlgorithmFinder.INSTANCE).setDirectSignature(true).build(signer,
                                new JcaX509CertificateHolder(signerCert)));
        gen.addCertificates(certs);

        CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(signatureFileBytes), false);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
            DEROutputStream dos = new DEROutputStream(out);
            dos.writeObject(asn1.readObject());
        }
        return out.toByteArray();
    } catch (OperatorCreationException | CMSException | IOException e) {
        throw new SignatureException("Failed to generate signature", e);
    }
}

From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java

License:Apache License

/**
 * Computes the digital signature of an array of data.
 *
 * @param data the data/*from   w ww  .j  av a 2 s  .  com*/
 * @return the digital signature
 * @throws IOException failed to read/write signature data
 * @throws CertificateEncodingException failed to sign the data
 * @throws OperatorCreationException failed to sign the data
 * @throws CMSException failed to sign the data
 */
private byte[] computePkcs7Signature(@NonNull byte[] data)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    CMSProcessableByteArray cmsData = new CMSProcessableByteArray(data);

    ArrayList<X509Certificate> certList = new ArrayList<>();
    certList.add(mCertificate);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    String signatureAlgName = mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm);
    ContentSigner shaSigner = new JcaContentSignerBuilder(signatureAlgName).build(mPrivateKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(shaSigner, mCertificate));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(cmsData, false);

    ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();

    /*
     * DEROutputStream is not closeable! OMG!
     */
    DEROutputStream dos = null;
    try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
        dos = new DEROutputStream(outputBytes);
        dos.writeObject(asn1.readObject());

        DEROutputStream toClose = dos;
        dos = null;
        toClose.close();
    } catch (IOException e) {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException ee) {
                e.addSuppressed(ee);
            }
        }
    }

    return outputBytes.toByteArray();
}

From source file:com.android.builder.signing.SignedJarApkCreator.java

License:Apache License

/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);/*  w w  w .  j a  v  a 2 s .co  m*/
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder(
            mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm)).build(mKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
        DEROutputStream dos = new DEROutputStream(mOutputJar);
        try {
            dos.writeObject(asn1.readObject());
        } finally {
            dos.flush();
            dos.close();
        }
    }
}