Example usage for org.bouncycastle.cert.ocsp RevokedStatus getRevocationReason

List of usage examples for org.bouncycastle.cert.ocsp RevokedStatus getRevocationReason

Introduction

In this page you can find the example usage for org.bouncycastle.cert.ocsp RevokedStatus getRevocationReason.

Prototype

public int getRevocationReason() 

Source Link

Document

return the revocation reason.

Usage

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 .ja va  2s  .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:eu.europa.ec.markt.dss.validation102853.OCSPCertificateVerifier.java

License:Open Source License

@Override
public RevocationToken check(final CertificateToken toCheckToken) {

    if (ocspSource == null) {

        LOG.warn("OCSPSource null");
        toCheckToken.extraInfo().infoOCSPSourceIsNull();
        return null;
    }/*from ww  w .  j a va  2  s .  co m*/
    try {

        final X509Certificate issuerCert = toCheckToken.getIssuerToken().getCertificate();
        final X509Certificate toCheckCert = toCheckToken.getCertificate();
        final BasicOCSPResp basicOCSPResp = ocspSource.getOCSPResponse(toCheckCert, issuerCert);
        if (basicOCSPResp == null) {

            String uri = "";
            if (ocspSource instanceof OnlineOCSPSource) {

                uri = ((OnlineOCSPSource) ocspSource).getAccessLocation(toCheckCert);
                toCheckToken.extraInfo().infoNoOCSPResponse(uri);
            }

            if (LOG.isInfoEnabled()) {
                LOG.info("OCSP response not found for " + toCheckToken.getDSSIdAsString() + " [" + uri + "]");
            }
            return null;
        }
        final BigInteger serialNumber = toCheckCert.getSerialNumber();
        final X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(
                DSSUtils.getEncoded(issuerCert));
        final DigestCalculator digestCalculator = DSSUtils.getSHA1DigestCalculator();
        final CertificateID certificateId = new CertificateID(digestCalculator, x509CertificateHolder,
                serialNumber);
        final SingleResp[] singleResps = basicOCSPResp.getResponses();
        for (final SingleResp singleResp : singleResps) {
            if (!DSSRevocationUtils.matches(certificateId, singleResp)) {

                continue;
            }
            if (LOG.isDebugEnabled()) {

                LOG.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
                LOG.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());
            }
            final OCSPToken ocspToken = new OCSPToken(basicOCSPResp, validationCertPool);
            if (ocspSource instanceof OnlineOCSPSource) {

                ocspToken.setSourceURI(((OnlineOCSPSource) ocspSource).getAccessLocation(toCheckCert));
            }

            ocspToken.setIssuingTime(basicOCSPResp.getProducedAt());
            toCheckToken.setRevocationToken(ocspToken);
            final Object certStatus = singleResp.getCertStatus();
            if (certStatus == null) {

                if (LOG.isInfoEnabled()) {
                    LOG.info("OCSP OK for: " + toCheckToken.getDSSIdAsString());
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("CertificateToken:\n{}", toCheckToken.toString());
                    }
                }
                ocspToken.setStatus(true);
            } else {

                if (LOG.isInfoEnabled()) {
                    LOG.info("OCSP certificate status: " + certStatus.getClass().getName());
                }
                if (certStatus instanceof RevokedStatus) {

                    if (LOG.isInfoEnabled()) {
                        LOG.info("OCSP status revoked");
                    }
                    final RevokedStatus revokedStatus = (RevokedStatus) certStatus;
                    ocspToken.setStatus(false);
                    ocspToken.setRevocationDate(revokedStatus.getRevocationTime());
                    final int reasonId = revokedStatus.getRevocationReason();
                    final CRLReason crlReason = CRLReason.lookup(reasonId);
                    ocspToken.setReason(crlReason.toString());
                } else if (certStatus instanceof UnknownStatus) {

                    if (LOG.isInfoEnabled()) {
                        LOG.info("OCSP status unknown");
                    }
                    ocspToken.setReason("OCSP status: unknown");
                }
            }
            return ocspToken;
        }
    } catch (DSSException e) {

        LOG.error("OCSP DSS Exception: " + e.getMessage(), e);
        toCheckToken.extraInfo().infoOCSPException(e);
        return null;
    } catch (OCSPException e) {

        LOG.error("OCSP Exception: " + e.getMessage());
        toCheckToken.extraInfo().infoOCSPException(e);
        throw new DSSException(e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
    if (LOG.isInfoEnabled()) {
        LOG.debug("No matching OCSP response entry");
    }
    toCheckToken.extraInfo().infoNoOCSPResponse(null);
    return null;
}

From source file:eu.europa.esig.dss.x509.ocsp.OCSPToken.java

License:Open Source License

private void extractStatusInfo(final CertificateStatus certStatus) {
    if (certStatus == null) {
        status = true;/*  ww  w  .j a  v a 2 s . c o  m*/
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("OCSP certificate status: " + certStatus.getClass().getSimpleName());
    }
    if (certStatus instanceof RevokedStatus) {
        if (logger.isInfoEnabled()) {
            logger.info("OCSP status revoked");
        }
        final RevokedStatus revokedStatus = (RevokedStatus) certStatus;
        status = false;
        revocationDate = revokedStatus.getRevocationTime();
        int reasonId = 0; // unspecified
        if (revokedStatus.hasRevocationReason()) {
            reasonId = revokedStatus.getRevocationReason();
        }
        reason = CRLReasonEnum.fromInt(reasonId).name();
    } else if (certStatus instanceof UnknownStatus) {
        if (logger.isInfoEnabled()) {
            logger.info("OCSP status unknown");
        }
        reason = "OCSP status: unknown";
    }
}

From source file:eu.europa.esig.dss.x509.OCSPToken.java

License:Open Source License

private int getRevocationReasonId(RevokedStatus revokedStatus) {
    try {/*from  w w w .j  a va 2s .c om*/
        return revokedStatus.getRevocationReason();
    } catch (IllegalStateException e) {
        logger.warn("OCSP Revocation reason is not available: " + e.getMessage());
        return 0; //Zero means 'unspecified'
    }
}

From source file:net.maritimecloud.pki.OCSPVerifier.java

License:Apache License

/**
 * Verifies a certificate against a its issuer using OCSP. In most cases you should probably use
 * {@link CertificateHandler#verifyCertificateChain(X509Certificate, KeyStore) verifyCertificateChain}
 * instead to verify the complete chain.
 *
 * @param cert Certificate to validate/*from   w w w . j a  v  a  2 s  . co m*/
 * @param issuerCert The issuer certificate
 * @return
 * @throws IOException
 * @throws OCSPValidationException
 */
public static RevocationInfo verifyCertificateOCSP(X509Certificate cert, X509Certificate issuerCert)
        throws IOException, OCSPValidationException {
    OCSPClient ocspClient = new OCSPClient(issuerCert, cert);
    RevocationInfo info = new RevocationInfo();
    if (ocspClient.checkOCSP()) {
        info.setStatus(ocspClient.getCertificateStatus());
    } else {
        info.setStatus(ocspClient.getCertificateStatus());
        if (ocspClient.getRevokedStatus().isPresent()) {
            RevokedStatus rs = ocspClient.getRevokedStatus().get();
            info.setRevokeReason(CRLReason.values()[rs.getRevocationReason()]);
            info.setRevokedAt(rs.getRevocationTime());
        }
    }
    return info;
}

From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java

License:Open Source License

/**
 * Tests creating an OCSP response using the ocspCertificate, revoking it.
 * Tests using both SHA1 and SHA256 CertID.
 *///from ww  w . j  ava2s.c o  m
@Test
public void testGetOcspResponseWithRevokedCertificate() throws Exception {
    ocspResponseGeneratorTestSession.reloadOcspSigningCache();

    // An OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate,
            ocspCertificate.getSerialNumber()));
    Extension[] extensions = new Extension[1];
    extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));

    OCSPReq req = gen.build();

    // Now revoke the ocspCertificate
    certificateStoreSession.setRevokeStatus(internalAdmin, ocspCertificate,
            RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, null);
    final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber();
    // Create the transaction logger for this transaction.
    TransactionLogger transactionLogger = new TransactionLogger(localTransactionId,
            GuidHolder.INSTANCE.getGlobalUid(), "");
    // Create the audit logger for this transaction.
    AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), "");
    byte[] responseBytes = ocspResponseGeneratorSession
            .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger)
            .getOcspResponse();
    assertNotNull("OCSP responder replied null", responseBytes);

    OCSPResp response = new OCSPResp(responseBytes);
    assertEquals("Response status not zero.", response.getStatus(), 0);
    BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject();
    assertTrue("OCSP response was not signed correctly.", basicOcspResponse
            .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey())));
    SingleResp[] singleResponses = basicOcspResponse.getResponses();
    assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length);
    assertEquals("Response cert did not match up with request cert", ocspCertificate.getSerialNumber(),
            singleResponses[0].getCertID().getSerialNumber());
    Object status = singleResponses[0].getCertStatus();
    assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus);
    RevokedStatus rev = (RevokedStatus) status;
    assertTrue("Status does not have reason", rev.hasRevocationReason());
    int reason = rev.getRevocationReason();
    assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);

    // Do the same test but using SHA256 as hash algorithm for CertID
    gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(
            new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)),
            caCertificate, ocspCertificate.getSerialNumber()));
    extensions = new Extension[1];
    extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    req = gen.build();
    responseBytes = ocspResponseGeneratorSession
            .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger)
            .getOcspResponse();
    response = new OCSPResp(responseBytes);
    assertEquals("Response status not zero.", response.getStatus(), 0);
    basicOcspResponse = (BasicOCSPResp) response.getResponseObject();
    assertTrue("OCSP response was not signed correctly.", basicOcspResponse
            .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey())));
    singleResponses = basicOcspResponse.getResponses();
    assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length);
    assertEquals("Response cert did not match up with request cert", ocspCertificate.getSerialNumber(),
            singleResponses[0].getCertID().getSerialNumber());
    status = singleResponses[0].getCertStatus();
    assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus);
    rev = (RevokedStatus) status;
    assertTrue("Status does not have reason", rev.hasRevocationReason());
    reason = rev.getRevocationReason();
    assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);

}

From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java

License:Open Source License

/** 
 * Tests the case of a standalone OCSP responder with a revoked certificate
 *//*w w w . ja va  2  s.  c o m*/
@Test
public void testResponseWithRevokedResponder() throws Exception {
    //Now delete the original CA, making this test completely standalone.
    OcspTestUtils.deleteCa(authenticationToken, x509ca);
    activateKeyBinding(internalKeyBindingId);
    //Revoke the responder cert
    certificateStoreSession.setRevokeStatus(authenticationToken, ocspSigningCertificate,
            RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, null);
    ocspResponseGeneratorSession.reloadOcspSigningCache();
    // Do the OCSP request
    final OCSPReq ocspRequest = buildOcspRequest(null, null, caCertificate,
            ocspSigningCertificate.getSerialNumber());
    final OCSPResp response = sendRequest(ocspRequest);
    BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject();
    SingleResp[] singleResponses = basicOcspResponse.getResponses();
    assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length);
    assertEquals("Response cert did not match up with request cert", ocspSigningCertificate.getSerialNumber(),
            singleResponses[0].getCertID().getSerialNumber());
    Object status = singleResponses[0].getCertStatus();
    assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus);
    RevokedStatus rev = (RevokedStatus) status;
    assertTrue("Status does not have reason", rev.hasRevocationReason());
    int reason = rev.getRevocationReason();
    assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);
}

From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java

License:Open Source License

/** 
 * Tests the case of a standalone OCSP responder with a revoked certificate issuer.
 * //  ww  w.j  ava  2s  .  co m
 * This should respond revoked, as from the RFC:
 * 
 *  If an OCSP responder knows that a particular CA's private key has
 *  been compromised, it MAY return the revoked state for all
 *  certificates issued by that CA.
 */
@Test
public void testResponseWithRevokedResponderIssuer() throws Exception {
    //Now delete the original CA, making this test completely standalone.
    OcspTestUtils.deleteCa(authenticationToken, x509ca);
    activateKeyBinding(internalKeyBindingId);
    //Revoke the issuer cert
    certificateStoreSession.setRevokeStatus(authenticationToken, caCertificate,
            RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, null);
    ocspResponseGeneratorSession.reloadOcspSigningCache();
    // Do the OCSP request
    final OCSPReq ocspRequest = buildOcspRequest(null, null, caCertificate,
            ocspSigningCertificate.getSerialNumber());
    final OCSPResp response = sendRequest(ocspRequest);
    BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject();
    SingleResp[] singleResponses = basicOcspResponse.getResponses();
    assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length);
    assertEquals("Response cert did not match up with request cert", ocspSigningCertificate.getSerialNumber(),
            singleResponses[0].getCertID().getSerialNumber());
    Object status = singleResponses[0].getCertStatus();
    assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus);
    RevokedStatus rev = (RevokedStatus) status;
    assertTrue("Status does not have reason", rev.hasRevocationReason());
    int reason = rev.getRevocationReason();
    assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);
}

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

License:Open Source License

/**
 * Tests ocsp message with bad status and a valid unid
 * /*from  w w  w .  j ava 2 s  .c om*/
 * @throws Exception error
 */
@Test
public void test02OcspBadWithFnr() throws Exception {
    revocationSession.revokeCertificate(admin, ocspTestCert, null,
            RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, null);

    // And an OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
            ocspTestCert.getSerialNumber()));
    Extension[] extensions = new Extension[1];
    extensions[0] = new Extension(FnrFromUnidExtension.FnrFromUnidOid, false,
            new DEROctetString("123456789".getBytes()));
    gen.setRequestExtensions(new Extensions(extensions));
    OCSPReq req = gen.build();

    // Send the request and receive a BasicResponse
    BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true);
    // When a certificate is revoked the FNR must not be returned
    assertEquals(getFnr(brep), null);
    SingleResp[] singleResps = brep.getResponses();
    assertEquals("No of SingResps should be 1.", singleResps.length, 1);
    SingleResp singleResp = singleResps[0];

    CertificateID certId = singleResp.getCertID();
    assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
            ocspTestCert.getSerialNumber());
    Object status = singleResp.getCertStatus();
    assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus);
    RevokedStatus rev = (RevokedStatus) status;
    assertTrue("Status does not have reason", rev.hasRevocationReason());
    int reason = rev.getRevocationReason();
    assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);
}

From source file:org.keycloak.common.util.OCSPUtils.java

License:Apache License

private static OCSPRevocationStatus singleResponseToRevocationStatus(final SingleResp singleResponse)
        throws CertPathValidatorException {
    final CertificateStatus certStatus = singleResponse.getCertStatus();

    int revocationReason = CRLReason.unspecified;
    Date revocationTime = null;/*  w  w w. ja va  2 s  .  c o  m*/
    RevocationStatus status = RevocationStatus.UNKNOWN;
    if (certStatus == CertificateStatus.GOOD) {
        status = RevocationStatus.GOOD;
    } else if (certStatus instanceof RevokedStatus) {
        RevokedStatus revoked = (RevokedStatus) certStatus;
        revocationTime = revoked.getRevocationTime();
        status = RevocationStatus.REVOKED;
        if (revoked.hasRevocationReason()) {
            revocationReason = revoked.getRevocationReason();
        }
    } else if (certStatus instanceof UnknownStatus) {
        status = RevocationStatus.UNKNOWN;
    } else {
        throw new CertPathValidatorException("Unrecognized revocation status received from OCSP.");
    }

    final RevocationStatus finalStatus = status;
    final Date finalRevocationTime = revocationTime;
    final int finalRevocationReason = revocationReason;
    return new OCSPRevocationStatus() {
        @Override
        public RevocationStatus getRevocationStatus() {
            return finalStatus;
        }

        @Override
        public Date getRevocationTime() {
            return finalRevocationTime;
        }

        @Override
        public CRLReason getRevocationReason() {
            return CRLReason.lookup(finalRevocationReason);
        }
    };
}