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

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

Introduction

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

Prototype

public boolean hasRevocationReason() 

Source Link

Usage

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;//from ww w  .  j  a  va 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: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.
 *///  w w  w  .  j a v  a2  s.  co  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
 *///from w  ww .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.
 * //www.  java  2  s  .c  o  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
 * /*  w  ww .ja v a 2 s.  c  o  m*/
 * @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.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java

License:Open Source License

/**
 * Tests ocsp message//from   ww  w .j  a v  a  2s . c  om
 * 
 * @throws Exception
 *             error
 */
@Test
public void test03OcspRevoked() throws Exception {
    ocspResponseGeneratorTestSession.reloadOcspSigningCache();
    final X509Certificate ocspTestCert = getRevokedTestCert();
    // And an OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), getCaCert(ocspTestCert),
            ocspTestCert.getSerialNumber()));
    OCSPReq req = gen.build();

    // Send the request and receive a singleResponse
    SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), null, 0, 200);
    assertEquals("No of SingResps should be 1.", 1, singleResps.length);
    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 (" + status + ") is not RevokedStatus", status instanceof RevokedStatus);
    RevokedStatus rev = (RevokedStatus) status;
    assertTrue("Status does not have reason", rev.hasRevocationReason());
}

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

License:Open Source License

/**
 * Tests the ocsp.revoked.untilNextUpdate configuration.
 * /* w w  w.  j a v  a  2s . co  m*/
 * The test sets ocsp.untilNextUpdate and ocsp.revoked.untilNextUpdate to different values and then verified that the response's next update value matches 
 * the setting of ocsp.revoked.untilNextUpdate and not ocsp.untilNextUpdate
 * 
 * @throws Exception
 *             error
 */
@Test
public void testRevokedNextUpdate() throws Exception {
    ocspResponseGeneratorTestSession.reloadOcspSigningCache();
    final X509Certificate ocspTestCert = getRevokedTestCert();

    final String oldConfigurationValue1 = configurationSession.getConfigurationValue(
            "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".untilNextUpdate");
    final String oldConfigurationValue2 = configurationSession.getConfigurationValue(
            "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".revoked.untilNextUpdate");
    configurationSession.setConfigurationValue(
            "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".untilNextUpdate", "7");
    configurationSession.setConfigurationValue(
            "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".revoked.untilNextUpdate",
            "5");
    // Make sure that we run the test with a CA where this is no OcspKeyBinding
    OcspTestUtils.setInternalKeyBindingStatus(authenticationToken, internalKeyBindingId,
            InternalKeyBindingStatus.DISABLED);
    ocspResponseGeneratorTestSession.reloadOcspSigningCache();
    try {

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), getCaCert(ocspTestCert),
                ocspTestCert.getSerialNumber()));
        OCSPReq req = gen.build();

        // Send the request and receive a singleResponse
        SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), null, 0, 200);
        assertEquals("No of SingResps should be 1.", 1, singleResps.length);
        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 (" + status + ") is not RevokedStatus", status instanceof RevokedStatus);
        RevokedStatus rev = (RevokedStatus) status;
        assertTrue("Status does not have reason", rev.hasRevocationReason());

        Date thisUpdate = singleResp.getThisUpdate();
        Date nextUpdate = singleResp.getNextUpdate();
        assertNotNull("thisUpdate was not set.", thisUpdate);
        assertNotNull(
                "nextUpdate was not set. (This test requires ocsp.revoked.untilNextUpdate to be configured.)",
                nextUpdate);

        long diff = nextUpdate.getTime() - thisUpdate.getTime();
        assertEquals("The nextUpdate value was not taken from ocsp.revoked.untilNextUpdate", 5000L, diff);

    } finally {
        configurationSession.setConfigurationValue(
                "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".untilNextUpdate",
                oldConfigurationValue1);
        configurationSession.setConfigurationValue(
                "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".revoked.untilNextUpdate",
                oldConfigurationValue2);
        OcspTestUtils.setInternalKeyBindingStatus(authenticationToken, internalKeyBindingId,
                InternalKeyBindingStatus.ACTIVE);
    }

}

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;/*www  . j  a  v a 2s.  co 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);
        }
    };
}

From source file:org.xipki.ocsp.client.shell.OCSPStatusCommand.java

License:Open Source License

@Override
protected Object processResponse(final OCSPResp response, final X509Certificate respIssuer,
        final X509Certificate issuer, final List<BigInteger> serialNumbers,
        final Map<BigInteger, byte[]> encodedCerts) throws Exception {
    BasicOCSPResp basicResp = OCSPUtils.extractBasicOCSPResp(response);

    boolean extendedRevoke = basicResp.getExtension(OCSPRequestor.id_pkix_ocsp_extendedRevoke) != null;

    SingleResp[] singleResponses = basicResp.getResponses();

    int n = singleResponses == null ? 0 : singleResponses.length;
    if (n == 0) {
        throw new CmdFailure("received no status from server");
    }/*from   w ww  .  j  ava 2  s  .  co  m*/

    if (n != serialNumbers.size()) {
        throw new CmdFailure("received status with " + n + " single responses from server, but "
                + serialNumbers.size() + " were requested");
    }

    Date[] thisUpdates = new Date[n];
    for (int i = 0; i < n; i++) {
        thisUpdates[i] = singleResponses[i].getThisUpdate();
    }

    // check the signature if available
    if (null == basicResp.getSignature()) {
        out("response is not signed");
    } else {
        X509CertificateHolder[] responderCerts = basicResp.getCerts();
        if (responderCerts == null || responderCerts.length < 1) {
            throw new CmdFailure("no responder certificate is contained in the response");
        }

        X509CertificateHolder respSigner = responderCerts[0];
        boolean validOn = true;
        for (Date thisUpdate : thisUpdates) {
            validOn = respSigner.isValidOn(thisUpdate);
            if (validOn == false) {
                throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
            }
        }

        if (validOn) {
            PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
            ContentVerifierProvider cvp = KeyUtil.getContentVerifierProvider(responderPubKey);
            boolean sigValid = basicResp.isSignatureValid(cvp);

            if (sigValid == false) {
                throw new CmdFailure("response is equipped with invalid signature");
            }

            // verify the OCSPResponse signer
            if (respIssuer != null) {
                boolean certValid = true;
                X509Certificate jceRespSigner = new X509CertificateObject(respSigner.toASN1Structure());
                if (X509Util.issues(respIssuer, jceRespSigner)) {
                    try {
                        jceRespSigner.verify(respIssuer.getPublicKey());
                    } catch (SignatureException e) {
                        certValid = false;
                    }
                }

                if (certValid == false) {
                    throw new CmdFailure(
                            "response is equipped with valid signature but the OCSP signer is not trusted");
                }
            } else {
                out("response is equipped with valid signature");
            }
        }

        if (verbose.booleanValue()) {
            out("responder is " + X509Util.getRFC4519Name(responderCerts[0].getSubject()));
        }
    }

    for (int i = 0; i < n; i++) {
        if (n > 1) {
            out("---------------------------- " + i + " ----------------------------");
        }
        SingleResp singleResp = singleResponses[i];
        BigInteger serialNumber = singleResp.getCertID().getSerialNumber();

        CertificateStatus singleCertStatus = singleResp.getCertStatus();

        String status;
        if (singleCertStatus == null) {
            status = "good";
        } else if (singleCertStatus instanceof RevokedStatus) {
            RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
            Date revTime = revStatus.getRevocationTime();
            Date invTime = null;
            Extension ext = singleResp.getExtension(Extension.invalidityDate);
            if (ext != null) {
                invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
            }

            if (revStatus.hasRevocationReason()) {
                int reason = revStatus.getRevocationReason();
                if (extendedRevoke && reason == CRLReason.CERTIFICATE_HOLD.getCode()
                        && revTime.getTime() == 0) {
                    status = "unknown (RFC6960)";
                } else {
                    StringBuilder sb = new StringBuilder("revoked, reason = ");
                    sb.append(CRLReason.forReasonCode(reason).getDescription());
                    sb.append(", revocationTime = ");
                    sb.append(revTime);
                    if (invTime != null) {
                        sb.append(", invalidityTime = ");
                        sb.append(invTime);
                    }
                    status = sb.toString();
                }
            } else {
                status = "revoked, no reason, revocationTime = " + revTime;
            }
        } else if (singleCertStatus instanceof UnknownStatus) {
            status = "unknown (RFC2560)";
        } else {
            status = "ERROR";
        }

        StringBuilder msg = new StringBuilder();
        msg.append("serialNumber: ").append(serialNumber);
        msg.append("\nCertificate status: ").append(status);

        if (verbose.booleanValue()) {
            msg.append("\nthisUpdate: " + singleResp.getThisUpdate());
            msg.append("\nnextUpdate: " + singleResp.getNextUpdate());

            Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
            if (extension != null) {
                msg.append("\nCertHash is provided:\n");
                ASN1Encodable extensionValue = extension.getParsedValue();
                CertHash certHash = CertHash.getInstance(extensionValue);
                ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
                byte[] hashValue = certHash.getCertificateHash();

                msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
                msg.append("\tHash value: ").append(Hex.toHexString(hashValue)).append("\n");

                if (encodedCerts != null) {
                    byte[] encodedCert = encodedCerts.get(serialNumber);
                    MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                    byte[] expectedHashValue = md.digest(encodedCert);
                    if (Arrays.equals(expectedHashValue, hashValue)) {
                        msg.append("\tThis matches the requested certificate");
                    } else {
                        msg.append("\tThis differs from the requested certificate");
                    }
                }
            }

            extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
            if (extension != null) {
                ASN1Encodable extensionValue = extension.getParsedValue();
                ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
                msg.append("\nArchive-CutOff: ");
                msg.append(time.getTimeString());
            }

            AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
            if (sigAlg == null) {
                msg.append(("\nresponse is not signed"));
            } else {
                String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
                if (sigAlgName == null) {
                    sigAlgName = "unknown";
                }
                msg.append("\nresponse is signed with ").append(sigAlgName);
            }

            // extensions
            msg.append("\nExtensions: ");

            List<?> extensionOIDs = basicResp.getExtensionOIDs();
            if (extensionOIDs == null || extensionOIDs.size() == 0) {
                msg.append("-");
            } else {
                int size = extensionOIDs.size();
                for (int j = 0; j < size; j++) {
                    ASN1ObjectIdentifier extensionOID = (ASN1ObjectIdentifier) extensionOIDs.get(j);
                    String name = extensionOidNameMap.get(extensionOID);
                    msg.append(name == null ? extensionOID.getId() : name);
                    if (j != size - 1) {
                        msg.append(", ");
                    }
                }
            }
        }

        out(msg.toString());
    }
    out("");

    return null;
}

From source file:org.xipki.ocsp.qa.impl.OcspQAImpl.java

License:Open Source License

private List<ValidationIssue> checkSingleCert(final int index, final SingleResp singleResp,
        final OcspCertStatus expectedStatus, final byte[] encodedCert, final boolean extendedRevoke,
        final Occurrence nextupdateOccurrence, final Occurrence certhashOccurrence,
        final ASN1ObjectIdentifier certhashAlg) {
    List<ValidationIssue> issues = new LinkedList<>();
    {//from ww  w. jav a  2 s .c  o m
        // status
        ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".STATUS", "certificate status");
        issues.add(issue);

        CertificateStatus singleCertStatus = singleResp.getCertStatus();

        OcspCertStatus status = null;
        if (singleCertStatus == null) {
            status = OcspCertStatus.good;
        } else if (singleCertStatus instanceof RevokedStatus) {
            RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
            Date revTime = revStatus.getRevocationTime();

            if (revStatus.hasRevocationReason()) {
                int reason = revStatus.getRevocationReason();
                if (extendedRevoke && reason == CRLReason.CERTIFICATE_HOLD.getCode()
                        && revTime.getTime() == 0) {
                    status = OcspCertStatus.unknown;
                } else {
                    CRLReason revocationReason = CRLReason.forReasonCode(reason);
                    switch (revocationReason) {
                    case UNSPECIFIED:
                        status = OcspCertStatus.unspecified;
                        break;
                    case KEY_COMPROMISE:
                        status = OcspCertStatus.keyCompromise;
                        break;
                    case CA_COMPROMISE:
                        status = OcspCertStatus.cACompromise;
                        break;
                    case AFFILIATION_CHANGED:
                        status = OcspCertStatus.affiliationChanged;
                        break;
                    case SUPERSEDED:
                        status = OcspCertStatus.superseded;
                        break;
                    case CERTIFICATE_HOLD:
                        status = OcspCertStatus.certificateHold;
                        break;
                    case REMOVE_FROM_CRL:
                        status = OcspCertStatus.removeFromCRL;
                        break;
                    case PRIVILEGE_WITHDRAWN:
                        status = OcspCertStatus.privilegeWithdrawn;
                        break;
                    case AA_COMPROMISE:
                        status = OcspCertStatus.aACompromise;
                        break;
                    default:
                        issue.setFailureMessage("should not reach here, unknwon CRLReason " + revocationReason);
                        break;
                    }
                }
            } else {
                status = OcspCertStatus.rev_noreason;
            }
        } else if (singleCertStatus instanceof UnknownStatus) {
            status = OcspCertStatus.issuerUnknown;
        } else {
            issue.setFailureMessage("unknown certstatus: " + singleCertStatus.getClass().getName());
        }

        if (issue.isFailed() == false && expectedStatus != status) {
            issue.setFailureMessage("is='" + status + "', but expected='" + expectedStatus + "'");
        }
    }

    {
        // nextUpdate
        Date nextUpdate = singleResp.getNextUpdate();
        checkOccurrence("OCSP.RESPONSE." + index + ".NEXTUPDATE", nextUpdate, nextupdateOccurrence);
    }

    Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
    {
        checkOccurrence("OCSP.RESPONSE." + index + ".CERTHASh", extension, certhashOccurrence);
    }

    if (extension != null) {
        ASN1Encodable extensionValue = extension.getParsedValue();
        CertHash certHash = CertHash.getInstance(extensionValue);
        ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
        if (certhashAlg != null) {
            // certHash algorithm
            ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CERTHASH.ALG",
                    "certhash algorithm");
            issues.add(issue);

            ASN1ObjectIdentifier is = certHash.getHashAlgorithm().getAlgorithm();
            if (certhashAlg.equals(is) == false) {
                issue.setFailureMessage("is '" + is.getId() + "', but expected '" + certhashAlg.getId() + "'");
            }
        }

        byte[] hashValue = certHash.getCertificateHash();
        if (encodedCert != null) {
            ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CERTHASH.VALIDITY",
                    "certhash validity");
            issues.add(issue);

            try {
                MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                byte[] expectedHashValue = md.digest(encodedCert);
                if (Arrays.equals(expectedHashValue, hashValue) == false) {
                    issue.setFailureMessage("certHash does not match the requested certificate");
                }
            } catch (NoSuchAlgorithmException e) {
                issue.setFailureMessage("NoSuchAlgorithm " + hashAlgOid.getId());
            }
        }
    }

    return issues;
}