List of usage examples for org.bouncycastle.cert.ocsp BasicOCSPResp getResponses
public SingleResp[] getResponses()
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 w ww . j a v a2 s .c om*/ 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.client.ocsp.OnlineOCSPSource.java
License:Open Source License
private SingleResp getBestSingleResp(final BasicOCSPResp basicOCSPResp, final CertificateID certId) { Date bestUpdate = null;//w w w .ja va 2 s . c om SingleResp bestSingleResp = null; for (final SingleResp singleResp : basicOCSPResp.getResponses()) { if (DSSRevocationUtils.matches(certId, singleResp)) { final Date thisUpdate = singleResp.getThisUpdate(); if ((bestUpdate == null) || thisUpdate.after(bestUpdate)) { bestSingleResp = singleResp; bestUpdate = thisUpdate; } } } return bestSingleResp; }
From source file:eu.europa.esig.dss.cookbook.sources.AlwaysValidOCSPSource.java
License:Open Source License
@Override public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken) { try {//from w w w. j av a2 s .co m final X509Certificate cert = certificateToken.getCertificate(); final BigInteger serialNumber = cert.getSerialNumber(); X509Certificate issuerCert = issuerCertificateToken.getCertificate(); final OCSPReq ocspReq = generateOCSPRequest(issuerCert, serialNumber); final DigestCalculator digestCalculator = DSSRevocationUtils.getSHA1DigestCalculator(); final BasicOCSPRespBuilder basicOCSPRespBuilder = new JcaBasicOCSPRespBuilder(issuerCert.getPublicKey(), digestCalculator); final Extension extension = ocspReq.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (extension != null) { basicOCSPRespBuilder.setResponseExtensions(new Extensions(new Extension[] { extension })); } final Req[] requests = ocspReq.getRequestList(); for (int ii = 0; ii != requests.length; ii++) { final Req req = requests[ii]; final CertificateID certID = req.getCertID(); boolean isOK = true; if (isOK) { basicOCSPRespBuilder.addResponse(certID, CertificateStatus.GOOD, ocspDate, null, null); } else { Date revocationDate = DSSUtils.getDate(ocspDate, -1); basicOCSPRespBuilder.addResponse(certID, new RevokedStatus(revocationDate, CRLReason.privilegeWithdrawn)); } } final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC") .build(privateKey); final X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(issuerCert.getEncoded()); final X509CertificateHolder[] chain = { x509CertificateHolder }; BasicOCSPResp basicResp = basicOCSPRespBuilder.build(contentSigner, chain, ocspDate); final SingleResp[] responses = basicResp.getResponses(); final OCSPToken ocspToken = new OCSPToken(); ocspToken.setBasicOCSPResp(basicResp); ocspToken.setBestSingleResp(responses[0]); return ocspToken; } catch (OCSPException e) { throw new DSSException(e); } catch (IOException e) { throw new DSSException(e); } catch (CertificateEncodingException e) { throw new DSSException(e); } catch (OperatorCreationException e) { throw new DSSException(e); } }
From source file:eu.europa.esig.dss.x509.ocsp.OfflineOCSPSource.java
License:Open Source License
@Override final public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken) { final List<BasicOCSPResp> containedOCSPResponses = getContainedOCSPResponses(); if (LOG.isTraceEnabled()) { final String dssIdAsString = certificateToken.getDSSIdAsString(); LOG.trace("--> OfflineOCSPSource queried for " + dssIdAsString + " contains: " + containedOCSPResponses.size() + " element(s)."); }//from w w w. jav a 2 s . c o m /** * TODO: (Bob 2013.05.08) Does the OCSP responses always use SHA1?<br> * RFC 2560:<br> * CertID ::= SEQUENCE {<br> * hashAlgorithm AlgorithmIdentifier,<br> * issuerNameHash OCTET STRING, -- Hash of Issuer's DN<br> * issuerKeyHash OCTET STRING, -- Hash of Issuer's public key<br> * serialNumber CertificateSerialNumber }<br> * * ... The hash algorithm used for both these hashes, is identified in hashAlgorithm. serialNumber is the * serial number of the cert for which status is being requested. */ Date bestUpdate = null; BasicOCSPResp bestBasicOCSPResp = null; SingleResp bestSingleResp = null; final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(certificateToken, issuerCertificateToken); for (final BasicOCSPResp basicOCSPResp : containedOCSPResponses) { for (final SingleResp singleResp : basicOCSPResp.getResponses()) { if (DSSRevocationUtils.matches(certId, singleResp)) { final Date thisUpdate = singleResp.getThisUpdate(); if ((bestUpdate == null) || thisUpdate.after(bestUpdate)) { bestBasicOCSPResp = basicOCSPResp; bestSingleResp = singleResp; bestUpdate = thisUpdate; } } } } if (bestBasicOCSPResp != null) { OCSPToken ocspToken = new OCSPToken(); ocspToken.setOrigin(RevocationOrigin.SIGNATURE); ocspToken.setBasicOCSPResp(bestBasicOCSPResp); ocspToken.setBestSingleResp(bestSingleResp); return ocspToken; } return null; }
From source file:io.netty.example.ocsp.OcspServerExample.java
License:Apache License
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"); }//w w w. j a v a 2 s. c om // 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(); } }
From source file:net.maritimecloud.pki.ocsp.OCSPClient.java
License:Open Source License
public CertStatus getCertificateStatus() throws OCSPValidationException { try {// w w w . java 2s. c o m if (null == url) { throw new OCSPValidationException("Certificate not validated by OCSP"); } byte[] encodedOcspRequest = generateOCSPRequest(issuer, certificate.getSerialNumber()).getEncoded(); HttpURLConnection httpConnection; httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestProperty("Content-Type", "application/ocsp-request"); httpConnection.setRequestProperty("Accept", "application/ocsp-response"); httpConnection.setDoOutput(true); try (DataOutputStream dataOut = new DataOutputStream( new BufferedOutputStream(httpConnection.getOutputStream()))) { dataOut.write(encodedOcspRequest); dataOut.flush(); } InputStream in = (InputStream) httpConnection.getContent(); if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new OCSPValidationException( "Received HTTP code != 200 [" + httpConnection.getResponseCode() + "]"); } OCSPResp ocspResponse = new OCSPResp(in); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); byte[] receivedNonce = basicResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnId() .getEncoded(); if (!Arrays.equals(receivedNonce, sentNonce)) { throw new OCSPValidationException("Nonce in ocsp response does not match nonce of ocsp request"); } X509CertificateHolder certHolder = basicResponse.getCerts()[0]; if (!basicResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) { if (!certHolder.isValidOn(Date.from(Instant.now()))) { throw new OCSPValidationException("Certificate is not valid today!"); } // Certificate must have a Key Purpose ID for authorized responders if (!ExtendedKeyUsage.fromExtensions(certHolder.getExtensions()) .hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning)) { throw new OCSPValidationException( "Certificate does not contain required extension (id_kp_OCSPSigning)"); } // Certificate must be issued by the same CA of the certificate that we are verifying if (!certHolder.isSignatureValid( new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) { throw new OCSPValidationException("Certificate is not signed by the same issuer"); } // Validate signature in OCSP response if (!basicResponse.isSignatureValid( new JcaContentVerifierProviderBuilder().setProvider("BC").build(certHolder))) { throw new OCSPValidationException("Could not validate OCSP response!"); } } else { if (!certHolder.isValidOn(Date.from(Instant.now()))) { throw new OCSPValidationException("Certificate is not valid today!"); } } // SCEE Certificate Policy (?) /*if (null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck) || null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck).getExtnId()) { throw new OCSPValidationException("Extension id_pkix_ocsp_nocheck not found in certificate"); }*/ SingleResp[] responses = basicResponse.getResponses(); if (responses[0].getCertID().getSerialNumber().equals(certificate.getSerialNumber())) { CertificateStatus status = responses[0].getCertStatus(); if (status == CertificateStatus.GOOD) { return CertStatus.GOOD; } else { if (status instanceof RevokedStatus) { revokedStatus = (RevokedStatus) status; return CertStatus.REVOKED; } else { return CertStatus.UNKNOWN; } } } else { throw new OCSPValidationException( "Serial number of certificate in response ocsp does not match certificate serial number"); } } catch (CertificateEncodingException | OperatorCreationException | OCSPException | IOException ex) { throw new OCSPValidationException("Unable to perform validation through OCSP (" + certificate.getSubjectX500Principal().getName() + ")", ex); } catch (CertException | CertificateException ex) { throw new OCSPValidationException("Unable to perform validation through OCSP (" + certificate.getSubjectX500Principal().getName() + ")", ex); } }
From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java
License:Apache License
/** * Gets the OCSP status for the specified subject and issuer certificates. * * @param ocspStatusKey status key/*from w w w . j a v a 2 s . c o m*/ * @return ocsp status */ private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) { final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate(); final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate(); // initialize the default status final OcspStatus ocspStatus = new OcspStatus(); ocspStatus.setVerificationStatus(VerificationStatus.Unknown); ocspStatus.setValidationStatus(ValidationStatus.Unknown); try { // prepare the request final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber(); final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider("BC").build(); final CertificateID certificateId = new CertificateID( calculatorProviderBuilder.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber); // generate the request final OCSPReqBuilder requestGenerator = new OCSPReqBuilder(); requestGenerator.addRequest(certificateId); // Create a nonce to avoid replay attack BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis()); Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray())); requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext })); final OCSPReq ocspRequest = requestGenerator.build(); // perform the request final Response response = getClientResponse(ocspRequest); // ensure the request was completed successfully if (Response.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) { logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus())); return ocspStatus; } // interpret the response OCSPResp ocspResponse = new OCSPResp(response.readEntity(InputStream.class)); // verify the response status switch (ocspResponse.getStatus()) { case OCSPRespBuilder.SUCCESSFUL: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful); break; case OCSPRespBuilder.INTERNAL_ERROR: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError); break; case OCSPRespBuilder.MALFORMED_REQUEST: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest); break; case OCSPRespBuilder.SIG_REQUIRED: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired); break; case OCSPRespBuilder.TRY_LATER: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater); break; case OCSPRespBuilder.UNAUTHORIZED: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized); break; default: ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown); break; } // only proceed if the response was successful if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) { logger.warn(String.format("OCSP request was unsuccessful (%s).", ocspStatus.getResponseStatus().toString())); return ocspStatus; } // ensure the appropriate response object final Object ocspResponseObject = ocspResponse.getResponseObject(); if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) { logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject)); return ocspStatus; } // get the response object final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); // attempt to locate the responder certificate final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts(); if (responderCertificates.length != 1) { logger.warn(String.format("Unexpected number of OCSP responder certificates: %s", responderCertificates.length)); return ocspStatus; } // get the responder certificate final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate( responderCertificates[0], issuerCertificate); if (trustedResponderCertificate != null) { // verify the response if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC") .build(trustedResponderCertificate.getPublicKey()))) { ocspStatus.setVerificationStatus(VerificationStatus.Verified); } else { ocspStatus.setVerificationStatus(VerificationStatus.Unverified); } } else { ocspStatus.setVerificationStatus(VerificationStatus.Unverified); } // validate the response final SingleResp[] responses = basicOcspResponse.getResponses(); for (SingleResp singleResponse : responses) { final CertificateID responseCertificateId = singleResponse.getCertID(); final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber(); if (responseSerialNumber.equals(subjectSerialNumber)) { Object certStatus = singleResponse.getCertStatus(); // interpret the certificate status if (CertificateStatus.GOOD == certStatus) { ocspStatus.setValidationStatus(ValidationStatus.Good); } else if (certStatus instanceof RevokedStatus) { ocspStatus.setValidationStatus(ValidationStatus.Revoked); } else { ocspStatus.setValidationStatus(ValidationStatus.Unknown); } } } } catch (final OCSPException | IOException | ProcessingException | OperatorCreationException e) { logger.error(e.getMessage(), e); } catch (CertificateException e) { e.printStackTrace(); } return ocspStatus; }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
/** * Tests creating an OCSP response using the root CA cert. * Tests using both SHA1, SHA256 and SHA224 CertID. SHA1 and SHA256 should work, while SHA224 should give an error. *///w w w. ja v a 2s.c o m @Test public void testGetOcspResponseSanity() throws Exception { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, caCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", 0, response.getStatus()); BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); SingleResp[] singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", caCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); // Do the same test but using SHA256 as hash algorithm for CertID gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID( new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)), caCertificate, caCertificate.getSerialNumber())); extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); req = gen.build(); responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", 0, response.getStatus()); basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", caCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); // Do the same test but using SHA224 as hash algorithm for CertID to see that we get an error back gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID( new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224)), caCertificate, caCertificate.getSerialNumber())); extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); req = gen.build(); responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); response = new OCSPResp(responseBytes); // Response status 1 means malformed request assertEquals("Response status not zero.", 1, response.getStatus()); basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertNull("No response object for this unsigned error response.", basicOcspResponse); }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
/** * Tests with nonexistingisrevoked/* w ww. j av a 2 s . c om*/ */ @Test public void testNonExistingIsRevoked() throws Exception { String originalValue = cesecoreConfigurationProxySession .getConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_REVOKED); cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_REVOKED, "true"); try { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); // Now remove the certificate internalCertificateStoreSession.removeCertificate(ocspCertificate.getSerialNumber()); ocspResponseGeneratorTestSession.reloadOcspSigningCache(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession.getOcspResponse(req.getEncoded(), null, "", "", new StringBuffer("http://foo.com"), auditLogger, transactionLogger).getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); SingleResp[] singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); responseBytes = ocspResponseGeneratorSession.getOcspResponse(req.getEncoded(), null, "", "", new StringBuffer("http://foo.com"), auditLogger, transactionLogger).getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); // Assert that status is revoked CertificateStatus status = singleResponses[0].getCertStatus(); assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus); // Set ocsp.nonexistingisgood=true, veryify that answer comes out okay. String originalNoneExistingIsGood = cesecoreConfigurationProxySession .getConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD); cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD, "true"); try { responseBytes = ocspResponseGeneratorSession.getOcspResponse(req.getEncoded(), null, "", "", new StringBuffer("http://foo.com"), auditLogger, transactionLogger).getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse.isSignatureValid( new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); } finally { cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_GOOD, originalNoneExistingIsGood); } } finally { cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.NONE_EXISTING_IS_REVOKED, originalValue); } }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
@Test public void testGetOcspResponseWithOcspCertificate() throws Exception { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build();//from ww w . j a va 2 s . com final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); SingleResp[] singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); }