Example usage for org.bouncycastle.cert.ocsp BasicOCSPResp getProducedAt

List of usage examples for org.bouncycastle.cert.ocsp BasicOCSPResp getProducedAt

Introduction

In this page you can find the example usage for org.bouncycastle.cert.ocsp BasicOCSPResp getProducedAt.

Prototype

public Date getProducedAt() 

Source Link

Usage

From source file:org.digidoc4j.impl.bdoc.OcspNonceValidator.java

License:GNU General Public License

private BasicOCSPResp getLatestOcspResponse(List<BasicOCSPResp> ocspResponses) {
    if (ocspResponses.size() == 0) {
        return null;
    }// w ww  . jav  a2 s  .  com

    BasicOCSPResp basicOCSPResp = ocspResponses.get(0);
    Date latestDate = basicOCSPResp.getProducedAt();

    for (int i = 1; i < ocspResponses.size(); i++) {
        BasicOCSPResp ocspResponse = ocspResponses.get(i);
        if (ocspResponse.getProducedAt().after(latestDate)) {
            latestDate = ocspResponse.getProducedAt();
            basicOCSPResp = ocspResponse;
        }
    }
    return basicOCSPResp;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java

License:Open Source License

private void testVerifyHttpGetHeaders(X509Certificate caCertificate, BigInteger serialNumber) throws Exception {
    // An OCSP request, ocspTestCert is already created in earlier tests
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber));
    OCSPReq req = gen.build();/*from w  ww  .  ja  va 2  s  .c om*/
    String reqString = new String(Base64.encode(req.getEncoded(), false));
    URL url = new URL(httpReqPath + '/' + resourceOcsp + '/' + URLEncoder.encode(reqString, "UTF-8"));
    log.debug("OCSP Request: " + url.toExternalForm());
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    assertEquals(
            "Response code did not match. (Make sure you allow encoded slashes in your appserver.. add -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true in Tomcat)",
            200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/ocsp-response; charset=UTF-8"
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertEquals("Response status not the expected.", OCSPRespBuilder.SUCCESSFUL, response.getStatus());
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    // Just output the headers to stdout so we can visually inspect them if
    // something goes wrong
    Set<String> keys = con.getHeaderFields().keySet();
    for (String field : keys) {
        List<String> values = con.getHeaderFields().get(field);
        for (String value : values) {
            log.info(field + ": " + value);
        }
    }
    String eTag = con.getHeaderField("ETag");
    assertNotNull(
            "RFC 5019 6.2: No 'ETag' HTTP header present as it SHOULD. (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            eTag);
    assertTrue("ETag is messed up.",
            ("\"" + new String(
                    Hex.encode(MessageDigest.getInstance("SHA-1", "BC").digest(response.getEncoded()))) + "\"")
                            .equals(eTag));
    long date = con.getHeaderFieldDate("Date", -1);
    assertTrue("RFC 5019 6.2: No 'Date' HTTP header present as it SHOULD.", date != -1);
    long lastModified = con.getHeaderFieldDate("Last-Modified", -1);
    assertTrue("RFC 5019 6.2: No 'Last-Modified' HTTP header present as it SHOULD.", lastModified != -1);
    // assertTrue("Last-Modified is after response was sent",
    // lastModified<=date); This will not hold on JBoss AS due to the
    // caching of the Date-header
    long expires = con.getExpiration();
    assertTrue("Expires is before response was sent", expires >= date);
    assertTrue("RFC 5019 6.2: No 'Expires' HTTP header present as it SHOULD.", expires != 0);
    String cacheControl = con.getHeaderField("Cache-Control");
    assertNotNull("RFC 5019 6.2: No 'Cache-Control' HTTP header present as it SHOULD.", cacheControl);
    assertTrue("RFC 5019 6.2: No 'public' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("public"));
    assertTrue("RFC 5019 6.2: No 'no-transform' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("no-transform"));
    assertTrue("RFC 5019 6.2: No 'must-revalidate' HTTP header Cache-Control present as it SHOULD.",
            cacheControl.contains("must-revalidate"));
    Matcher matcher = Pattern.compile(".*max-age\\s*=\\s*(\\d+).*").matcher(cacheControl);
    assertTrue("RFC 5019 6.2: No 'max-age' HTTP header Cache-Control present as it SHOULD.", matcher.matches());
    int maxAge = Integer.parseInt(matcher.group(1));
    log.debug("maxAge=" + maxAge + " (expires-lastModified)/1000=" + ((expires - lastModified) / 1000));
    assertTrue(
            "thisUpdate and nextUpdate should not be the same (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)",
            expires != lastModified);
    assertTrue("RFC 5019 6.2: [maxAge] SHOULD be 'later than thisUpdate but earlier than nextUpdate'.",
            maxAge < (expires - lastModified) / 1000);
    // assertTrue("Response cannot be produced after it was sent.",
    // brep.getProducedAt().getTime() <= date); This might not hold on JBoss
    // AS due to the caching of the Date-header
    X509CertificateHolder[] chain = brep.getCerts();
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    assertNull("No nonce should be present.", brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce));
    SingleResp[] singleResps = brep.getResponses();
    assertNotNull("SingleResps should not be null.", singleResps);
    assertTrue("Expected a single SingleResp in the repsonse.", singleResps.length == 1);
    assertEquals("Serno in response does not match serno in request.",
            singleResps[0].getCertID().getSerialNumber(), serialNumber);
    assertEquals("Status is not null (null is 'good')", singleResps[0].getCertStatus(), null);
    assertTrue(
            "RFC 5019 6.2: Last-Modified SHOULD 'be the same as the thisUpdate timestamp in the request itself'",
            singleResps[0].getThisUpdate().getTime() == lastModified);
    assertTrue("RFC 5019 6.2: Expires SHOULD 'be the same as the nextUpdate timestamp in the request itself'",
            singleResps[0].getNextUpdate().getTime() == expires);
    assertTrue("Response cannot be produced before it was last modified..",
            brep.getProducedAt().getTime() >= singleResps[0].getThisUpdate().getTime());
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java

License:Open Source License

private void testNextUpdateThisUpdate(X509Certificate caCertificate, BigInteger serialNumber) throws Exception {
    // And an OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber));
    OCSPReq req = gen.build();/*from   w  ww. jav a2 s.c o m*/
    // POST the request and receive a singleResponse
    URL url = new URL(httpReqPath + '/' + resourceOcsp);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/ocsp-request");
    OutputStream os = con.getOutputStream();
    os.write(req.getEncoded());
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/ocsp-response; charset=UTF-8"
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertEquals("Response status not the expected.", 0, response.getStatus());
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    X509CertificateHolder[] chain = brep.getCerts();
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", 1, singleResps.length);
    CertificateID certId = singleResps[0].getCertID();
    assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), serialNumber);
    assertNull("Status is not null.", singleResps[0].getCertStatus());
    Date thisUpdate = singleResps[0].getThisUpdate();
    Date nextUpdate = singleResps[0].getNextUpdate();
    Date producedAt = brep.getProducedAt();
    assertNotNull("thisUpdate was not set.", thisUpdate);
    assertNotNull("nextUpdate was not set. (This test requires ocsp.untilNextUpdate to be configured.)",
            nextUpdate);
    assertNotNull("producedAt was not set.", producedAt);
    assertTrue("nextUpdate cannot be before thisUpdate.", !nextUpdate.before(thisUpdate));
    assertTrue("producedAt cannot be before thisUpdate.", !producedAt.before(thisUpdate));
}

From source file:org.xdi.oxauth.cert.validation.OCSPCertificateVerifier.java

License:MIT License

@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers,
        Date validationDate) {/*w w  w.java2  s .  c om*/
    X509Certificate issuer = issuers.get(0);
    ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate,
            ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN);

    try {
        Principal subjectX500Principal = certificate.getSubjectX500Principal();

        String ocspUrl = getOCSPUrl(certificate);
        if (ocspUrl == null) {
            log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
            return status;
        }

        log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");

        DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build()
                .get(CertificateID.HASH_SHA1);
        CertificateID certificateId = new CertificateID(digestCalculator,
                new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());

        // Generate OCSP request
        OCSPReq ocspReq = generateOCSPRequest(certificateId);

        // Get OCSP response from server
        OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
        if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            log.error("OCSP response is invalid!");
            status.setValidity(CertificateValidity.INVALID);
            return status;
        }

        boolean foundResponse = false;
        BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
        SingleResp[] singleResps = basicOCSPResp.getResponses();
        for (SingleResp singleResp : singleResps) {
            CertificateID responseCertificateId = singleResp.getCertID();
            if (!certificateId.equals(responseCertificateId)) {
                continue;
            }

            foundResponse = true;

            log.debug("OCSP validationDate: " + validationDate);
            log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
            log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());

            status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());

            Object certStatus = singleResp.getCertStatus();
            if (certStatus == CertificateStatus.GOOD) {
                log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
                status.setValidity(CertificateValidity.VALID);
            } else {
                if (singleResp.getCertStatus() instanceof RevokedStatus) {
                    log.warn("OCSP status is revoked for: " + subjectX500Principal);
                    if (validationDate
                            .before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
                        log.warn("OCSP revocation time after the validation date, the certificate '"
                                + subjectX500Principal + "' was valid at " + validationDate);
                        status.setValidity(CertificateValidity.VALID);
                    } else {
                        Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
                        log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since "
                                + revocationDate);
                        status.setRevocationDate(revocationDate);
                        status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
                        status.setValidity(CertificateValidity.REVOKED);
                    }
                }
            }
        }

        if (!foundResponse) {
            log.error("There is no matching OCSP response entries");
        }
    } catch (Exception ex) {
        log.error("OCSP exception: ", ex);
    }

    return status;
}