List of usage examples for org.bouncycastle.cert.ocsp OCSPReq getEncoded
public byte[] getEncoded() throws IOException
From source file:be.fedict.trust.ocsp.OnlineOcspRepository.java
License:Open Source License
private OCSPResp getOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate) throws Exception { LOG.debug("OCSP URI: " + ocspUri); OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(); CertificateID certId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuerCertificate), certificate.getSerialNumber()); ocspReqBuilder.addRequest(certId);/*from w ww. ja va 2 s. com*/ OCSPReq ocspReq = ocspReqBuilder.build(); byte[] ocspReqData = ocspReq.getEncoded(); HttpPost httpPost = new HttpPost(ocspUri.toString()); ContentType contentType = ContentType.create("application/ocsp-request"); HttpEntity requestEntity = new ByteArrayEntity(ocspReqData, contentType); httpPost.addHeader("User-Agent", "jTrust OCSP Client"); httpPost.setEntity(requestEntity); DefaultHttpClient httpClient = new DefaultHttpClient(); if (null != this.networkConfig) { HttpHost proxy = new HttpHost(this.networkConfig.getProxyHost(), this.networkConfig.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (null != this.credentials) { this.credentials.init(httpClient.getCredentialsProvider()); } HttpResponse httpResponse; int responseCode; try { httpResponse = httpClient.execute(httpPost); StatusLine statusLine = httpResponse.getStatusLine(); responseCode = statusLine.getStatusCode(); } catch (ConnectException e) { LOG.debug("OCSP responder is down"); return null; } if (HttpURLConnection.HTTP_OK != responseCode) { LOG.error("HTTP response code: " + responseCode); return null; } Header responseContentTypeHeader = httpResponse.getFirstHeader("Content-Type"); if (null == responseContentTypeHeader) { LOG.error("no Content-Type response header"); return null; } String resultContentType = responseContentTypeHeader.getValue(); if (!"application/ocsp-response".equals(resultContentType)) { LOG.error("result content type not application/ocsp-response"); LOG.error("actual content-type: " + resultContentType); if ("text/html".equals(resultContentType)) { LOG.error("content: " + EntityUtils.toString(httpResponse.getEntity())); } return null; } Header responseContentLengthHeader = httpResponse.getFirstHeader("Content-Length"); if (null != responseContentLengthHeader) { String resultContentLength = responseContentLengthHeader.getValue(); if ("0".equals(resultContentLength)) { LOG.debug("no content returned"); return null; } } HttpEntity httpEntity = httpResponse.getEntity(); OCSPResp ocspResp = new OCSPResp(httpEntity.getContent()); LOG.debug("OCSP response size: " + ocspResp.getEncoded().length + " bytes"); httpPost.releaseConnection(); return ocspResp; }
From source file:com.itextpdf.signatures.OcspClientBouncyCastle.java
License:Open Source License
private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url) throws GeneralSecurityException, OCSPException, IOException, OperatorException { if (checkCert == null || rootCert == null) return null; if (url == null) { url = CertificateUtil.getOCSPURL(checkCert); }//from w w w. j a v a 2s.c o m if (url == null) return null; LOGGER.info("Getting OCSP from " + url); OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber()); byte[] array = request.getEncoded(); URL urlt = new URL(url); InputStream in = SignUtils.getHttpResponseForOcspRequest(array, urlt); return new OCSPResp(StreamUtil.inputStreamToArray(in)); }
From source file:com.itextpdf.text.pdf.security.OcspClientBouncyCastle.java
License:Open Source License
private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url) throws GeneralSecurityException, OCSPException, IOException, OperatorException { if (checkCert == null || rootCert == null) return null; if (url == null) { url = CertificateUtil.getOCSPURL(checkCert); }//from ww w . j av a 2 s. c om if (url == null) return null; LOGGER.info("Getting OCSP from " + url); 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( MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } //Get Response InputStream in = (InputStream) con.getContent(); return new OCSPResp(StreamUtil.inputStreamToArray(in)); }
From source file:com.tremolosecurity.proxy.auth.ssl.OCSP.java
License:Apache License
@Override public boolean isValid(X509Certificate cert, X509Certificate issuer) { try {//from w w w . ja va2s . c o m OCSPReq ocspRequest = generateOcspRequest(issuer, cert.getSerialNumber()); URL url = new URL(this.url); HttpURLConnection url_con = (HttpURLConnection) url.openConnection(); url_con.setDoOutput(true); url_con.connect(); OutputStream os = url_con.getOutputStream(); os.write(ocspRequest.getEncoded()); InputStream is = url_con.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; do { len = is.read(buffer); if (len > 0) { baos.write(buffer, 0, len); } } while (len > 0); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); OCSPResp ocspResponse = new OCSPResp(bais); BasicOCSPResp resp = (BasicOCSPResp) ocspResponse.getResponseObject(); //System.err.println(resp.getResponses()[0].getCertStatus()); return resp.getResponses()[0].getCertStatus() == null || (!(resp.getResponses()[0] .getCertStatus() instanceof org.bouncycastle.cert.ocsp.RevokedStatus)); } catch (Exception e) { logger.error("Error validating certificate", e); return false; } }
From source file:controller.CCInstance.java
License:Open Source License
private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert) throws GeneralSecurityException, OCSPException, IOException, OperatorException { if (checkCert == null || rootCert == null) { return null; }//from w ww .j a v a 2 s . c o m String url = CertificateUtil.getOCSPURL(checkCert); if (url == null) { return null; } 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(); try (DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out))) { dataOut.write(array); dataOut.flush(); } if (con.getResponseCode() / 100 != 2) { throw new IOException( MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } //Get Response InputStream in = (InputStream) con.getContent(); return new OCSPResp(in); } catch (Exception e) { return null; } }
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 va 2 s.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.signer.certmanager.OcspClient.java
License:Open Source License
private static void sendRequest(HttpURLConnection connection, OCSPReq ocspRequest) throws IOException { try (DataOutputStream outStream = new DataOutputStream( new BufferedOutputStream(connection.getOutputStream()))) { outStream.write(ocspRequest.getEncoded()); }// ww w . j a v a 2 s. c o m }
From source file:eu.europa.ec.markt.dss.validation102853.ocsp.OnlineOCSPSource.java
License:Open Source License
private byte[] buildOCSPRequest(final X509Certificate x509Certificate, final X509Certificate issuerX509Certificate) throws DSSException { try {/* w w w .ja v a 2 s. c o m*/ final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(x509Certificate, issuerX509Certificate); final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); ocspReqBuilder.addRequest(certId); /* * The nonce extension is used to bind a request to a response to prevent replay attacks. */ if (ADD_NONCE) { final long currentTimeNonce = System.currentTimeMillis(); nonce = new DEROctetString(DSSUtils.toByteArray(currentTimeNonce)); final Extension extension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonce); final Extensions extensions = new Extensions(extension); ocspReqBuilder.setRequestExtensions(extensions); } final OCSPReq ocspReq = ocspReqBuilder.build(); final byte[] ocspReqData = ocspReq.getEncoded(); return ocspReqData; } catch (OCSPException e) { throw new DSSException(e); } catch (IOException e) { throw new DSSException(e); } }
From source file:eu.europa.esig.dss.client.ocsp.OnlineOCSPSource.java
License:Open Source License
private byte[] buildOCSPRequest(final CertificateID certId) throws DSSException { try {/*from ww w .j ava 2s. c o m*/ final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); ocspReqBuilder.addRequest(certId); /* * The nonce extension is used to bind a request to a response to prevent replay attacks. * RFC 6960 (OCSP) section 4.1.2 such extensions SHOULD NOT be flagged as critical */ if (nonceSource != null) { Extension extension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonceSource.getNonce().toByteArray())); Extensions extensions = new Extensions(extension); ocspReqBuilder.setRequestExtensions(extensions); } final OCSPReq ocspReq = ocspReqBuilder.build(); final byte[] ocspReqData = ocspReq.getEncoded(); return ocspReqData; } catch (OCSPException e) { throw new DSSException("Cannot build OCSP Request", e); } catch (IOException e) { throw new DSSException("Cannot build OCSP Request", e); } }
From source file:io.netty.example.ocsp.OcspUtils.java
License:Apache License
/** * TODO: This is a very crude and non-scalable HTTP client to fetch the OCSP response from the * CA's OCSP responder server. It's meant to demonstrate the basic building blocks on how to * interact with the responder server and you should consider using Netty's HTTP client instead. *//* w w w . ja va2 s .c o m*/ public static OCSPResp request(URI uri, OCSPReq request, long timeout, TimeUnit unit) throws IOException { byte[] encoded = request.getEncoded(); URL url = uri.toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { connection.setConnectTimeout((int) unit.toMillis(timeout)); connection.setReadTimeout((int) unit.toMillis(timeout)); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("host", uri.getHost()); connection.setRequestProperty("content-type", OCSP_REQUEST_TYPE); connection.setRequestProperty("accept", OCSP_RESPONSE_TYPE); connection.setRequestProperty("content-length", String.valueOf(encoded.length)); OutputStream out = connection.getOutputStream(); try { out.write(encoded); out.flush(); InputStream in = connection.getInputStream(); try { int code = connection.getResponseCode(); if (code != HttpsURLConnection.HTTP_OK) { throw new IOException("Unexpected status-code=" + code); } String contentType = connection.getContentType(); if (!contentType.equalsIgnoreCase(OCSP_RESPONSE_TYPE)) { throw new IOException("Unexpected content-type=" + contentType); } int contentLength = connection.getContentLength(); if (contentLength == -1) { // Probably a terrible idea! contentLength = Integer.MAX_VALUE; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte[] buffer = new byte[8192]; int length = -1; while ((length = in.read(buffer)) != -1) { baos.write(buffer, 0, length); if (baos.size() >= contentLength) { break; } } } finally { baos.close(); } return new OCSPResp(baos.toByteArray()); } finally { in.close(); } } finally { out.close(); } } finally { connection.disconnect(); } }