Example usage for org.bouncycastle.operator.jcajce JcaDigestCalculatorProviderBuilder JcaDigestCalculatorProviderBuilder

List of usage examples for org.bouncycastle.operator.jcajce JcaDigestCalculatorProviderBuilder JcaDigestCalculatorProviderBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.operator.jcajce JcaDigestCalculatorProviderBuilder JcaDigestCalculatorProviderBuilder.

Prototype

public JcaDigestCalculatorProviderBuilder() 

Source Link

Usage

From source file:de.mendelson.util.security.BCCryptoHelper.java

public boolean verifySignatureCMS(InputStream signed, Certificate cert) throws Exception {
    CMSSignedDataParser parser = new CMSSignedDataParser(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed);
    parser.getSignedContent().drain();/* w w  w . j  a v  a2s  .c om*/
    SignerInformationStore signers = parser.getSignerInfos();
    Collection signerCollection = signers.getSigners();
    Iterator it = signerCollection.iterator();
    boolean verified = false;
    X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
    SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
            .build(certHolder);
    while (it.hasNext()) {
        SignerInformation signerInformation = (SignerInformation) it.next();
        if (!verified) {
            verified = signerInformation.verify(verifier);
        }
        if (verified) {
            break;
        }
    }
    return (verified);
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

public void removeSignatureCMS(InputStream signed, OutputStream unsigned, Certificate cert) throws Exception {
    CMSSignedDataParser parser = new CMSSignedDataParser(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed);
    InputStream signedContent = parser.getSignedContent().getContentStream();
    this.copyStreams(signedContent, unsigned);
    unsigned.flush();/* w w w  . j  ava 2 s. com*/
}

From source file:ec.rubrica.ocsp.ValidadorOCSP.java

License:Open Source License

public static void check(X509Certificate issuerCert, X509Certificate x509Cert)
        throws OcspValidationException, OcspTimeoutException {
    try {//from ww w .  j  a  va  2  s .  c  o m
        BigInteger serialNumber = x509Cert.getSerialNumber();
        X509CertificateHolder holder;

        try {
            holder = new X509CertificateHolder(issuerCert.getEncoded());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        CertificateID id = new CertificateID(new JcaDigestCalculatorProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build().get(CertificateID.HASH_SHA1), holder,
                serialNumber);

        OCSPReqBuilder ocspGen = new OCSPReqBuilder();
        ocspGen.addRequest(id);
        OCSPReq ocspReq = ocspGen.build();

        // Ir al OCSP
        String ocspUrl = CertificateUtil.getOCSPURL(x509Cert);

        if (ocspUrl == null) {
            logger.info("URL de OCSP is null");
            return;
        }

        URL url;

        try {
            url = new URL(ocspUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

        HttpURLConnection con;
        OCSPResp ocspResponse;

        try {
            con = (HttpURLConnection) url.openConnection();

            con.setRequestProperty("Content-Type", "application/ocsp-request");
            con.setRequestProperty("Accept", "application/ocsp-response");
            con.setDoOutput(true);

            OutputStream out = con.getOutputStream();
            DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
            dataOut.write(ocspReq.getEncoded());

            dataOut.flush();
            dataOut.close();

            /*
             * Se parsea la respuesta y se obtiene el estado del certificado
             * retornado por el OCSP
             */
            InputStream in = (InputStream) con.getContent();
            byte[] resp = read(in); // Read the reponse
            ocspResponse = new OCSPResp(resp);
        } catch (IOException e) {
            throw new OcspTimeoutException(url);
        }

        int status = ocspResponse.getStatus();
        System.out.println("status=" + status);

        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        if (basicResponse != null) {
            SingleResp[] responses = basicResponse.getResponses();
            SingleResp response = responses[0];
            CertificateStatus certStatus = response.getCertStatus();

            if (certStatus instanceof RevokedStatus) {
                System.out.println("REVOKED");
                RevokedStatus revokedStatus = (RevokedStatus) certStatus;
                System.out.println("Reason: " + revokedStatus.getRevocationReason());
                System.out.println("Date: " + revokedStatus.getRevocationTime());

                throw new OcspValidationException(revokedStatus.getRevocationReason(),
                        revokedStatus.getRevocationTime());
            }
        }
    } catch (OCSPException e) {
        throw new RuntimeException(e);
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java

License:Apache License

private Collection<?> extractCerts(byte[] contents) throws Exception {
    JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
    builder.setProvider(CSR_SIGNER_PROVIDER);
    DigestCalculatorProvider provider = builder.build();
    CMSSignedDataParser parser = new CMSSignedDataParser(provider, contents);
    Store store = parser.getCertificates();
    return store.getMatches(certSelector);
}

From source file:eu.peppol.as2.SignedMimeMessage.java

License:EUPL

void parseSignedMessage() {
    SMIMESignedParser smimeSignedParser = null;
    try {/*from   w  ww.j  a v  a 2  s  . c  o m*/
        // MimeMessageHelper.dumpMimePartToFile("/tmp/parseSignedMessage.txt", mimeMessage);
        smimeSignedParser = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().build(),
                (MimeMultipart) mimeMessage.getContent());
    } catch (MessagingException | CMSException | IOException | OperatorCreationException e) {
        throw new IllegalStateException("Unable to create SMIMESignedParser: " + e.getMessage(), e);
    }

    Store certs = null;
    try {
        certs = smimeSignedParser.getCertificates();
    } catch (CMSException e) {
        throw new IllegalStateException("Unable to retrieve the certificates from signed message.");
    }

    //
    // SignerInfo blocks which contain the signatures
    //
    SignerInformationStore signerInfos = null;
    try {
        signerInfos = smimeSignedParser.getSignerInfos();
    } catch (CMSException e) {
        throw new IllegalStateException("Unable to get the Signer information from message. " + e.getMessage(),
                e);
    }

    Collection signers = signerInfos.getSigners();
    Iterator signersIterator = signers.iterator();

    //
    // Only a single signer, get the first and only certificate
    //
    if (signersIterator.hasNext()) {

        // Retrieves information on first and only signer
        SignerInformation signer = (SignerInformation) signersIterator.next();

        // Retrieves the collection of certificates for first and only signer
        Collection certCollection = certs.getMatches(signer.getSID());

        // Retrieve the first certificate
        Iterator certIt = certCollection.iterator();
        if (certIt.hasNext()) {
            try {
                signersX509Certificate = new JcaX509CertificateConverter()
                        .setProvider(new BouncyCastleProvider())
                        .getCertificate((X509CertificateHolder) certIt.next());
            } catch (CertificateException e) {
                throw new IllegalStateException("Unable to fetch certificate for signer. " + e.getMessage(), e);
            }
        } else {
            throw new IllegalStateException(
                    "Signers certificate was not found, unable to verify the signature");
        }

        // Verify that the signature is correct and that signersIterator was generated when the certificate was current
        try {
            if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider())
                    .build(signersX509Certificate))) {
                throw new IllegalStateException("Verification of signer failed");
            }
        } catch (CMSException e) {
            throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e);
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e);
        }

        String issuerDN = signersX509Certificate.getIssuerDN().toString();
        log.debug("Certificate issued by: " + issuerDN);

    } else {
        throw new IllegalStateException("There is no signer information available");
    }

}

From source file:fixture.pdfboxeg.CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation./*from ww  w .j ava 2s. 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.
 *
 * 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.  com*/
 */
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:mitm.common.security.cms.CMSSignedInspectorImplTest.java

License:Open Source License

@Test
public void testClearSignedParser() throws Exception {
    MimeMessage signedMessage = loadMessage("clear-signed-validcertificate.eml");

    MimeMultipart multipart = (MimeMultipart) signedMessage.getContent();

    SMIMESignedParser signedDataParser = new SMIMESignedParser(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), multipart);

    CMSSignedDataAdapter signedDataAdapter = CMSAdapterFactory.createAdapter(signedDataParser);

    assertTrue(signedDataAdapter instanceof CMSSignedDataParserAdapterImpl);

    testClearSigned(signedDataAdapter);//from  w w  w . j a  v a  2  s .c  o  m
}

From source file:mitm.common.security.cms.CMSSignedInspectorImplTest.java

License:Open Source License

@Test(expected = SignerInfoException.class)
public void testClearSignedIncorrectHashParser() throws Exception {
    MimeMessage signedMessage = loadMessage("clear-signed-hash-incorrect.eml");

    MimeMultipart multipart = (MimeMultipart) signedMessage.getContent();

    SMIMESignedParser signedData = new SMIMESignedParser(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), multipart);

    CMSSignedDataAdapter signedDataAdapter = CMSAdapterFactory.createAdapter(signedData);

    assertTrue(signedDataAdapter instanceof CMSSignedDataParserAdapterImpl);

    testClearSignedIncorrectHash(signedDataAdapter);
}

From source file:mitm.common.security.cms.CMSSignedInspectorImplTest.java

License:Open Source License

@Test
public void testClearSignedMultipleSignersParser() throws Exception {
    MimeMessage signedMessage = loadMessage("clear-signed-multiple-signers-validcertificate.eml");

    MimeMultipart multipart = (MimeMultipart) signedMessage.getContent();

    SMIMESignedParser signedData = new SMIMESignedParser(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), multipart);

    CMSSignedDataAdapter signedDataAdapter = CMSAdapterFactory.createAdapter(signedData);

    assertTrue(signedDataAdapter instanceof CMSSignedDataParserAdapterImpl);

    testClearSignedMultipleSigners(signedDataAdapter);
}