Example usage for org.bouncycastle.cert.ocsp OCSPResp OCSPResp

List of usage examples for org.bouncycastle.cert.ocsp OCSPResp OCSPResp

Introduction

In this page you can find the example usage for org.bouncycastle.cert.ocsp OCSPResp OCSPResp.

Prototype

private OCSPResp(ASN1InputStream aIn) throws IOException 

Source Link

Usage

From source file:be.fedict.trust.ocsp.OfflineOcspRepository.java

License:Open Source License

/**
 * Main constructor//from  ww  w  . j a va2 s  . c o m
 * 
 * @param encodedOcspResponses
 *            the list of encoded OCSP responses that can be queried.
 * @throws IOException
 */
public OfflineOcspRepository(List<byte[]> encodedOcspResponses) throws IOException {

    this.ocspResponses = new LinkedList<>();
    for (byte[] encodedOcspResponse : encodedOcspResponses) {
        OCSPResp ocspResponse = new OCSPResp(encodedOcspResponse);
        ocspResponses.add(ocspResponse);
    }
}

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);//ww  w .ja v a 2 s.co  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:com.itextpdf.signatures.LtvVerifier.java

License:Open Source License

/**
 * Gets OCSP responses from the Document Security Store.
 * @return   a list of BasicOCSPResp objects
 * @throws IOException/*from  www . jav a  2s. com*/
 * @throws GeneralSecurityException
 */
public List<BasicOCSPResp> getOCSPResponsesFromDSS() throws IOException, GeneralSecurityException {
    List<BasicOCSPResp> ocsps = new ArrayList<>();
    if (dss == null)
        return ocsps;
    PdfArray ocsparray = dss.getAsArray(PdfName.OCSPs);
    if (ocsparray == null)
        return ocsps;
    for (int i = 0; i < ocsparray.size(); i++) {
        PdfStream stream = ocsparray.getAsStream(i);
        OCSPResp ocspResponse = new OCSPResp(stream.getBytes());
        if (ocspResponse.getStatus() == 0)
            try {
                ocsps.add((BasicOCSPResp) ocspResponse.getResponseObject());
            } catch (OCSPException e) {
                throw new GeneralSecurityException(e.toString());
            }
    }
    return ocsps;
}

From source file:com.itextpdf.signatures.OcspClientBouncyCastle.java

License:Open Source License

private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url)
        throws GeneralSecurityException, OCSPException, IOException, OperatorException {
    if (checkCert == null || rootCert == null)
        return null;
    if (url == null) {
        url = CertificateUtil.getOCSPURL(checkCert);
    }/*from ww w.j a  v  a  2  s. c o m*/
    if (url == null)
        return null;
    LOGGER.info("Getting OCSP from " + url);
    OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber());
    byte[] array = request.getEncoded();
    URL urlt = new URL(url);
    InputStream in = SignUtils.getHttpResponseForOcspRequest(array, urlt);
    return new OCSPResp(StreamUtil.inputStreamToArray(in));
}

From source file:com.itextpdf.text.pdf.security.LtvVerifier.java

License:Open Source License

/**
 * Gets OCSP responses from the Document Security Store.
 * @return   a list of BasicOCSPResp objects
 * @throws IOException//from  w w  w .j  a  va 2 s.co m
 * @throws GeneralSecurityException
 */
public List<BasicOCSPResp> getOCSPResponsesFromDSS() throws IOException, GeneralSecurityException {
    List<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>();
    if (dss == null)
        return ocsps;
    PdfArray ocsparray = dss.getAsArray(PdfName.OCSPS);
    if (ocsparray == null)
        return ocsps;
    for (int i = 0; i < ocsparray.size(); i++) {
        PRStream stream = (PRStream) ocsparray.getAsStream(i);
        OCSPResp ocspResponse = new OCSPResp(PdfReader.getStreamBytes(stream));
        if (ocspResponse.getStatus() == 0)
            try {
                ocsps.add((BasicOCSPResp) ocspResponse.getResponseObject());
            } catch (OCSPException e) {
                throw new GeneralSecurityException(e);
            }
    }
    return ocsps;
}

From source file:com.itextpdf.text.pdf.security.OcspClientBouncyCastle.java

License:Open Source License

private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url)
        throws GeneralSecurityException, OCSPException, IOException, OperatorException {
    if (checkCert == null || rootCert == null)
        return null;
    if (url == null) {
        url = CertificateUtil.getOCSPURL(checkCert);
    }//from w w w.jav a 2  s  . co  m
    if (url == null)
        return null;
    LOGGER.info("Getting OCSP from " + url);
    OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber());
    byte[] array = request.getEncoded();
    URL urlt = new URL(url);
    HttpURLConnection con = (HttpURLConnection) urlt.openConnection();
    con.setRequestProperty("Content-Type", "application/ocsp-request");
    con.setRequestProperty("Accept", "application/ocsp-response");
    con.setDoOutput(true);
    OutputStream out = con.getOutputStream();
    DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
    dataOut.write(array);
    dataOut.flush();
    dataOut.close();
    if (con.getResponseCode() / 100 != 2) {
        throw new IOException(
                MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode()));
    }
    //Get Response
    InputStream in = (InputStream) con.getContent();
    return new OCSPResp(StreamUtil.inputStreamToArray(in));
}

From source file:com.swisscom.ais.itext.PDF.java

License:Open Source License

/** 
 * Add external revocation information to DSS Dictionary, to enable Long Term Validation (LTV) in Adobe Reader
 * //from  ww w  . ja  v a2 s.c  o  m
 * @param ocspArr List of OCSP Responses as base64 encoded String
 * @param crlArr  List of CRLs as base64 encoded String
 * @throws Exception 
 */
public void addValidationInformation(ArrayList<String> ocspArr, ArrayList<String> crlArr) throws Exception {
    if (ocspArr == null && crlArr == null)
        return;

    PdfReader reader = new PdfReader(outputFilePath);

    // Check if source pdf is not protected by a certification
    if (reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED)
        throw new Exception(
                "Could not apply revocation information (LTV) to the DSS Dictionary. Document contains a certification that does not allow any changes.");

    Collection<byte[]> ocspColl = new ArrayList<byte[]>();
    Collection<byte[]> crlColl = new ArrayList<byte[]>();

    // Decode each OCSP Response (String of base64 encoded form) and add it to the Collection (byte[])
    if (ocspArr != null) {
        for (String ocspBase64 : ocspArr) {
            OCSPResp ocspResp = new OCSPResp(new ByteArrayInputStream(Base64.decode(ocspBase64)));
            BasicOCSPResp basicResp = (BasicOCSPResp) ocspResp.getResponseObject();

            if (Soap._debugMode) {
                System.out.println("\nEmbedding OCSP Response...");
                System.out.println("Status                : " + ((ocspResp.getStatus() == 0) ? "GOOD" : "BAD"));
                System.out.println("Produced at           : " + basicResp.getProducedAt());
                System.out.println("This Update           : " + basicResp.getResponses()[0].getThisUpdate());
                System.out.println("Next Update           : " + basicResp.getResponses()[0].getNextUpdate());
                System.out.println("X509 Cert Issuer      : " + basicResp.getCerts()[0].getIssuer());
                System.out.println("X509 Cert Subject     : " + basicResp.getCerts()[0].getSubject());
                System.out.println(
                        "Responder ID X500Name : " + basicResp.getResponderId().toASN1Object().getName());
                System.out.println("Certificate ID        : "
                        + basicResp.getResponses()[0].getCertID().getSerialNumber().toString() + " ("
                        + basicResp.getResponses()[0].getCertID().getSerialNumber().toString(16).toUpperCase()
                        + ")");
            }

            ocspColl.add(basicResp.getEncoded()); // Add Basic OCSP Response to Collection (ASN.1 encoded representation of this object)
        }
    }

    // Decode each CRL (String of base64 encoded form) and add it to the Collection (byte[])
    if (crlArr != null) {
        for (String crlBase64 : crlArr) {
            X509CRL x509crl = (X509CRL) CertificateFactory.getInstance("X.509")
                    .generateCRL(new ByteArrayInputStream(Base64.decode(crlBase64)));

            if (Soap._debugMode) {
                System.out.println("\nEmbedding CRL...");
                System.out.println("IssuerDN                    : " + x509crl.getIssuerDN());
                System.out.println("This Update                 : " + x509crl.getThisUpdate());
                System.out.println("Next Update                 : " + x509crl.getNextUpdate());
                System.out.println(
                        "No. of Revoked Certificates : " + ((x509crl.getRevokedCertificates() == null) ? "0"
                                : x509crl.getRevokedCertificates().size()));
            }

            crlColl.add(x509crl.getEncoded()); // Add CRL to Collection (ASN.1 DER-encoded form of this CRL)
        }
    }

    byteArrayOutputStream = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, byteArrayOutputStream, '\0', true);
    LtvVerification validation = stamper.getLtvVerification();

    // Add the CRL/OCSP validation information to the DSS Dictionary
    boolean addVerification = false;
    for (String sigName : stamper.getAcroFields().getSignatureNames()) {
        addVerification = validation.addVerification(sigName, // Signature Name
                ocspColl, // OCSP
                crlColl, // CRL
                null // certs
        );
    }

    validation.merge(); // Merges the validation with any validation already in the document or creates a new one.

    stamper.close();
    reader.close();

    // Save to (same) file
    OutputStream outputStream = new FileOutputStream(outputFilePath);
    byteArrayOutputStream.writeTo(outputStream);

    if (Soap._debugMode) {
        if (addVerification)
            System.out.println("\nOK merging LTV validation information to " + outputFilePath);
        else
            System.out.println("\nFAILED merging LTV validation information to " + outputFilePath);
    }

    byteArrayOutputStream.close();
    outputStream.close();
}

From source file:com.tremolosecurity.proxy.auth.ssl.OCSP.java

License:Apache License

@Override
public boolean isValid(X509Certificate cert, X509Certificate issuer) {
    try {/*from   w  ww.  ja v  a2 s  . c  om*/
        OCSPReq ocspRequest = generateOcspRequest(issuer, cert.getSerialNumber());
        URL url = new URL(this.url);
        HttpURLConnection url_con = (HttpURLConnection) url.openConnection();

        url_con.setDoOutput(true);
        url_con.connect();
        OutputStream os = url_con.getOutputStream();
        os.write(ocspRequest.getEncoded());

        InputStream is = url_con.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int len = 0;

        do {
            len = is.read(buffer);
            if (len > 0) {
                baos.write(buffer, 0, len);
            }
        } while (len > 0);

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

        OCSPResp ocspResponse = new OCSPResp(bais);

        BasicOCSPResp resp = (BasicOCSPResp) ocspResponse.getResponseObject();

        //System.err.println(resp.getResponses()[0].getCertStatus());

        return resp.getResponses()[0].getCertStatus() == null || (!(resp.getResponses()[0]
                .getCertStatus() instanceof org.bouncycastle.cert.ocsp.RevokedStatus));

    } catch (Exception e) {
        logger.error("Error validating certificate", e);
        return false;
    }
}

From source file:controller.CCInstance.java

License:Open Source License

private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert)
        throws GeneralSecurityException, OCSPException, IOException, OperatorException {
    if (checkCert == null || rootCert == null) {
        return null;
    }/*from  w w w.  j a v a  2s .c o  m*/
    String url = CertificateUtil.getOCSPURL(checkCert);

    if (url == null) {
        return null;
    }
    try {
        OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber());
        byte[] array = request.getEncoded();
        URL urlt = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlt.openConnection();
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        con.setRequestProperty("Accept", "application/ocsp-response");
        con.setDoOutput(true);

        OutputStream out = con.getOutputStream();
        try (DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out))) {
            dataOut.write(array);
            dataOut.flush();
        }

        if (con.getResponseCode() / 100 != 2) {
            throw new IOException(
                    MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode()));
        }
        //Get Response
        InputStream in = (InputStream) con.getContent();
        return new OCSPResp(in);
    } catch (Exception e) {
        return null;
    }
}

From source file:ec.rubrica.ocsp.ValidadorOCSP.java

License:Open Source License

public static void check(X509Certificate issuerCert, X509Certificate x509Cert)
        throws OcspValidationException, OcspTimeoutException {
    try {//from ww w  . j a v a2 s.  co  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);
    }
}