Java Code Examples for org.bouncycastle.cert.ocsp.BasicOCSPResp#getResponses()
The following examples show how to use
org.bouncycastle.cert.ocsp.BasicOCSPResp#getResponses() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DSSRevocationUtilsTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void testGetOCSPCertificateIDAndMatch() throws IOException { CertificateToken certificate = DSSUtils.loadCertificate(new File("src/test/resources/citizen_ca.cer")); CertificateToken issuer = DSSUtils.loadCertificate(new File("src/test/resources/belgiumrs2.crt")); assertTrue(certificate.isSignedBy(issuer)); CertificateID certificateID = DSSRevocationUtils.getOCSPCertificateID(certificate, issuer, DigestAlgorithm.SHA256); assertNotNull(certificateID); BasicOCSPResp basicOCSPResp = DSSRevocationUtils.loadOCSPBase64Encoded( "MIIHOgoBAKCCBzMwggcvBgkrBgEFBQcwAQEEggcgMIIHHDCCATOhRDBCMQswCQYDVQQGEwJERTEaMBgGA1UECgwRQnVuZGVzbmV0emFnZW50dXIxFzAVBgNVBAMMDjE0Ui1PQ1NQIDEyOlBOGA8yMDE2MDQyNjA5NDE0M1owgbUwgbIwOzAJBgUrDgMCGgUABBRAEkWUqHsHRftOoCVj8/DhlIT7BwQU/fNQhDCO7COa9TOy44EH3eTvgK4CAgM0gAAYDzIwMTUwOTI5MDkwOTI4WqFgMF4wXAYFKyQIAw0EUzBRMA0GCWCGSAFlAwQCAwUABED48AGg2Q8uukS9H0fDCz8LSLzuISU1he4/rk1s7xipORuO0L4BCE/uPEuEU3903zxw5ZRsbqRBysQE1tL8afTaoSIwIDAeBgkrBgEFBQcwAQYEERgPMTk4NjA0MjYwMDAwMDBaMA0GCSqGSIb3DQEBDQUAA4IBAQB3zLgjV0NAApajfNyGk2ijwzAxlTo87ktHjZyv4ccyEWYQoQf26a2K3BMNwZE/6GCY8ElXd4S7pyt5APeHDxjSjxp68OjEctF4lgghVedvMhI2BN57judwZcK9ytd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gYDVR0gBAswCTAHBgUrJAgBATCBsQYDVR0fBIGpMIGmMIGjoIGgoIGdhoGabGRhcDovL2xkYXAubnJjYS1kcy5kZTozODkvQ049Q1JMLE89QnVuZGVzbmV0emFnZW50dXIsQz1ERSxkYz1sZGFwLGRjPW5yY2EtZHMsZGM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9uTGlzdDtiaW5hcnk/YmFzZT9vYmplY3RDbGFzcz1jUkxEaXN0cmlidXRpb25Qb2ludDAbBgkrBgEEAcBtAwUEDjAMBgorBgEEAcBtAwUBMA8GA1UdEwEB/wQFMAMBAQAwHwYDVR0jBBgwFoAU/fNQhDCO7COa9TOy44EH3eTvgK4wHQYDVR0OBBYEFBFllODWsNReIMI/MM3rQ3+rIEBEMA0GCSqGSIb3DQEBDQUAA4IBAQAt3sYpIcdAKClBtX5zPG1+c9qwGq5VW0Q3AqClqI00OxY/GuK840FNUTf5RDt+aOgbgkTVb8n1lJBS05aQddFowA3k4fnxHtgyiR6KygYO3Fsl2MeEJCKgYlRaB0bqiN1A3hzMKXq3S7+l6yUKPnkNg5Nci6PoztZSe7z/TbbUyu8dY+CVYnjgy85AcUhT1tJwoa527ZfgNVDq/6GLLF3ZQzUNNebF90aZlwsW+sFtk9xkxAWuFcSkRq+IaKz/hDhVYlSYaIBlpgjR8YIIaqtky9xakC8bs8KWdBh1DcRxgdAUfLCqHMd3PwkWEw2PmLpqLZeuHFJzb7zeAcXvvVkP"); SingleResp[] responses = basicOCSPResp.getResponses(); assertFalse(DSSRevocationUtils.matches(certificateID, responses[0])); }
Example 2
Source File: OcspClientExample.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override protected boolean verify(ChannelHandlerContext ctx, ReferenceCountedOpenSslEngine engine) throws Exception { byte[] staple = engine.getOcspResponse(); if (staple == null) { throw new IllegalStateException("Server didn't provide an OCSP staple!"); } OCSPResp response = new OCSPResp(staple); if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) { return false; } SSLSession session = engine.getSession(); X509Certificate[] chain = session.getPeerCertificateChain(); BigInteger certSerial = chain[0].getSerialNumber(); BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject(); SingleResp first = basicResponse.getResponses()[0]; // ATTENTION: CertificateStatus.GOOD is actually a null value! Do not use // equals() or you'll NPE! CertificateStatus status = first.getCertStatus(); BigInteger ocspSerial = first.getCertID().getSerialNumber(); String message = new StringBuilder() .append("OCSP status of ").append(ctx.channel().remoteAddress()) .append("\n Status: ").append(status == CertificateStatus.GOOD ? "Good" : status) .append("\n This Update: ").append(first.getThisUpdate()) .append("\n Next Update: ").append(first.getNextUpdate()) .append("\n Cert Serial: ").append(certSerial) .append("\n OCSP Serial: ").append(ocspSerial) .toString(); System.out.println(message); return status == CertificateStatus.GOOD && certSerial.equals(ocspSerial); }
Example 3
Source File: DSSRevocationUtils.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
private static SingleResp[] getSingleResps(BasicOCSPResp basicResponse) { try { return basicResponse.getResponses(); } catch (Exception e) { LOG.warn("Unable to extract SingleResp(s) : {}", e.getMessage()); return new SingleResp[] {}; } }
Example 4
Source File: OCSPFuncTest.java From ph-commons with Apache License 2.0 | 5 votes |
@Nonnull public static ETriState evalOCSPResponse (@Nonnull final OCSPResp aOCSPResponse) throws OCSPException { final EOCSPResponseStatus eStatus = EOCSPResponseStatus.getFromValueOrNull (aOCSPResponse.getStatus ()); if (eStatus == null) throw new OCSPException ("Unsupported status code " + aOCSPResponse.getStatus () + " received!"); if (eStatus.isFailure ()) throw new OCSPException ("Non-success status code " + aOCSPResponse.getStatus () + " received!"); final Object aResponseObject = aOCSPResponse.getResponseObject (); if (aResponseObject instanceof BasicOCSPResp) { final BasicOCSPResp aBasicResponse = (BasicOCSPResp) aResponseObject; final SingleResp [] aResponses = aBasicResponse.getResponses (); // Assume we queried only one if (aResponses.length == 1) { final SingleResp aResponse = aResponses[0]; final CertificateStatus aStatus = aResponse.getCertStatus (); if (aStatus == CertificateStatus.GOOD) return ETriState.TRUE; if (aStatus instanceof RevokedStatus) return ETriState.FALSE; // else status is unknown } } return ETriState.UNDEFINED; }
Example 5
Source File: OcspServerExample.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { // We assume there's a private key. PrivateKey privateKey = null; // Step 1: Load the certificate chain for netty.io. We'll need the certificate // and the issuer's certificate and we don't need any of the intermediate certs. // The array is assumed to be a certain order to keep things simple. X509Certificate[] keyCertChain = parseCertificates(OcspServerExample.class, "netty_io_chain.pem"); X509Certificate certificate = keyCertChain[0]; X509Certificate issuer = keyCertChain[keyCertChain.length - 1]; // Step 2: We need the URL of the CA's OCSP responder server. It's somewhere encoded // into the certificate! Notice that it's a HTTP URL. URI uri = OcspUtils.ocspUri(certificate); System.out.println("OCSP Responder URI: " + uri); if (uri == null) { throw new IllegalStateException("The CA/certificate doesn't have an OCSP responder"); } // Step 3: Construct the OCSP request OCSPReq request = new OcspRequestBuilder() .certificate(certificate) .issuer(issuer) .build(); // Step 4: Do the request to the CA's OCSP responder OCSPResp response = OcspUtils.request(uri, request, 5L, TimeUnit.SECONDS); if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) { throw new IllegalStateException("response-status=" + response.getStatus()); } // Step 5: Is my certificate any good or has the CA revoked it? BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject(); SingleResp first = basicResponse.getResponses()[0]; CertificateStatus status = first.getCertStatus(); System.out.println("Status: " + (status == CertificateStatus.GOOD ? "Good" : status)); System.out.println("This Update: " + first.getThisUpdate()); System.out.println("Next Update: " + first.getNextUpdate()); if (status != null) { throw new IllegalStateException("certificate-status=" + status); } BigInteger certSerial = certificate.getSerialNumber(); BigInteger ocspSerial = first.getCertID().getSerialNumber(); if (!certSerial.equals(ocspSerial)) { throw new IllegalStateException("Bad Serials=" + certSerial + " vs. " + ocspSerial); } // Step 6: Cache the OCSP response and use it as long as it's not // expired. The exact semantics are beyond the scope of this example. if (!OpenSsl.isAvailable()) { throw new IllegalStateException("OpenSSL is not available!"); } if (!OpenSsl.isOcspSupported()) { throw new IllegalStateException("OCSP is not supported!"); } if (privateKey == null) { throw new IllegalStateException("Because we don't have a PrivateKey we can't continue past this point."); } ReferenceCountedOpenSslContext context = (ReferenceCountedOpenSslContext) SslContextBuilder.forServer(privateKey, keyCertChain) .sslProvider(SslProvider.OPENSSL) .enableOcsp(true) .build(); try { ServerBootstrap bootstrap = new ServerBootstrap() .childHandler(newServerHandler(context, response)); // so on and so forth... } finally { context.release(); } }
Example 6
Source File: OcspClientBouncyCastle.java From itext2 with GNU Lesser General Public License v3.0 | 4 votes |
/** * @return a byte array * @see com.lowagie.text.pdf.OcspClient#getEncoded() */ public byte[] getEncoded() { try { OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber()); byte[] array = request.getEncoded(); URL urlt = new URL(url); HttpURLConnection con = (HttpURLConnection)urlt.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(array); dataOut.flush(); dataOut.close(); if (con.getResponseCode() / 100 != 2) { throw new IOException("Invalid HTTP response"); } //Get Response InputStream in = (InputStream) con.getContent(); OCSPResp ocspResponse = new OCSPResp(in); if (ocspResponse.getStatus() != 0) throw new IOException("Invalid status: " + ocspResponse.getStatus()); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse != null) { SingleResp[] responses = basicResponse.getResponses(); if (responses.length == 1) { SingleResp resp = responses[0]; Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { return basicResponse.getEncoded(); } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) { throw new IOException("OCSP Status is revoked!"); } else { throw new IOException("OCSP Status is unknown!"); } } } } catch (Exception ex) { throw new ExceptionConverter(ex); } return null; }
Example 7
Source File: SFTrustManager.java From snowflake-jdbc with Apache License 2.0 | 4 votes |
/** * Validates OCSP Basic OCSP response. * * @param currentTime the current timestamp. * @param basicOcspResp BasicOcspResponse data. * @throws SFOCSPException raises if any failure occurs. */ private void validateBasicOcspResponse( Date currentTime, BasicOCSPResp basicOcspResp) throws SFOCSPException { for (SingleResp singleResps : basicOcspResp.getResponses()) { checkCertUnknownTestParameter(); CertificateStatus certStatus = singleResps.getCertStatus(); if (certStatus != CertificateStatus.GOOD) { if (certStatus instanceof RevokedStatus) { RevokedStatus status = (RevokedStatus) certStatus; int reason; try { reason = status.getRevocationReason(); } catch (IllegalStateException ex) { reason = -1; } Date revocationTime = status.getRevocationTime(); throw new SFOCSPException(OCSPErrorCode.CERTIFICATE_STATUS_REVOKED, String.format( "The certificate has been revoked. Reason: %d, Time: %s", reason, DATE_FORMAT_UTC.format(revocationTime))); } else { // Unknown status throw new SFOCSPException(OCSPErrorCode.CERTIFICATE_STATUS_UNKNOWN, "Failed to validate the certificate for UNKNOWN reason."); } } Date thisUpdate = singleResps.getThisUpdate(); Date nextUpdate = singleResps.getNextUpdate(); LOGGER.debug("Current Time: {}, This Update: {}, Next Update: {}", currentTime, thisUpdate, nextUpdate); if (!isValidityRange(currentTime, thisUpdate, nextUpdate)) { throw new SFOCSPException(OCSPErrorCode.INVALID_OCSP_RESPONSE_VALIDITY, String.format( "The OCSP response validity is out of range: " + "Current Time: %s, This Update: %s, Next Update: %s", DATE_FORMAT_UTC.format(currentTime), DATE_FORMAT_UTC.format(thisUpdate), DATE_FORMAT_UTC.format(nextUpdate))); } } LOGGER.debug("OK. Verified the certificate revocation status."); }
Example 8
Source File: OCSPCertificateVerifier.java From oxAuth with MIT License | 4 votes |
@Override public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) { 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; }