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

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

Introduction

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

Prototype

public boolean isSignatureValid(ContentVerifierProvider verifierProvider) throws OCSPException 

Source Link

Document

verify the signature against the tbsResponseData object we contain.

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  . j  av  a2s  . c o  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:com.itextpdf.signatures.SignUtils.java

License:Open Source License

static boolean isSignatureValid(BasicOCSPResp validator, Certificate certStoreX509, String provider)
        throws OperatorCreationException, OCSPException {
    if (provider == null)
        provider = "BC";
    return validator.isSignatureValid(
            new JcaContentVerifierProviderBuilder().setProvider(provider).build(certStoreX509.getPublicKey()));
}

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

License:Open Source License

/**
 * Verifies an OCSP response against a KeyStore.
 * @param ocsp the OCSP response/*from ww  w.j  ava  2s.  co  m*/
 * @param keystore the <CODE>KeyStore</CODE>
 * @param provider the provider or <CODE>null</CODE> to use the BouncyCastle provider
 * @return <CODE>true</CODE> is a certificate was found
 */
public static boolean verifyOcspCertificates(BasicOCSPResp ocsp, KeyStore keystore, String provider) {
    if (provider == null)
        provider = "BC";
    try {
        for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
            try {
                String alias = aliases.nextElement();
                if (!keystore.isCertificateEntry(alias))
                    continue;
                X509Certificate certStoreX509 = (X509Certificate) keystore.getCertificate(alias);
                if (ocsp.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider(provider)
                        .build(certStoreX509.getPublicKey())))
                    return true;
            } catch (Exception ex) {
            }
        }
    } catch (Exception e) {
    }
    return false;
}

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

License:Open Source License

/**
 * Checks if an OCSP response is genuine
 * @param ocspResp   the OCSP response//  w  w w . ja  va  2 s .  c om
 * @param responderCert   the responder certificate
 * @return   true if the OCSP response verifies against the responder certificate
 */
public boolean isSignatureValid(BasicOCSPResp ocspResp, Certificate responderCert) {
    try {
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().setProvider("BC")
                .build(responderCert.getPublicKey());
        return ocspResp.isSignatureValid(verifierProvider);
    } catch (OperatorCreationException e) {
        return false;
    } catch (OCSPException e) {
        return false;
    }
}

From source file:ec.rubrica.pdf.FirmaPDF.java

License:Open Source License

/**
 * TODO: Mas de dos firmas?/*  www . j av  a 2  s  .c  o  m*/
 * 
 * @param pdf
 * @throws IOException
 * @throws SignatureException
 */
public static boolean verificar(byte[] pdf) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(pdf);
    AcroFields af = reader.getAcroFields();
    ArrayList<String> names = af.getSignatureNames();

    for (int k = 0; k < names.size(); ++k) {
        String name = (String) names.get(k);
        System.out.println("Signature name: " + name);
        System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        PdfPKCS7 pk = af.verifySignature(name);
        Calendar cal = pk.getSignDate();
        Certificate[] pkc = pk.getCertificates();
        TimeStampToken ts = pk.getTimeStampToken();

        if (ts != null) {
            cal = pk.getTimeStampDate();
        }

        if (!pk.isTsp() && ts != null) {
            boolean impr;
            try {
                impr = pk.verifyTimestampImprint();
                System.out.println("Timestamp imprint verifies: " + impr);
                System.out.println("Timestamp date: " + cal);
            } catch (NoSuchAlgorithmException e) {
                throw new SignatureException(e);
            }
        }

        System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
        System.out.println("Document modified: " + !pk.verify());

        KeyStore kall = KeyStoreUtil.loadCacertsKeyStore();

        Object fails[] = CertificateVerification.verifyCertificates(pkc, kall, null, cal);

        if (fails == null) {
            System.out.println("Certificates verified against the KeyStore");
        } else {
            System.out.println("Certificate failed: " + fails[0]);
            return false;
        }

        BasicOCSPResp ocsp = pk.getOcsp();

        if (ocsp != null) {
            try {
                X509Certificate cert = new SecurityDataSubCaCert();

                boolean verifies = ocsp.isSignatureValid(new JcaContentVerifierProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert.getPublicKey()));

                System.out.println("OCSP signature verifies: " + verifies);

                System.out.println("OCSP revocation refers to this certificate: " + pk.isRevocationValid());

                return verifies;
            } catch (OperatorCreationException e) {
                throw new SignatureException(e);
            } catch (OCSPException e) {
                throw new SignatureException(e);
            }
        } else {
            return true;
        }
    }

    return false;
}

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

License:Open Source License

private boolean verifySignature(BasicOCSPResp basicResp, X509Certificate ocspCert)
        throws OperatorCreationException, OCSPException {
    ContentVerifierProvider verifier = createDefaultContentVerifier(ocspCert.getPublicKey());

    return basicResp.isSignatureValid(verifier);
}

From source file:net.maritimecloud.pki.ocsp.OCSPClient.java

License:Open Source License

public CertStatus getCertificateStatus() throws OCSPValidationException {
    try {// w w  w.  j a  v a 2 s. 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/* w w w  .ja va  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.
 */// ww w .  j av  a2 s  .  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//from w w w  .  ja v 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);
    }

}