Search in sources :

Example 6 with OCSPReqBuilder

use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project module-ballerina-http by ballerina-platform.

the class OCSPVerifier method generateOCSPRequest.

/**
 * This method generates an OCSP Request to be sent to an OCSP authority access endpoint.
 *
 * @param issuerCert the Issuer's certificate of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request.
 * @throws CertificateVerificationException if any error occurs while generating ocsp request.
 */
public static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws CertificateVerificationException {
    // Programatically adding Bouncy Castle as the security provider. So no need to manually set. Once the programme
    // is over security provider will also be removed.
    Security.addProvider(new BouncyCastleProvider());
    try {
        byte[] issuerCertEnc = issuerCert.getEncoded();
        X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(Constants.BOUNCY_CASTLE_PROVIDER).build();
        // CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560.
        CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, serialNumber);
        // basic request generation with nonce.
        OCSPReqBuilder builder = new OCSPReqBuilder();
        builder.addRequest(id);
        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent re-play attacks. As the name implies,
        // the nonce value is something that the client should only use once during a reasonably small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        // to create the request Extension
        builder.setRequestExtensions(new Extensions(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce.toByteArray()))));
        return builder.build();
    } catch (OCSPException | OperatorCreationException | IOException | CertificateEncodingException e) {
        throw new CertificateVerificationException("Cannot generate OCSP Request with the given certificate", e);
    }
}
Also used : CertificateID(org.bouncycastle.cert.ocsp.CertificateID) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) Extension(org.bouncycastle.asn1.x509.Extension) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CertificateVerificationException(io.ballerina.stdlib.http.transport.contractimpl.common.certificatevalidation.CertificateVerificationException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 7 with OCSPReqBuilder

use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project eblocker by eblocker.

the class OcspCache method createOcspRequest.

private OCSPReq createOcspRequest(X509Certificate issuerCertificate, BigInteger serialNumber) throws OcspException {
    try {
        X509CertificateHolder holder = new X509CertificateHolder(issuerCertificate.getEncoded());
        CertificateID id = new CertificateID(digestCalculatorProvider.get(CertificateID.HASH_SHA1), holder, serialNumber);
        return new OCSPReqBuilder().addRequest(id).build();
    } catch (CertificateEncodingException | OperatorCreationException | IOException | OCSPException e) {
        throw new OcspException("creating ocsp request failed: ", e);
    }
}
Also used : CertificateID(org.bouncycastle.cert.ocsp.CertificateID) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder)

Example 8 with OCSPReqBuilder

use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project ddf by codice.

the class OcspChecker method generateOcspRequest.

/**
 * Creates an {@link OCSPReq} to send to the OCSP server for the given certificate.
 *
 * @param cert - the certificate to verify
 * @return the created OCSP request
 * @throws OcspCheckerException after posting an alert to the admin console, if any error occurs
 */
@VisibleForTesting
OCSPReq generateOcspRequest(Certificate cert) throws OcspCheckerException {
    try {
        X509CertificateHolder issuerCert = resolveIssuerCertificate(cert);
        JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
        DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
        DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
        CertificateID certId = new CertificateID(digestCalculator, issuerCert, cert.getSerialNumber().getValue());
        OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
        ocspReqGenerator.addRequest(certId);
        return ocspReqGenerator.build();
    } catch (OCSPException | OperatorCreationException e) {
        throw new OcspCheckerException("Unable to create an OCSP request." + NOT_VERIFIED_MSG, e);
    }
}
Also used : DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 9 with OCSPReqBuilder

use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project oxAuth by GluuFederation.

the class OCSPCertificateVerifier method generateOCSPRequest.

private OCSPReq generateOCSPRequest(CertificateID certificateId) throws OCSPException, OperatorCreationException, CertificateEncodingException {
    OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
    ocspReqGenerator.addRequest(certificateId);
    OCSPReq ocspReq = ocspReqGenerator.build();
    return ocspReq;
}
Also used : OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder)

Example 10 with OCSPReqBuilder

use of org.bouncycastle.cert.ocsp.OCSPReqBuilder in project nifi by apache.

the class OcspCertificateValidator method getOcspStatus.

/**
 * Gets the OCSP status for the specified subject and issuer certificates.
 *
 * @param ocspStatusKey status key
 * @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;
}
Also used : CertificateException(java.security.cert.CertificateException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ProcessingException(javax.ws.rs.ProcessingException) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Extension(org.bouncycastle.asn1.x509.Extension) Response(javax.ws.rs.core.Response) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)

Aggregations

OCSPReqBuilder (org.bouncycastle.cert.ocsp.OCSPReqBuilder)18 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)15 IOException (java.io.IOException)10 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)9 Extension (org.bouncycastle.asn1.x509.Extension)8 Extensions (org.bouncycastle.asn1.x509.Extensions)8 BigInteger (java.math.BigInteger)7 DEROctetString (org.bouncycastle.asn1.DEROctetString)7 OCSPException (org.bouncycastle.cert.ocsp.OCSPException)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)6 OCSPReq (org.bouncycastle.cert.ocsp.OCSPReq)5 CertificateEncodingException (java.security.cert.CertificateEncodingException)4 X509Certificate (java.security.cert.X509Certificate)4 DigestCalculatorProvider (org.bouncycastle.operator.DigestCalculatorProvider)4 CertificateException (java.security.cert.CertificateException)3 ArrayList (java.util.ArrayList)3 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)3 OCSPResp (org.bouncycastle.cert.ocsp.OCSPResp)3 InputStream (java.io.InputStream)2