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

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

Introduction

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

Prototype

public Date getRevocationTime() 

Source Link

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 w  w w .  j a v  a2s. 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:ee.ria.xroad.common.ocsp.OcspVerifier.java

License:Open Source License

private static String getStatusString(CertificateStatus status) {
    if (status instanceof UnknownStatus) {
        return "UNKNOWN";
    } else if (status instanceof RevokedStatus) {
        RevokedStatus rs = (RevokedStatus) status;
        return String.format("REVOKED (date: %tF %tT)", rs.getRevocationTime(), rs.getRevocationTime());
    } else {//from www.j av a 2 s.  c  om
        return "INVALID";
    }

}

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  v  a 2  s. c  o 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;//from w  w w. jav a  2 s  .c om
        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 void setStatus(final CertificateStatus certStatus) {

    if (certStatus == null) {
        status = true;//from   w w  w .  ja va2s . c  om
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("OCSP certificate status: " + certStatus.getClass().getName());
    }
    if (certStatus instanceof RevokedStatus) {

        if (logger.isInfoEnabled()) {
            logger.info("OCSP status revoked");
        }
        final RevokedStatus revokedStatus = (RevokedStatus) certStatus;
        status = false;
        revocationDate = revokedStatus.getRevocationTime();
        reason = getRevocationReason(revokedStatus);
    } else if (certStatus instanceof UnknownStatus) {

        if (logger.isInfoEnabled()) {
            logger.info("OCSP status unknown");
        }
        reason = "OCSP status: unknown";
    }
}

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/*  w w  w.j a  va 2 s  .c  om*/
 * @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.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 ww.j av a2 s .com*/
    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");
    }// w  ww.  j  a v a 2  s .  c om

    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   w  ww .j  a  va 2  s .c om
        // 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;
}

From source file:org.xipki.pki.ocsp.client.shell.OcspStatusCmd.java

License:Open Source License

@Override
protected Object processResponse(final OCSPResp response, final X509Certificate respIssuer,
        final IssuerHash issuerHash, final List<BigInteger> serialNumbers,
        final Map<BigInteger, byte[]> encodedCerts) throws Exception {
    ParamUtil.requireNonNull("response", response);
    ParamUtil.requireNonNull("issuerHash", issuerHash);
    ParamUtil.requireNonNull("serialNumbers", serialNumbers);

    BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);

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

    SingleResp[] singleResponses = basicResp.getResponses();

    if (singleResponses == null || singleResponses.length == 0) {
        throw new CmdFailure("received no status from server");
    }//from ww  w  .j a  va2  s.  com

    final int n = singleResponses.length;
    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()) {
        println("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");
        }

        ResponderID respId = basicResp.getResponderId().toASN1Primitive();
        X500Name respIdByName = respId.getName();
        byte[] respIdByKey = respId.getKeyHash();

        X509CertificateHolder respSigner = null;
        for (X509CertificateHolder cert : responderCerts) {
            if (respIdByName != null) {
                if (cert.getSubject().equals(respIdByName)) {
                    respSigner = cert;
                }
            } else {
                byte[] spkiSha1 = HashAlgoType.SHA1
                        .hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
                if (Arrays.equals(respIdByKey, spkiSha1)) {
                    respSigner = cert;
                }
            }

            if (respSigner != null) {
                break;
            }
        }

        if (respSigner == null) {
            throw new CmdFailure("no responder certificate match the ResponderId");
        }

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

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

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

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

                if (!certValid) {
                    throw new CmdFailure("response is equipped with valid signature but the"
                            + " OCSP signer is not trusted");
                }
            } else {
                println("response is equipped with valid signature");
            } // end if(respIssuer)
        } // end if(validOn)

        if (verbose.booleanValue()) {
            println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
        }
    } // end if

    for (int i = 0; i < n; i++) {
        if (n > 1) {
            println("---------------------------- " + i + "----------------------------");
        }
        SingleResp singleResp = singleResponses[i];
        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 = ").append(revTime);
                    if (invTime != null) {
                        sb.append(", invalidityTime = ").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();

        CertificateID certId = singleResp.getCertID();
        HashAlgoType hashAlgo = HashAlgoType.getNonNullHashAlgoType(certId.getHashAlgOID());
        boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
        BigInteger serialNumber = certId.getSerialNumber();

        msg.append("issuer matched: ").append(issuerMatch);
        msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
        msg.append("\nCertificate status: ").append(status);

        if (verbose.booleanValue()) {
            msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
            msg.append("\nnextUpdate: ").append(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");
                    }
                }
            } // end if (extension != null)

            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 = EXTENSION_OIDNAME_MAP.get(extensionOid);
                    if (name == null) {
                        msg.append(extensionOid.getId());
                    } else {
                        msg.append(name);
                    }
                    if (j != size - 1) {
                        msg.append(", ");
                    }
                }
            }
        } // end if (verbose.booleanValue())

        println(msg.toString());
    } // end for
    println("");

    return null;
}