List of usage examples for org.bouncycastle.cert.ocsp CertificateID equals
public boolean equals(Object o)
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
License:Open Source License
@Override public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy) throws TrustLinkerResultException, Exception { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return TrustLinkerResult.UNDECIDED; }/*from ww w.j a v a 2 s .c o m*/ LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate, validationDate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return TrustLinkerResult.UNDECIDED; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return TrustLinkerResult.UNDECIDED; } Object responseObject = ocspResp.getResponseObject(); BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts(); for (X509CertificateHolder responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubject()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer()); } algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate); if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the issuing * CA itself. */ ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey()); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return TrustLinkerResult.UNDECIDED; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509CertificateHolder ocspResponderCertificate = responseCertificates[0]; ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate); boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return TrustLinkerResult.UNDECIDED; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature algorithm algorithmPolicy.checkSignatureAlgorithm( ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate); X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { // so the OCSP certificate chain only contains a single // entry LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly signed * by the CA. */ issuingCaCertificate = certificate; } else { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); issuingCaCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded())); /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return TrustLinkerResult.UNDECIDED; } } // check certificate signature algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate); PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded())); LOG.debug("OCSP Responder public key fingerprint: " + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded())); publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate, validationDate, revocationData, algorithmPolicy); if (null == x509OcspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return TrustLinkerResult.UNDECIDED; } List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage(); if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return TrustLinkerResult.UNDECIDED; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return TrustLinkerResult.UNDECIDED; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); // and the CA certificate is already trusted at this point } } DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(); CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber()); SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } DateTime thisUpdate = new DateTime(singleResp.getThisUpdate()); DateTime nextUpdate; if (null != singleResp.getNextUpdate()) { nextUpdate = new DateTime(singleResp.getNextUpdate()); } else { LOG.debug("no OCSP nextUpdate"); nextUpdate = thisUpdate; } LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("(OCSP) nextUpdate: " + nextUpdate); DateTime beginValidity = thisUpdate.minus(this.freshnessInterval); DateTime endValidity = nextUpdate.plus(this.freshnessInterval); DateTime validationDateTime = new DateTime(validationDate); if (validationDateTime.isBefore(beginValidity)) { LOG.warn("OCSP response not yet valid"); continue; } if (validationDateTime.isAfter(endValidity)) { LOG.warn("OCSP response expired"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp, ocspUri); return TrustLinkerResult.TRUSTED; } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp, ocspUri); throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return TrustLinkerResult.UNDECIDED; }
From source file:com.itextpdf.signatures.PdfPKCS7.java
License:Open Source License
/** * Checks if OCSP revocation refers to the document signing certificate. * * @return true if it checks, false otherwise *///from www . j a v a 2 s .c o m public boolean isRevocationValid() { if (basicResp == null) return false; if (signCerts.size() < 2) return false; try { X509Certificate[] cs = (X509Certificate[]) getSignCertificateChain(); SingleResp sr = basicResp.getResponses()[0]; CertificateID cid = sr.getCertID(); X509Certificate sigcer = getSigningCertificate(); X509Certificate isscer = cs[1]; CertificateID tis = SignUtils.generateCertificateId(isscer, sigcer.getSerialNumber(), cid.getHashAlgOID()); return tis.equals(cid); } catch (Exception ignored) { } return false; }
From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java
License:Open Source License
/** * Checks if OCSP revocation refers to the document signing certificate. * @return true if it checks, false otherwise * @since 2.1.6/* w w w. j av a 2 s.c o m*/ */ public boolean isRevocationValid() { if (basicResp == null) return false; if (signCerts.size() < 2) return false; try { X509Certificate[] cs = (X509Certificate[]) getSignCertificateChain(); SingleResp sr = basicResp.getResponses()[0]; CertificateID cid = sr.getCertID(); DigestCalculator digestalg = new JcaDigestCalculatorProviderBuilder().build() .get(new AlgorithmIdentifier(cid.getHashAlgOID(), DERNull.INSTANCE)); X509Certificate sigcer = getSigningCertificate(); X509Certificate isscer = cs[1]; CertificateID tis = new CertificateID(digestalg, new JcaX509CertificateHolder(isscer), sigcer.getSerialNumber()); return tis.equals(cid); } catch (Exception ex) { } return false; }
From source file:ee.ria.xroad.common.cert.CertHelper.java
License:Open Source License
/** * Finds the OCSP response from a list of OCSP responses * for a given certificate.//ww w . j a v a 2 s. c o m * @param cert the certificate * @param issuer the issuer of the certificate * @param ocspResponses list of OCSP responses * @return the OCSP response or null if not found * @throws Exception if an error occurs */ public static OCSPResp getOcspResponseForCert(X509Certificate cert, X509Certificate issuer, List<OCSPResp> ocspResponses) throws Exception { CertificateID certId = CryptoUtils.createCertId(cert, issuer); for (OCSPResp resp : ocspResponses) { BasicOCSPResp basicResp = (BasicOCSPResp) resp.getResponseObject(); SingleResp singleResp = basicResp.getResponses()[0]; if (certId.equals(singleResp.getCertID())) { return resp; } } return null; }
From source file:org.jivesoftware.openfire.net.OCSPChecker.java
License:Open Source License
@Override public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException { Log.debug("OCSPChecker: check called"); InputStream in = null;/*from ww w . ja v a2 s . co m*/ OutputStream out = null; try { // Examine OCSP properties X509Certificate responderCert = null; boolean haveResponderCert = true; //defaults to issuers cert X500Principal responderSubjectName = null; boolean haveIssuerCert = false; // If we set the subject name, we need to find the certificate if (ocspServerSubject != null) { haveResponderCert = false; responderSubjectName = new X500Principal(ocspServerSubject); } X509Certificate issuerCert = null; X509Certificate currCert = (X509Certificate) cert; // Set the issuer certificate if we were passed a chain if (certIndex != 0) { issuerCert = (X509Certificate) (certs[certIndex]); haveIssuerCert = true; if (haveResponderCert) { responderCert = certs[certIndex]; } } if (!haveIssuerCert || !haveResponderCert) { if (!haveResponderCert) { Log.debug("OCSPChecker: Looking for responder's certificate"); } if (!haveIssuerCert) { Log.debug("OCSPChecker: Looking for issuer's certificate"); } // Extract the anchor certs Iterator anchors = pkixParams.getTrustAnchors().iterator(); if (!anchors.hasNext()) { throw new CertPathValidatorException("Must specify at least one trust anchor"); } X500Principal certIssuerName = currCert.getIssuerX500Principal(); while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) { TrustAnchor anchor = (TrustAnchor) anchors.next(); X509Certificate anchorCert = anchor.getTrustedCert(); X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal(); // Check if this anchor cert is the issuer cert if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) { issuerCert = anchorCert; haveIssuerCert = true; //If we have not set the responderCert at this point, set it to the issuer if (haveResponderCert && responderCert == null) { responderCert = anchorCert; Log.debug("OCSPChecker: Responder's certificate = issuer certificate"); } } // Check if this anchor cert is the responder cert if (!haveResponderCert) { if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) { responderCert = anchorCert; haveResponderCert = true; } } } if (issuerCert == null) { //No trust anchor was found matching the issuer throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN()); } // Check cert stores if responder cert has not yet been found if (!haveResponderCert) { Log.debug("OCSPChecker: Searching cert stores for responder's certificate"); if (responderSubjectName != null) { X509CertSelector filter = new X509CertSelector(); filter.setSubject(responderSubjectName.getName()); List<CertStore> certStores = pkixParams.getCertStores(); for (CertStore certStore : certStores) { Iterator i = certStore.getCertificates(filter).iterator(); if (i.hasNext()) { responderCert = (X509Certificate) i.next(); haveResponderCert = true; break; } } } } } // Could not find the responder cert if (!haveResponderCert) { throw new CertPathValidatorException("Cannot find the responder's certificate."); } // Construct an OCSP Request OCSPReqBuilder gen = new OCSPReqBuilder(); CertificateID certID = new CertificateID( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber()); gen.addRequest(certID); OCSPReq ocspRequest = gen.build(); URL url; if (ocspServerUrl != null) { try { url = new URL(ocspServerUrl); } catch (MalformedURLException e) { throw new CertPathValidatorException(e); } } else { throw new CertPathValidatorException("Must set OCSP Server URL"); } HttpURLConnection con = (HttpURLConnection) url.openConnection(); Log.debug("OCSPChecker: connecting to OCSP service at: " + url); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); byte[] bytes = ocspRequest.getEncoded(); con.setRequestProperty("Content-length", String.valueOf(bytes.length)); out = con.getOutputStream(); out.write(bytes); out.flush(); // Check the response if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage()); } in = con.getInputStream(); OCSPResp ocspResponse = new OCSPResp(in); BigInteger serialNumber = currCert.getSerialNumber(); BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject(); try { if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC") .build(responderCert.getPublicKey()))) { throw new CertPathValidatorException("OCSP response is not verified"); } } catch (Exception e) { throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex); } SingleResp[] singleResp = brep.getResponses(); boolean foundResponse = false; for (SingleResp resp : singleResp) { CertificateID respCertID = resp.getCertID(); if (respCertID.equals(certID)) { Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good"); foundResponse = true; break; } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked"); throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex); } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown"); throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex); } else { Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized"); throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex); } } } // Check that response applies to the cert that was supplied if (!foundResponse) { throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request."); } } catch (CertPathValidatorException cpve) { throw cpve; } catch (Exception e) { throw new CertPathValidatorException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { throw new CertPathValidatorException(ioe); } } if (out != null) { try { out.close(); } catch (IOException ioe) { throw new CertPathValidatorException(ioe); } } } }
From source file:org.jruby.ext.openssl.OCSPBasicResponse.java
License:Common Public License
private CertificateID checkCertIds(List<SingleResp> singleResponses) { ArrayList<SingleResp> ary = new ArrayList<SingleResp>(singleResponses); CertificateID cid = ary.remove(0).getCertID(); for (SingleResp singleResp : ary) { if (!cid.equals(singleResp.getCertID())) return null; }/* ww w . j a v a2s .c o m*/ return cid; }
From source file:org.xdi.oxauth.cert.validation.OCSPCertificateVerifier.java
License:MIT License
@Override public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {/*from w ww . jav a 2s . c o m*/ X509Certificate issuer = issuers.get(0); ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN); try { Principal subjectX500Principal = certificate.getSubjectX500Principal(); String ocspUrl = getOCSPUrl(certificate); if (ocspUrl == null) { log.error("OCSP URL for '" + subjectX500Principal + "' is empty"); return status; } log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'"); DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build() .get(CertificateID.HASH_SHA1); CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber()); // Generate OCSP request OCSPReq ocspReq = generateOCSPRequest(certificateId); // Get OCSP response from server OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq); if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) { log.error("OCSP response is invalid!"); status.setValidity(CertificateValidity.INVALID); return status; } boolean foundResponse = false; BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject(); SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (!certificateId.equals(responseCertificateId)) { continue; } foundResponse = true; log.debug("OCSP validationDate: " + validationDate); log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate()); log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate()); status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt()); Object certStatus = singleResp.getCertStatus(); if (certStatus == CertificateStatus.GOOD) { log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'"); status.setValidity(CertificateValidity.VALID); } else { if (singleResp.getCertStatus() instanceof RevokedStatus) { log.warn("OCSP status is revoked for: " + subjectX500Principal); if (validationDate .before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) { log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate); status.setValidity(CertificateValidity.VALID); } else { Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime(); log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate); status.setRevocationDate(revocationDate); status.setRevocationObjectIssuingTime(singleResp.getThisUpdate()); status.setValidity(CertificateValidity.REVOKED); } } } } if (!foundResponse) { log.error("There is no matching OCSP response entries"); } } catch (Exception ex) { log.error("OCSP exception: ", ex); } return status; }