Example usage for org.bouncycastle.asn1.ocsp OCSPResponseStatus SUCCESSFUL

List of usage examples for org.bouncycastle.asn1.ocsp OCSPResponseStatus SUCCESSFUL

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.ocsp OCSPResponseStatus SUCCESSFUL.

Prototype

int SUCCESSFUL

To view the source code for org.bouncycastle.asn1.ocsp OCSPResponseStatus SUCCESSFUL.

Click Source Link

Usage

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. jav  a 2 s  . co 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:ee.ria.xroad.signer.certmanager.OcspClient.java

License:Open Source License

private static void verifyResponse(OCSPResp response) throws Exception {
    int responseStatus = response.getStatus();

    if (responseStatus == OCSPResponseStatus.SUCCESSFUL) {
        return;/*from   ww  w.j  av a 2  s.  co m*/
    }

    if (responseStatus == OCSPResponseStatus.SIG_REQUIRED) {
        throw new OCSPException("OCSP responder requires request to be signed");
    }

    throw new OCSPException("Invalid OCSP response status: " + responseStatus);
}

From source file:eu.europa.ec.markt.dss.DSSRevocationUtils.java

License:Open Source License

/**
 * Convert a BasicOCSPResp in OCSPResp (connection status is set to SUCCESSFUL).
 *
 * @param basicOCSPResp//from  www  .ja  v a2 s  .com
 * @return
 */
public static final OCSPResp fromBasicToResp(final byte[] basicOCSPResp) {

    final OCSPResponseStatus responseStatus = new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL);
    final DEROctetString derBasicOCSPResp = new DEROctetString(basicOCSPResp);
    final ResponseBytes responseBytes = new ResponseBytes(OCSPObjectIdentifiers.id_pkix_ocsp_basic,
            derBasicOCSPResp);
    final OCSPResponse ocspResponse = new OCSPResponse(responseStatus, responseBytes);
    final OCSPResp ocspResp = new OCSPResp(ocspResponse);
    //!!! todo to be checked: System.out.println("===> RECREATED: " + ocspResp.hashCode());
    return ocspResp;
}

From source file:eu.europa.ec.markt.dss.validation.ocsp.OCSPUtils.java

License:Open Source License

/**
 * Convert a BasicOCSPResp in OCSPResp (connection status is set to SUCCESSFUL).
 * //w  ww .java 2 s. c  o m
 * @param basicOCSPResp
 * @return
 */
public static final OCSPResp fromBasicToResp(byte[] basicOCSPResp) {
    OCSPResponse response = new OCSPResponse(new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL),
            new ResponseBytes(OCSPObjectIdentifiers.id_pkix_ocsp_basic, new DEROctetString(basicOCSPResp)));
    OCSPResp resp = new OCSPResp(response);
    return resp;
}

From source file:eu.europa.esig.dss.DSSRevocationUtils.java

License:Open Source License

/**
 * Convert a BasicOCSPResp in OCSPResp (connection status is set to
 * SUCCESSFUL).//from  www  .jav  a 2  s.  c  om
 *
 * @param basicOCSPResp
 * @return
 */
public static final OCSPResp fromBasicToResp(final byte[] basicOCSPResp) {
    final OCSPResponseStatus responseStatus = new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL);
    final DEROctetString derBasicOCSPResp = new DEROctetString(basicOCSPResp);
    final ResponseBytes responseBytes = new ResponseBytes(OCSPObjectIdentifiers.id_pkix_ocsp_basic,
            derBasicOCSPResp);
    final OCSPResponse ocspResponse = new OCSPResponse(responseStatus, responseBytes);
    final OCSPResp ocspResp = new OCSPResp(ocspResponse);
    // !!! todo to be checked: System.out.println("===> RECREATED: " +
    // ocspResp.hashCode());
    return ocspResp;
}

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  ww  .  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.sf.dsig.verify.OCSPHelper.java

License:Apache License

/**
 * Check with OCSP protocol whether a certificate is valid
 * /*from ww  w.j  a  va2  s  . c  o  m*/
 * @param certificate an {@link X509Certificate} object
 * @return true if the certificate is valid; false otherwise
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an OCSP related error occurs
 */
public boolean isValid(X509Certificate certificate) throws NetworkAccessException, VerificationException {
    PostMethod post = null;

    try {
        CertificateID cid = new CertificateID(CertificateID.HASH_SHA1, caCertificate,
                certificate.getSerialNumber());

        OCSPReqGenerator gen = new OCSPReqGenerator();
        gen.addRequest(cid);

        // Nonce
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Vector oids = new Vector();
        Vector values = new Vector();
        oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
        values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
        values.add(new X509Extension(false,
                new DEROctetString(new BigInteger("041063FAB2B54CF1ED014F9DF7C70AACE575", 16).toByteArray())));
        gen.setRequestExtensions(new X509Extensions(oids, values));

        // Requestor name - not really required, but added for completeness
        //          gen.setRequestorName(
        //                  new GeneralName(
        //                          new X509Name(
        //                                  certificate.getSubjectX500Principal().getName())));

        logger.debug("Generating OCSP request" + "; serialNumber=" + certificate.getSerialNumber().toString(16)
                + ", nonce=" + nonce.toString(16) + ", caCertificate.subjectName="
                + caCertificate.getSubjectX500Principal().getName());

        // TODO Need to call the generate(...) method, that signs the 
        // request. Which means, need to have a keypair for that, too
        OCSPReq req = gen.generate();

        // First try finding the OCSP access location in the X.509 certificate
        String uriAsString = getOCSPAccessLocationUri(certificate);

        // If not found, try falling back to the default
        if (uriAsString == null) {
            uriAsString = defaultOcspAccessLocation;
        }

        // If still null, bail out
        if (uriAsString == null) {
            throw new ConfigurationException(
                    "OCSP AccessLocation not found on certificate, and no default set");
        }

        HostConfiguration config = getHostConfiguration();

        post = new PostMethod(uriAsString);
        post.setRequestHeader("Content-Type", "application/ocsp-request");
        post.setRequestHeader("Accept", "application/ocsp-response");
        post.setRequestEntity(new ByteArrayRequestEntity(req.getEncoded()));

        getHttpClient().executeMethod(config, post);

        logger.debug("HTTP POST executed" + "; authorityInfoAccessUri=" + uriAsString + ", statusLine="
                + post.getStatusLine());

        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new NetworkAccessException("HTTP GET failed; statusLine=" + post.getStatusLine());
        }

        byte[] responseBodyBytes = post.getResponseBody();

        OCSPResp ocspRes = new OCSPResp(responseBodyBytes);
        if (ocspRes.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
            // One possible exception is the use of a wrong CA certificate
            throw new ConfigurationException("OCSP request failed; possibly wrong issuer/user certificate"
                    + "; status=" + ocspRes.getStatus());
        }

        BasicOCSPResp res = (BasicOCSPResp) ocspRes.getResponseObject();
        SingleResp[] responses = res.getResponses();
        SingleResp response = responses[0];

        CertificateStatus status = (CertificateStatus) response.getCertStatus();
        // Normal OCSP protocol allows a null status
        return status == null || status == CertificateStatus.GOOD;
    } catch (IOException e) {
        throw new NetworkAccessException("I/O error occured", e);
    } catch (OCSPException e) {
        throw new VerificationException("Error while following OCSP protocol", e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspSignedHttpTest.java

License:Open Source License

/** Tests ocsp message
 * @throws Exception error/*w  w  w  . ja  va  2s .  com*/
 */
@Test
public void test01OcspGood() throws Exception {
    log.trace(">test01OcspGood()");

    // find a CA (TestCA?) create a user and generate his cert
    // send OCSP req to server and get good response
    // change status of cert to bad status
    // send OCSP req and get bad status
    // (send crap message and get good error)

    // Make user that we know...
    boolean userExists = endEntityManagementSession.existsUser(END_ENTITY_NAME);
    if (!userExists) {
        endEntityManagementSession.addUser(admin, END_ENTITY_NAME, "foo123", "C=SE,O=AnaTom,CN=OCSPTest", null,
                "ocsptest@anatom.se", false, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityTypes.ENDUSER.toEndEntityType(),
                SecConst.TOKEN_SOFT_PEM, 0, caid);
        log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest");
    } else {
        log.debug("User ocsptest already exists.");
        EndEntityInformation userData = new EndEntityInformation(END_ENTITY_NAME, "C=SE,O=AnaTom,CN=OCSPTest",
                caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW,
                EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0,
                null);
        userData.setPassword("foo123");
        endEntityManagementSession.changeUser(admin, userData, false);
        log.debug("Reset status to NEW");
    }
    try {
        // Generate certificate for the new user
        KeyPair keys = KeyTools.genKeys("512", "RSA");

        // user that we know exists...
        ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "ocsptest", "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        assertNotNull("Failed to create a certificate", ocspTestCert);

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
                ocspTestCert.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));
        X509CertificateHolder chain[] = new JcaX509CertificateHolder[2];
        chain[0] = new JcaX509CertificateHolder(ocspTestCert);
        chain[1] = new JcaX509CertificateHolder(cacert);
        gen.setRequestorName(chain[0].getSubject());
        OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain);
        // Send the request and receive a singleResponse
        SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789",
                OCSPResponseStatus.SUCCESSFUL, 200);
        assertEquals("Number of of SingResps should be 1.", 1, singleResps.length);
        SingleResp singleResp = singleResps[0];

        CertificateID certId = singleResp.getCertID();
        assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
                ocspTestCert.getSerialNumber());
        Object status = singleResp.getCertStatus();
        assertEquals("Status is not null (good)", null, status);

        // Try with an unsigned request, we should get a status code 5 back from the server (signature required)
        req = gen.build();
        // Send the request and receive a singleResponse, this response should have error code SIGNATURE_REQUIRED
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.SIG_REQUIRED, 200);
        assertNull(singleResps);

        // sign with a keystore where the CA-certificate is not known
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        ByteArrayInputStream fis = new ByteArrayInputStream(ks3);
        store.load(fis, "foo123".toCharArray());
        Certificate[] certs = KeyTools.getCertChain(store, "privateKey");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should have error code UNAUTHORIZED (6)
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.UNAUTHORIZED, 200);
        assertNull(singleResps);
    } finally {
        endEntityManagementSession.deleteUser(roleMgmgToken, END_ENTITY_NAME);
    }
    log.trace("<test01OcspGood()");
}

From source file:org.signserver.test.utils.builders.ocsp.OCSPResponseBuilder.java

License:Open Source License

public OCSPResponseStatus getResponseStatus() {
    if (responseStatus == null) {
        responseStatus = new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL);
    }/* www.  java  2  s .c  o  m*/
    return responseStatus;
}

From source file:org.signserver.validationservice.server.ValidationUtils.java

License:Open Source License

/**
 * Sends a request to the OCSP responder and returns the results.
 *
 * Note: Based on code from the EJBCA ValidationTool.
 *
 * @param url of the OCSP responder//from w ww . j ava 2  s  . c  om
 * @param request to send
 * @return An OCSPResponse object filled with information about the response
 * @throws IOException in case of networking related errors
 * @throws OCSPException in case of error parsing the response
 */
public static OCSPResponse queryOCSPResponder(URL url, OCSPReq request) throws IOException, OCSPException {
    final OCSPResponse result = new OCSPResponse();

    final HttpURLConnection con;
    final URLConnection urlCon = url.openConnection();
    if (!(urlCon instanceof HttpURLConnection)) {
        throw new IOException("Unsupported protocol in URL: " + url);
    }
    con = (HttpURLConnection) urlCon;

    // POST the OCSP request
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/ocsp-request");
    OutputStream os = null;
    try {
        os = con.getOutputStream();
        os.write(request.getEncoded());
    } finally {
        if (os != null) {
            os.close();
        }
    }

    result.setHttpReturnCode(con.getResponseCode());
    if (result.getHttpReturnCode() != 200) {
        if (result.getHttpReturnCode() == 401) {
            result.setError(OCSPResponse.Error.httpUnauthorized);
        } else {
            result.setError(OCSPResponse.Error.unknown);
        }
        return result;
    }

    OCSPResp response = null;
    InputStream in = null;
    try {
        in = con.getInputStream();
        if (in != null) {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            int b;
            while ((b = in.read()) != -1) {
                bout.write(b);
            }
            response = new OCSPResp(bout.toByteArray());
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {
            } // NOPMD
        }
    }

    if (response == null) {
        result.setError(OCSPResponse.Error.noResponse);
        return result;
    }
    result.setResp(response);

    if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
        result.setError(OCSPResponse.Error.fromBCOCSPResponseStatus(response.getStatus()));
        return result;
    }

    final BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    result.setResponseObject(brep);
    if (brep == null) {
        result.setError(OCSPResponse.Error.noResponse);
        return result;
    }

    final RespID id = brep.getResponderId();
    final DERTaggedObject to = (DERTaggedObject) id.toASN1Object().toASN1Object();
    final RespID respId;

    final X509CertificateHolder[] chain = brep.getCerts();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    X509Certificate signerCertificate;
    try {
        signerCertificate = converter.getCertificate(chain[0]);
    } catch (CertificateException ex) {
        throw new IOException("Could not convert certificate: " + ex.getMessage());
    }
    result.setSignerCertificate(signerCertificate);

    if (to.getTagNo() == 1) {
        // This is Name
        respId = new JcaRespID(signerCertificate.getSubjectX500Principal());
    } else {
        // This is KeyHash
        final PublicKey signerPub = signerCertificate.getPublicKey();
        try {
            respId = new JcaRespID(signerPub,
                    new JcaDigestCalculatorProviderBuilder().build().get(RespID.HASH_SHA1));
        } catch (OperatorCreationException ex) {
            throw new IOException("Could not create respId: " + ex.getMessage());
        }
    }
    if (!id.equals(respId)) {
        // Response responderId does not match signer certificate responderId!
        result.setError(OCSPResponse.Error.invalidSignerId);
    }

    result.setIssuerDN(signerCertificate.getIssuerX500Principal());

    if (result.getError() == null) {
        result.setError(OCSPResponse.Error.responseSuccess);
    }

    return result;
}