Example usage for org.bouncycastle.cert.jcajce JcaCertStore JcaCertStore

List of usage examples for org.bouncycastle.cert.jcajce JcaCertStore JcaCertStore

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaCertStore JcaCertStore.

Prototype

public JcaCertStore(Collection collection) throws CertificateEncodingException 

Source Link

Document

Basic constructor.

Usage

From source file:assinaBc.java

CMSSignedDataGenerator setUpProvider(final KeyStore keystore) throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    Certificate[] certchain = (Certificate[]) keystore.getCertificateChain(KEY_ALIAS_IN_KEYSTORE);

    final List<Certificate> certlist = new ArrayList<>();

    for (int i = 0, length = certchain == null ? 0 : certchain.length; i < length; i++) {
        certlist.add(certchain[i]);//from   w w  w. jav  a2s.  c  om
    }
    Store certstore = new JcaCertStore(certlist);

    Certificate cert = keystore.getCertificate(KEY_ALIAS_IN_KEYSTORE);

    ContentSigner signer = new JcaContentSignerBuilder(SIGNATUREALGO).setProvider("BC")
            .build((PrivateKey) (keystore.getKey(KEY_ALIAS_IN_KEYSTORE, KEYSTORE_PASSWORD.toCharArray())));

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

    generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(signer,
                    (X509Certificate) cert));

    generator.addCertificates(certstore);

    return generator;
}

From source file:CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation./*w w w .  j  a v  a2s  .  c o 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.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static TimeStampToken createTimeStampToken(PrivateKey privateKey, List<X509Certificate> certificateChain)
        throws Exception {

    Store certs = new JcaCertStore(certificateChain);

    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();
    requestGen.setCertReq(true);//from   w w  w  .  j  a  v  a2  s  .  c  o  m
    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));

    TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
            new JcaSimpleSignerInfoGeneratorBuilder().build("SHA1withRSA", privateKey, certificateChain.get(0)),
            new JcaDigestCalculatorProviderBuilder().build().get(
                    new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)),
            new ASN1ObjectIdentifier("1.2"));

    tsTokenGen.addCertificates(certs);
    return tsTokenGen.generate(request, BigInteger.ONE, new Date());
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static Store buscarCrlParaCadaCertificado(Store certs) throws CertStoreException, Exception {
    X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certs.getMatches(null));

    List certList = new ArrayList();
    for (X509Certificate cert : cadeiaTotal)
        certList.add(cert);/*w  w  w.j ava2 s .co m*/
    for (X509CRLObject crl : (Collection<X509CRLObject>) X509ChainValidator.getCRLs(cadeiaTotal))
        certList.add(crl);
    // certList.add(ASN1Object.fromByteArray(crl.getEncoded()));

    return new JcaCertStore(certList);
}

From source file:br.ufpb.dicomflow.integrationAPI.mail.AbstractMailSender.java

License:Open Source License

private Message signAndEcrypt(Message message, X509Certificate signCert, X509Certificate encryptCert,
        PrivateKey privateKey) throws Exception {
    MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();

    mailcap.addMailcap(//from   w w w.jav a 2  s . c om
            "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
    mailcap.addMailcap(
            "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
    mailcap.addMailcap(
            "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
    mailcap.addMailcap(
            "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
    mailcap.addMailcap(
            "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");

    CommandMap.setDefaultCommandMap(mailcap);

    /* Create the Signer - SMIMESignedGenerator */
    SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    ASN1EncodableVector attributes = new ASN1EncodableVector();
    attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
            new IssuerAndSerialNumber(new X500Name(((X509Certificate) signCert).getIssuerDN().getName()),
                    ((X509Certificate) signCert).getSerialNumber())));
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder()
            .setSignedAttributeGenerator(new AttributeTable(attributes))
            .build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey,
                    signCert));

    /* Add the list of certs to the generator */
    List certList = new ArrayList();
    certList.add(signCert);
    Store certs = new JcaCertStore(certList);
    signer.addCertificates(certs);

    /* Sign the message */
    MimeMultipart mm = signer.generate((MimeMessage) message);
    MimeMessage signedMessage = new MimeMessage(message.getSession());

    /* Set all original MIME headers in the signed message */
    Enumeration headers = ((MimeMessage) message).getAllHeaderLines();
    while (headers.hasMoreElements()) {
        signedMessage.addHeaderLine((String) headers.nextElement());
    }

    /* Set the content of the signed message */
    signedMessage.setContent(mm);
    signedMessage.saveChanges();

    /* Create the encrypter - SMIMEEnvelopedGenerator */
    SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
    encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(encryptCert));

    /* Encrypt the message */
    MimeBodyPart encryptedPart = encrypter.generate(signedMessage,
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).build());

    /*
     * Create a new MimeMessage that contains the encrypted and signed
     * content
     */
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    encryptedPart.writeTo(out);

    MimeMessage encryptedMessage = new MimeMessage(message.getSession(),
            new ByteArrayInputStream(out.toByteArray()));

    /* Set all original MIME headers in the encrypted message */
    headers = ((MimeMessage) message).getAllHeaderLines();
    while (headers.hasMoreElements()) {
        String headerLine = (String) headers.nextElement();
        /*
         * Make sure not to override any content-* headers from the
         * original message
         */
        if (!Strings.toLowerCase(headerLine).startsWith("content-")) {
            encryptedMessage.addHeaderLine(headerLine);
        }
    }

    return encryptedMessage;

}

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  ww.j  av  a  2s  .  c  om
        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.aaasec.sigserv.csspsupport.pdfbox.CreateSignature.java

License:EUPL

/**
 * <p>//from  w w w.j a va  2s  .  c  o  m
 * SignatureInterface implementation.
 * </p>
 *
 * <p>
 * This method will be called from inside of the pdfbox and create the pkcs7
 * signature. The given InputStream contains the bytes that are provided by
 * the byte range.
 * </p>
 *
 * <p>
 * This method is for internal use only.
 * </p>
 *
 * <p>
 * Here the user should use his favorite cryptographic library and implement
 * a pkcs7 signature creation.
 * </p>
 */
public byte[] sign(InputStream content) throws SignatureException, IOException {
    List<Certificate> certList = Arrays.asList(cert);
    CMSProcessableInputStream input = new CMSProcessableInputStream(content);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    CertStore certStore = null;
    try {
        Store certs = new JcaCertStore(certList);
        certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), provider);

        gen.addSigner(privKey, (X509Certificate) certList.get(0), CMSSignedGenerator.DIGEST_SHA256);

        gen.addCertificates(certs);
        CMSSignedData signedData = gen.generate(input, false, provider);
        model.setSignedData(signedData);

        PdfBoxSigUtil.parseSignedData(model);
        return signedData.getEncoded();
    } catch (Exception e) {
        // should be handled
        System.err.println("Error while creating pkcs7 signature.");
        e.printStackTrace();
    }
    throw new RuntimeException("Problem while preparing signature");
}

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

License:Apache License

/**
 * SignatureInterface implementation.//from  ww w .  j av 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 {//  www .  j  a  v  a  2  s .  co 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//ww w  .  j  a va 2s . c  om
 * @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();
}