Example usage for org.bouncycastle.cert.ocsp BasicOCSPResp getResponses

List of usage examples for org.bouncycastle.cert.ocsp BasicOCSPResp getResponses

Introduction

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

Prototype

public SingleResp[] getResponses() 

Source Link

Usage

From source file:controller.CCInstance.java

License:Open Source License

public final ArrayList<SignatureValidation> validatePDF(final String file, final ValidationListener vl)
        throws IOException, DocumentException, GeneralSecurityException {
    this.validating = true;

    final PdfReader reader = new PdfReader(file);
    final AcroFields af = reader.getAcroFields();
    final ArrayList names = af.getSignatureNames();
    final ArrayList<SignatureValidation> validateList = new ArrayList<>();
    X509Certificate x509c = null;

    Security.setProperty("ocsp.enable", "true");
    System.setProperty("com.sun.security.enableCRLDP", "true");

    boolean nextValid = true;

    for (Object o : names) {
        if (!validating) {
            return null;
        }/*from   w w w  . j  a va 2  s .  c  o m*/

        final String name = (String) o;
        final PdfPKCS7 pk = af.verifySignature(name, "BC");
        final Certificate pkc[] = pk.getCertificates();
        x509c = (X509Certificate) pkc[pkc.length - 1];

        final Certificate[] aL = pkc;//getCompleteCertificateChain(x509c);

        if (null == aL || 0 == aL.length) {
            return null;
        }

        CertificateStatus ocspCertificateStatus = CertificateStatus.UNCHECKED;

        BasicOCSPResp ocspResp = pk.getOcsp();
        if (null != ocspResp && pk.isRevocationValid()) {
            for (SingleResp singleResp : ocspResp.getResponses()) {
                if (null == singleResp.getCertStatus()) {
                    ocspCertificateStatus = CertificateStatus.OK;
                } else if (singleResp.getCertStatus() instanceof RevokedStatus) {
                    if (ocspResp.getProducedAt()
                            .before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
                        ocspCertificateStatus = CertificateStatus.OK;
                    } else {
                        ocspCertificateStatus = CertificateStatus.REVOKED;
                    }
                } else if (singleResp.getCertStatus() instanceof UnknownStatus) {
                    ocspCertificateStatus = CertificateStatus.UNKNOWN;
                }
            }
        }

        CertificateStatus crlCertificateStatus = CertificateStatus.UNCHECKED;
        Collection<CRL> crlResp = pk.getCRLs();
        if (null != crlResp) {
            boolean revoked = false;
            for (CRL crl : crlResp) {
                if (crl.isRevoked(x509c)) {
                    revoked = true;
                }
            }
            crlCertificateStatus = revoked ? CertificateStatus.REVOKED : CertificateStatus.OK;
        }

        if (ocspCertificateStatus.equals(CertificateStatus.UNCHECKED)
                && crlCertificateStatus.equals(CertificateStatus.UNCHECKED)) {
            if (pkc.length == 1) {
                Certificate[] completeChain = getCompleteTrustedCertificateChain(x509c);
                if (completeChain.length == 1) {
                    ocspCertificateStatus = CertificateStatus.UNCHAINED;
                } else {
                    ocspCertificateStatus = CertificateStatus.CHAINED_LOCALLY;
                }
            }
        }

        final TimeStampToken tst = pk.getTimeStampToken();
        boolean validTimestamp = false;
        if (null != tst) {
            final boolean hasTimestamp = pk.verifyTimestampImprint();
            validTimestamp = hasTimestamp && CertificateVerification.verifyTimestampCertificates(tst, ks, null);
        }

        PdfDictionary pdfDic = reader.getAcroFields().getSignatureDictionary(name);
        SignaturePermissions sp = new SignaturePermissions(pdfDic, null);

        boolean isValid;
        if (nextValid) {
            isValid = pk.verify();
        } else {
            isValid = false;
        }

        List<AcroFields.FieldPosition> posList = af.getFieldPositions(name);
        final SignatureValidation signature = new SignatureValidation(file, name, pk, !pk.verify(),
                af.signatureCoversWholeDocument(name), af.getRevision(name), af.getTotalRevisions(),
                reader.getCertificationLevel(), ocspCertificateStatus, crlCertificateStatus, validTimestamp,
                posList, sp, isValid);
        validateList.add(signature);

        if (null != vl) {
            vl.onValidationComplete(signature);
        }
        if (!sp.isFillInAllowed()) {
            nextValid = false;
        }
    }
    return validateList;
}

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

License:Open Source License

public static void check(X509Certificate issuerCert, X509Certificate x509Cert)
        throws OcspValidationException, OcspTimeoutException {
    try {/*  w  w w  .  j  a  v  a 2  s .  c o  m*/
        BigInteger serialNumber = x509Cert.getSerialNumber();
        X509CertificateHolder holder;

        try {
            holder = new X509CertificateHolder(issuerCert.getEncoded());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        CertificateID id = new CertificateID(new JcaDigestCalculatorProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build().get(CertificateID.HASH_SHA1), holder,
                serialNumber);

        OCSPReqBuilder ocspGen = new OCSPReqBuilder();
        ocspGen.addRequest(id);
        OCSPReq ocspReq = ocspGen.build();

        // Ir al OCSP
        String ocspUrl = CertificateUtil.getOCSPURL(x509Cert);

        if (ocspUrl == null) {
            logger.info("URL de OCSP is null");
            return;
        }

        URL url;

        try {
            url = new URL(ocspUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

        HttpURLConnection con;
        OCSPResp ocspResponse;

        try {
            con = (HttpURLConnection) url.openConnection();

            con.setRequestProperty("Content-Type", "application/ocsp-request");
            con.setRequestProperty("Accept", "application/ocsp-response");
            con.setDoOutput(true);

            OutputStream out = con.getOutputStream();
            DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
            dataOut.write(ocspReq.getEncoded());

            dataOut.flush();
            dataOut.close();

            /*
             * Se parsea la respuesta y se obtiene el estado del certificado
             * retornado por el OCSP
             */
            InputStream in = (InputStream) con.getContent();
            byte[] resp = read(in); // Read the reponse
            ocspResponse = new OCSPResp(resp);
        } catch (IOException e) {
            throw new OcspTimeoutException(url);
        }

        int status = ocspResponse.getStatus();
        System.out.println("status=" + status);

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

        if (basicResponse != null) {
            SingleResp[] responses = basicResponse.getResponses();
            SingleResp response = responses[0];
            CertificateStatus certStatus = response.getCertStatus();

            if (certStatus instanceof RevokedStatus) {
                System.out.println("REVOKED");
                RevokedStatus revokedStatus = (RevokedStatus) certStatus;
                System.out.println("Reason: " + revokedStatus.getRevocationReason());
                System.out.println("Date: " + revokedStatus.getRevocationTime());

                throw new OcspValidationException(revokedStatus.getRevocationReason(),
                        revokedStatus.getRevocationTime());
            }
        }
    } catch (OCSPException e) {
        throw new RuntimeException(e);
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
}

From source file:ee.ria.xroad.common.cert.CertHelper.java

License:Open Source License

/**
 * Finds the OCSP response from a list of OCSP responses
 * for a given certificate./*www. j a  v a2  s .co m*/
 * @param cert the certificate
 * @param issuer the issuer of the certificate
 * @param ocspResponses list of OCSP responses
 * @return the OCSP response or null if not found
 * @throws Exception if an error occurs
 */
public static OCSPResp getOcspResponseForCert(X509Certificate cert, X509Certificate issuer,
        List<OCSPResp> ocspResponses) throws Exception {
    CertificateID certId = CryptoUtils.createCertId(cert, issuer);
    for (OCSPResp resp : ocspResponses) {
        BasicOCSPResp basicResp = (BasicOCSPResp) resp.getResponseObject();
        SingleResp singleResp = basicResp.getResponses()[0];
        if (certId.equals(singleResp.getCertID())) {
            return resp;
        }
    }

    return null;
}

From source file:ee.ria.xroad.common.ocsp.OcspVerifier.java

License:Open Source License

private SingleResp verifyResponseValidity(OCSPResp response, X509Certificate subject, X509Certificate issuer)
        throws Exception {
    BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
    SingleResp singleResp = basicResp.getResponses()[0];

    CertificateID requestCertId = createCertId(subject, issuer);

    // http://www.ietf.org/rfc/rfc2560.txt -- 3.2:
    // Prior to accepting a signed response as valid, OCSP clients
    // SHALL confirm that:

    // 1. The certificate identified in a received response corresponds to
    // that which was identified in the corresponding request;
    if (!singleResp.getCertID().equals(requestCertId)) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO,
                "OCSP response does not apply to certificate (sn = %s)", subject.getSerialNumber());
    }//from www  .  j av a2 s  . c om

    X509Certificate ocspCert = getOcspCert(basicResp);
    if (ocspCert == null) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO,
                "Could not find OCSP certificate for responder ID");
    }

    if (!verifySignature(basicResp, ocspCert)) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO, "Signature on OCSP response is not valid");
    }

    // 3. The identity of the signer matches the intended
    // recipient of the request.
    // -- Not important here because the original request is not available.

    // 4. The signer is currently authorized to sign the response.
    if (!isAuthorizedOcspSigner(ocspCert, issuer)) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO, "OCSP responder is not authorized for given CA");
    }
    return singleResp;
}

From source file:ee.ria.xroad.common.ocsp.OcspVerifier.java

License:Open Source License

/**
 * Verifies the status of the OCSP response.
 * @param response the OCSP response//  www.  jav a 2 s.  c  om
 * @throws Exception CodedException with error code X_CERT_VALIDATION
 * if status is not good.
 */
public static void verifyStatus(OCSPResp response) throws Exception {
    BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
    SingleResp singleResp = basicResp.getResponses()[0];

    CertificateStatus status = singleResp.getCertStatus();
    if (status != null) { // null indicates GOOD.
        throw new CodedException(X_CERT_VALIDATION, "OCSP response indicates certificate status is %s",
                getStatusString(status));
    }
}

From source file:ee.ria.xroad.common.ocsp.OcspVerifier.java

License:Open Source License

/**
 * Returns true if the OCSP response is about to expire at the current date.
 * @param response the response//from   ww  w  .ja  va2s.c  o m
 * @return true, if the OCSP response is expired
 * @throws Exception if an error occurs
 */
public boolean isExpired(OCSPResp response) throws Exception {
    BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
    SingleResp singleResp = basicResp.getResponses()[0];
    return isExpired(singleResp, new Date());
}

From source file:ee.ria.xroad.common.ocsp.OcspVerifier.java

License:Open Source License

/**
 * Returns true if the OCSP response is about to expire at the
 * specified date./*from w  ww .j  a v a2s.c om*/
 * @param response the response
 * @param atDate the date
 * @return true, if the OCSP response is expired at the specified date.
 * @throws Exception if an error occurs
 */
public boolean isExpired(OCSPResp response, Date atDate) throws Exception {
    BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
    SingleResp singleResp = basicResp.getResponses()[0];
    return isExpired(singleResp, atDate);
}

From source file:ee.ria.xroad.signer.console.Utils.java

License:Open Source License

@SneakyThrows
static String getOcspStatus(byte[] ocspBytes) {
    if (ocspBytes == null) {
        return "<not available>";
    }//from  ww  w  . j  ava 2 s  .c  o  m

    OCSPResp response = new OCSPResp(ocspBytes);
    BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject();
    SingleResp resp = basicResponse.getResponses()[0];
    CertificateStatus status = resp.getCertStatus();

    if (status == CertificateStatus.GOOD) {
        return "GOOD";
    } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
        return "REVOKED";
    } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) {
        return "UNKNOWN";
    } else {
        return "{" + status.getClass() + "}";
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.ocsp.OfflineOCSPSource.java

License:Open Source License

@Override
final public BasicOCSPResp getOCSPResponse(final X509Certificate x509Certificate,
        final X509Certificate issuerX509Certificate) {

    /**//from   w w  w. ja v  a  2  s  . c  om
     * 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;
    final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(x509Certificate,
            issuerX509Certificate);
    for (final BasicOCSPResp basicOCSPResp : getContainedOCSPResponses()) {

        for (final SingleResp singleResp : basicOCSPResp.getResponses()) {

            if (DSSRevocationUtils.matches(certId, singleResp)) {

                final Date thisUpdate = singleResp.getThisUpdate();
                if (bestUpdate == null || thisUpdate.after(bestUpdate)) {

                    bestBasicOCSPResp = basicOCSPResp;
                    bestUpdate = thisUpdate;
                }
            }
        }
    }
    return bestBasicOCSPResp;
}

From source file:eu.europa.ec.markt.dss.validation102853.ocsp.SKOnlineOCSPSource.java

License:GNU General Public License

@Override
public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificatePool certificatePool) {
    if (listener != null) {
        listener.onGetOCSPToken(certificateToken, certificatePool);
    }//w w w  .j a va  2s  . c o  m
    if (dataLoader == null) {
        throw new DSSNullException(DataLoader.class);
    }
    try {
        final String dssIdAsString = certificateToken.getDSSIdAsString();
        if (logger.isTraceEnabled()) {
            logger.trace("--> OnlineOCSPSource queried for " + dssIdAsString);
        }
        final X509Certificate certificate = certificateToken.getCertificate();
        //      final X509Certificate issuerCertificate = certificateToken.getIssuerToken().getCertificate();
        X500Principal issuerX500Principal = certificateToken.getIssuerX500Principal();
        List<CertificateToken> issuerTokens = certificatePool.get(issuerX500Principal);

        if (issuerTokens == null || issuerTokens.size() == 0)
            throw new DSSException("Not possible to find issuer " + issuerX500Principal + " certificate");
        final X509Certificate issuerCertificate = issuerTokens.get(0).getCertificate();

        final String ocspUri = getAccessLocation();
        if (logger.isDebugEnabled()) {
            logger.debug("OCSP URI: " + ocspUri);
        }
        if (ocspUri == null) {

            return null;
        }
        Extension nonceExtension = createNonce();
        final byte[] content = buildOCSPRequest(certificate, issuerCertificate, nonceExtension);

        final byte[] ocspRespBytes = dataLoader.post(ocspUri, content);

        final OCSPResp ocspResp = new OCSPResp(ocspRespBytes);
        BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();

        checkNonce(basicOCSPResp, nonceExtension);

        Date bestUpdate = null;
        SingleResp bestSingleResp = null;
        final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(certificate, issuerCertificate);
        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;
                }
            }
        }
        if (bestSingleResp != null) {

            final OCSPToken ocspToken = new OCSPToken(basicOCSPResp, bestSingleResp, certificatePool);
            ocspToken.setSourceURI(ocspUri);
            certificateToken.setRevocationToken(ocspToken);
            return ocspToken;
        }
    } catch (NullPointerException e) {
        logger.error(
                "OCSP error: Encountered a case when the OCSPResp is initialised with a null OCSP response...",
                e);
    } catch (OCSPException e) {
        logger.error("OCSP error: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
    return null;
}