List of usage examples for org.bouncycastle.cert.ocsp CertificateID HASH_SHA1
AlgorithmIdentifier HASH_SHA1
To view the source code for org.bouncycastle.cert.ocsp CertificateID HASH_SHA1.
Click Source Link
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 w w w . ja v a 2s .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:be.fedict.trust.ocsp.OfflineOcspRepository.java
License:Open Source License
@Override public OCSPResp findOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate, Date validationDate) {//from w ww. j a v a 2 s . c o m LOG.debug("find OCSP response"); DigestCalculatorProvider digCalcProv; try { digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(); } catch (OperatorCreationException e) { throw new RuntimeException(e); } CertificateID certId; try { certId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuerCertificate), certificate.getSerialNumber()); } catch (Exception e) { throw new RuntimeException(e); } try { for (OCSPResp ocspResp : this.ocspResponses) { BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject(); for (SingleResp singleResp : basicOCSPResp.getResponses()) { if (singleResp.getCertID().equals(certId)) { LOG.debug("OCSP response found"); return ocspResp; } } } } catch (OCSPException e) { LOG.error("OCSPException: " + e.getMessage(), e); return null; } LOG.debug("OCSP response not found"); return null; }
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 w w .j a v a2 s . c o m 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:be.fedict.trust.test.PKITestUtils.java
License:Open Source License
public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm) throws Exception { // request/*from w w w. ja va 2 s . c o m*/ 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); OCSPReq ocspReq = ocspReqBuilder.build(); BasicOCSPRespBuilder basicOCSPRespBuilder = new JcaBasicOCSPRespBuilder( ocspResponderCertificate.getPublicKey(), digCalcProv.get(CertificateID.HASH_SHA1)); // request processing Req[] requestList = ocspReq.getRequestList(); for (Req ocspRequest : requestList) { CertificateID certificateID = ocspRequest.getCertID(); CertificateStatus certificateStatus; if (revoked) { certificateStatus = new RevokedStatus(new Date(), CRLReason.unspecified); } else { certificateStatus = CertificateStatus.GOOD; } basicOCSPRespBuilder.addResponse(certificateID, certificateStatus); } // basic response generation X509CertificateHolder[] chain = null; if (!ocspResponderCertificate.equals(issuerCertificate)) { chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), new X509CertificateHolder(issuerCertificate.getEncoded()) }; } ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm) .build(ocspResponderPrivateKey); BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date()); // response generation OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp); return ocspResp; }
From source file:be.fedict.trust.test.PKITestUtils.java
License:Open Source License
public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, List<X509Certificate> ocspResponderCertificateChain) throws Exception { // request/* ww w.ja v a 2 s . c om*/ 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); OCSPReq ocspReq = ocspReqBuilder.build(); BasicOCSPRespBuilder basicOCSPRespBuilder = new JcaBasicOCSPRespBuilder( ocspResponderCertificate.getPublicKey(), digCalcProv.get(CertificateID.HASH_SHA1)); // request processing Req[] requestList = ocspReq.getRequestList(); for (Req ocspRequest : requestList) { CertificateID certificateID = ocspRequest.getCertID(); CertificateStatus certificateStatus; if (revoked) { certificateStatus = new RevokedStatus(new Date(), CRLReason.unspecified); } else { certificateStatus = CertificateStatus.GOOD; } basicOCSPRespBuilder.addResponse(certificateID, certificateStatus); } // basic response generation X509CertificateHolder[] chain; if (ocspResponderCertificateChain.isEmpty()) { chain = null; } else { chain = new X509CertificateHolder[ocspResponderCertificateChain.size()]; for (int idx = 0; idx < chain.length; idx++) { chain[idx] = new X509CertificateHolder(ocspResponderCertificateChain.get(idx).getEncoded()); } } ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(ocspResponderPrivateKey); BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date()); // response generation OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp); return ocspResp; }
From source file:com.itextpdf.signatures.OcspClientBouncyCastle.java
License:Open Source License
/** * Generates an OCSP request using BouncyCastle. * * @param issuerCert certificate of the issues * @param serialNumber serial number// w ww.j a v a 2s. c om * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException { //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // Generate the id for the certificate we are looking for CertificateID id = SignUtils.generateCertificateId(issuerCert, serialNumber, CertificateID.HASH_SHA1); // basic request generation with nonce return SignUtils.generateOcspRequestWithNonce(id); }
From source file:com.itextpdf.text.pdf.security.OcspClientBouncyCastle.java
License:Open Source License
/** * Generates an OCSP request using BouncyCastle. * @param issuerCert certificate of the issues * @param serialNumber serial number//from w w w . j a v a 2 s . c om * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException { //Add provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // Generate the id for the certificate we are looking for CertificateID id = new CertificateID( new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuerCert), serialNumber); // basic request generation with nonce OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(id); Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded())); gen.setRequestExtensions(new Extensions(new Extension[] { ext })); return gen.build(); }
From source file:com.tremolosecurity.proxy.auth.ssl.OCSP.java
License:Apache License
private OCSPReq generateOcspRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, CertificateEncodingException, OperatorCreationException, IOException { BcDigestCalculatorProvider util = new BcDigestCalculatorProvider(); // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(util.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), serialNumber); OCSPReqBuilder ocspGen = new OCSPReqBuilder(); ocspGen.addRequest(id);/*from w w w . ja v a 2 s. c om*/ BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray())); ocspGen.setRequestExtensions(new Extensions(new Extension[] { ext })); return ocspGen.build(); }
From source file:controller.CCInstance.java
License:Open Source License
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CertificateID id = new CertificateID( new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuerCert), serialNumber); OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(id);/* w w w. ja v a 2 s. c o m*/ Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded())); gen.setRequestExtensions(new Extensions(new Extension[] { ext })); return gen.build(); }
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 www . ja 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); } }