Example usage for java.security.cert X509Certificate getIssuerX500Principal

List of usage examples for java.security.cert X509Certificate getIssuerX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getIssuerX500Principal.

Prototype

public X500Principal getIssuerX500Principal() 

Source Link

Document

Returns the issuer (issuer distinguished name) value from the certificate as an X500Principal .

Usage

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Import a PKCS12 format (which includes the private key) certificate.
 *//*from w ww  .  j  a  v a2  s.com*/
@Test
public void importCertificatePkcs12() throws Exception {
    String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dt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aoYkyLAwdJWIXTi+c37YaC8FRSEnnNmS79Dou1Kc3BvK4EYKAD2KxjtUebrV174gD0Q+9YuJ0GXOTspBvCFd5VT2Rw5zDNrA/J3F5fMCk4wOzAfMAcGBSsOAwIaBBSxgh2xyF+88V4vAffBmZXv8Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ";
    String certificatePassword = "123";

    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12);
    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties);
    Attributes attribute = new CertificateAttributes().withEnabled(true);

    String vaultUri = getVaultUri();
    String certificateName = "importCertPkcs";
    CertificateBundle certificateBundle = keyVaultClient.importCertificate(
            new ImportCertificateRequest.Builder(vaultUri, certificateName, certificateContent)
                    .withPassword(certificatePassword).withPolicy(certificatePolicy).withAttributes(attribute)
                    .withTags(sTags).build());

    // Validate the certificate bundle created
    validateCertificateBundle(certificateBundle, certificatePolicy);
    Assert.assertTrue(toHexString(certificateBundle.x509Thumbprint())
            .equalsIgnoreCase("7cb8b7539d87ba7215357b9b9049dff2d3fa59ba"));
    Assert.assertEquals(attribute.enabled(), certificateBundle.attributes().enabled());

    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals("CN=KeyVaultTest"));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals("CN=Root Agency"));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());

    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(),
            certificateName);

    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
}

From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

/**
 * /*from w  w  w  .  j av  a 2  s .c  o  m*/
 * 
 * @param signerSubjectDN signerSubjectDN subject DN of the signing key to be renewed. The string "all" will result in all keys being renewed
 * @param safetyMargin the number of seconds before actual expiration that a keystore should be renewed
 * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist.
 * @throws InvalidKeyException if the public key in the tokenAndChain can not be used to verify a string signed by the private key, because the key 
 * is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 */
private synchronized void renewKeyStores(String signerSubjectDN, long safetyMargin)
        throws InvalidKeyException, CryptoTokenOfflineException {
    //Cancel all running timers
    cancelTimers();
    try {
        final EjbcaWS ejbcaWS = getEjbcaWS();
        if (ejbcaWS == null) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "Could not locate a suitable web service for automatic OCSP key/certificate renewal.");
            }
            return;
        }
        final X500Principal target;
        try {
            target = signerSubjectDN.trim().equalsIgnoreCase(RENEW_ALL_KEYS) ? null
                    : new X500Principal(signerSubjectDN);
        } catch (IllegalArgumentException e) {
            log.error(intres.getLocalizedMessage("ocsp.rekey.triggered.dn.not.valid", signerSubjectDN));
            return;
        }
        final StringBuffer matched = new StringBuffer();
        final StringBuffer unMatched = new StringBuffer();
        for (final OcspSigningCacheEntry ocspSigningCacheEntry : OcspSigningCache.INSTANCE.getEntries()) {
            // Only perform renewal for non CA signing key OCSP signers
            if (!ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
                continue;
            }
            final X509Certificate ocspSigningCertificate = ocspSigningCacheEntry.getOcspSigningCertificate();
            final long timeLeftBeforeRenewal = ocspSigningCertificate.getNotAfter().getTime()
                    - new Date().getTime();
            if (timeLeftBeforeRenewal < (1000 * safetyMargin)) {
                final X500Principal src = ocspSigningCertificate.getSubjectX500Principal();
                if (target != null && !src.equals(target)) {
                    unMatched.append(" '" + src.getName() + '\'');
                    continue;
                }
                matched.append(" '" + ocspSigningCertificate.getIssuerX500Principal().getName() + '\'');
                try {
                    renewKeyStore(ejbcaWS, ocspSigningCacheEntry);
                } catch (KeyRenewalFailedException e) {
                    String msg = intres.getLocalizedMessage("ocsp.rekey.failed.unknown.reason", target,
                            e.getLocalizedMessage());
                    log.error(msg, e);
                    continue;
                }
            }
        }
        if (matched.length() < 1 && target != null) {
            log.error(intres.getLocalizedMessage("ocsp.rekey.triggered.dn.not.existing", target.getName(),
                    unMatched));
            return;
        }
        log.info(intres.getLocalizedMessage("ocsp.rekey.triggered", matched));
    } finally {
        //Set new timer to run, even if something breaks.
        addTimer(OcspConfiguration.getRekeyingUpdateTimeInSeconds());
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Create a self-signed certificate in PKCS12 format (which includes the
 * private key) certificate.// w ww .  ja  v  a  2 s.  co m
 * 
 * @throws Exception
 */
@Test
public void createSelfSignedCertificatePkcs12() throws Exception {
    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12);

    String subjectName = "CN=SelfSignedJavaPkcs12";
    X509CertificateProperties x509Properties = new X509CertificateProperties().withSubject(subjectName)
            .withValidityInMonths(12);

    // Set issuer to "Self"
    IssuerParameters issuerParameters = new IssuerParameters().withName(ISSUER_SELF);

    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties)
            .withIssuerParameters(issuerParameters).withX509CertificateProperties(x509Properties);

    Attributes attribute = new CertificateAttributes().withEnabled(true)
            .withExpires(new DateTime().withYear(2050).withMonthOfYear(1))
            .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1));

    String vaultUri = getVaultUri();
    String certificateName = "createSelfSignedJavaPkcs12";

    CreateCertificateRequest createCertificateRequest = new CreateCertificateRequest.Builder(vaultUri,
            certificateName).withPolicy(certificatePolicy).withAttributes(attribute).withTags(sTags).build();

    CertificateOperation certificateOperation = keyVaultClient.createCertificate(createCertificateRequest);

    Assert.assertNotNull(certificateOperation);
    Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS));

    CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation);
    validateCertificateBundle(certificateBundle, certificatePolicy);
    compareAttributes(attribute, createCertificateRequest.certificateAttributes());

    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());

    // Retrieve the key backing the certificate
    KeyIdentifier keyIdentifier = certificateBundle.keyIdentifier();
    KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier());
    Assert.assertTrue(keyBundle.managed());

    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(),
            certificateName);
    Assert.assertNotNull(deletedCertificateBundle);
    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/*from  w  ww  . j  av a 2 s  .c  om*/
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Create a test-issuer issued certificate in PKCS12 format (which includes
 * the private key) certificate./*  www  . java2  s  . c  om*/
 * 
 * @throws Exception
 */
@Test
public void createCertificatePkcs12() throws Exception {
    // Construct organization administrator details
    AdministratorDetails administratorDetails = new AdministratorDetails().withFirstName("John")
            .withLastName("Doe").withEmailAddress("john.doe@contoso.com").withPhone("1234567890");

    // Construct organization details
    List<AdministratorDetails> administratorsDetails = new ArrayList<AdministratorDetails>();
    administratorsDetails.add(administratorDetails);
    OrganizationDetails organizationDetails = new OrganizationDetails().withAdminDetails(administratorsDetails);

    // Construct certificate issuer credentials
    IssuerCredentials credentials = new IssuerCredentials().withAccountId("account1").withPassword("Pa$$w0rd");

    String certificateIssuerName = "createCertificateJavaPkcs12Issuer01";
    IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer(
            new SetCertificateIssuerRequest.Builder(getVaultUri(), certificateIssuerName, ISSUER_TEST)
                    .withCredentials(credentials).withOrganizationDetails(organizationDetails).build());

    validateCertificateIssuer(createdCertificateIssuer, certificateIssuerName);

    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12);

    String subjectName = "CN=TestJavaPkcs12";
    X509CertificateProperties x509Properties = new X509CertificateProperties().withSubject(subjectName)
            .withValidityInMonths(12);

    // Set issuer reference to the created issuer
    IssuerParameters issuerParameters = new IssuerParameters();
    issuerParameters.withName(createdCertificateIssuer.issuerIdentifier().name());

    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties)
            .withIssuerParameters(issuerParameters).withX509CertificateProperties(x509Properties);

    String vaultUri = getVaultUri();
    String certificateName = "createTestJavaPkcs12";
    CertificateOperation certificateOperation = keyVaultClient
            .createCertificate(new CreateCertificateRequest.Builder(vaultUri, certificateName)
                    .withPolicy(certificatePolicy).build());

    Assert.assertNotNull(certificateOperation);
    Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS));

    CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation);
    validateCertificateBundle(certificateBundle, certificatePolicy);

    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());

    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(),
            certificateName);
    Assert.assertNotNull(deletedCertificateBundle);

    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
}

From source file:org.bitrepository.protocol.security.PermissionStore.java

/**
 * Load permissions and certificates into the store based.
 * @param permissions the PermissionSet from RepositorySettings.
 * @param componentID the ID of the component using the PermissionStore. 
 * @throws CertificateException in case a bad certificate data in PermissionSet.   
 *///from  w  w w.jav  a 2  s.c  o m
public void loadPermissions(PermissionSet permissions, String componentID) throws CertificateException {
    if (permissions != null) {
        Set<Operation> allowedOperations;
        Set<String> allowedUsers;
        for (Permission permission : permissions.getPermission()) {
            if (permission.getCertificate().getAllowedCertificateUsers() != null) {
                allowedUsers = new HashSet<String>();
                allowedUsers.addAll(permission.getCertificate().getAllowedCertificateUsers().getIDs());
            } else {
                allowedUsers = null;
            }

            allowedOperations = new HashSet<Operation>();
            X509Certificate certificate = null;
            if (permission.getOperationPermission() != null) {
                for (OperationPermission perm : permission.getOperationPermission()) {
                    if (perm.getAllowedComponents() == null
                            || perm.getAllowedComponents().getIDs().contains(componentID)) {
                        allowedOperations.add(perm.getOperation());
                    }
                }
                if (!allowedOperations.isEmpty()) {
                    certificate = makeCertificate(permission.getCertificate().getCertificateData());
                }
            }
            if (permission.getInfrastructurePermission().contains(InfrastructurePermission.MESSAGE_SIGNER)) {
                if (certificate == null) {
                    certificate = makeCertificate(permission.getCertificate().getCertificateData());
                }
            }

            if (certificate != null) {
                CertificateID certID = new CertificateID(certificate.getIssuerX500Principal(),
                        certificate.getSerialNumber());
                CertificatePermission certificatePermission = new CertificatePermission(certificate,
                        allowedOperations, allowedUsers);
                permissionMap.put(certID, certificatePermission);
            }
        }
    } else {
        log.info("The provided PermissionSet was null");
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate,
        String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    String defaultAlias = Collections.list(keyStore.aliases()).get(0);
    X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Validate the key in the KeyStore
    Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray());
    Assert.assertNotNull(secretKey);//from  w w w  . ja v  a2s .co m
    Assert.assertTrue(secretKey instanceof PrivateKey);
    PrivateKey secretPrivateKey = (PrivateKey) secretKey;

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}

From source file:org.glite.security.voms.admin.persistence.dao.VOMSUserDAO.java

public Certificate addCertificate(VOMSUser u, X509Certificate x509Cert) {

    Validate.notNull(u, "User must be non-null!");
    Validate.notNull(x509Cert, "Certificate must be non-null!");

    // Assume the certificate have been already validated
    // at this stage.

    String caDN = DNUtil.getOpenSSLSubject(x509Cert.getIssuerX500Principal());
    VOMSCA ca = VOMSCADAO.instance().getByName(caDN);

    if (ca == null)
        throw new NoSuchCAException("CA '" + caDN + "' not recognized!");

    Certificate cert = CertificateDAO.instance().find(x509Cert);

    if (cert != null)
        throw new AlreadyExistsException("Certificate already bound!");

    cert = new Certificate();

    String subjectString = DNUtil.getOpenSSLSubject(x509Cert.getSubjectX500Principal());
    cert.setSubjectString(subjectString);
    cert.setCreationTime(new Date());
    cert.setSuspended(false);/*from w  ww.  j  av a 2s  .c  o  m*/
    cert.setCa(ca);

    cert.setUser(u);

    if (u.isSuspended()) {
        cert.setSuspended(true);
        cert.setSuspensionReason(u.getSuspensionReason());
    }

    u.addCertificate(cert);

    HibernateFactory.getSession().saveOrUpdate(cert);
    HibernateFactory.getSession().saveOrUpdate(u);

    return cert;

}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

private boolean acceptCRL_6_3_3_b(X509Certificate targetCertificate, X509CRL crl) throws IOException {
    boolean match = false;

    if (X509CRLInspector.isDeltaCRL(crl)) {
        /* CRL is not complete because it's a delta CRL */
        return false;
    }//  www.j ava2 s. com

    if (!crl.getIssuerX500Principal().equals(targetCertificate.getIssuerX500Principal())) {
        logger.debug("CRL issuer and certificate issuer do not match.");

        return false;
    }

    IssuingDistributionPoint idp = X509CRLInspector.getIssuingDistributionPoint(crl);

    /* if there is no IssuingDistributionPoint there is always a match */
    if (idp == null) {
        return true;
    }

    DistributionPointName idpn = idp.getDistributionPoint();

    CRLDistPoint crlDistPoint = X509CertificateInspector.getCRLDistibutionPoints(targetCertificate);

    DistributionPoint[] dps = null;

    if (crlDistPoint != null) {
        dps = crlDistPoint.getDistributionPoints();
    }

    if (dps != null) {
        for (DistributionPoint dp : dps) {
            if (dp == null) {
                logger.debug("Distributionpoint is null.");
                continue;
            }

            if (dp.getCRLIssuer() != null) {
                /* we do not support indirect CRLs */
                logger.debug("CRL issuer should only be used for indirect CRLs.");

                continue;
            }

            DistributionPointName dpn = dp.getDistributionPoint();

            if (idp != null) {
                if (idpn != null && dpn != null) {
                    X500Principal issuer = targetCertificate.getIssuerX500Principal();

                    if (hasMatchingName(idpn, dpn, issuer)) {
                        match = true;
                        break;
                    }
                }
            }
        }
        if (!match) {
            logger.debug("The CRL did not contain matching DistributionPoint names.");
        }
    } else {
        match = (idpn == null);
    }

    BasicConstraints basicConstraints = X509CertificateInspector.getBasicConstraints(targetCertificate);

    if (idp != null) {
        /* if basicConstraints is null assume it's a user certificate */

        if (idp.onlyContainsCACerts()
                && ((basicConstraints != null && !basicConstraints.isCA()) | basicConstraints == null)) {
            logger.debug("Certificate is a user certificate but CRL only contains CA certificate.");
            match = false;
        }

        if (idp.onlyContainsUserCerts() && basicConstraints != null && basicConstraints.isCA()) {
            logger.debug("Certificate is a CA but CRL only contains user certificates.");
            match = false;
        }

        if (idp.onlyContainsAttributeCerts()) {
            logger.debug("Certificate only contains attribute certs.");
            match = false;
        }
    }

    return match;
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

private boolean preFilter(X509Certificate targetCertificate, X509CRL crl) throws IOException {
    IssuingDistributionPoint idp = X509CRLInspector.getIssuingDistributionPoint(crl);

    if (idp != null) {
        if (idp.isIndirectCRL()) {
            logger.debug("CRL is indirect.");
            return false;
        }/*from   w  w w .j a  v a2s.co m*/
    }

    if (!crl.getIssuerX500Principal().equals(targetCertificate.getIssuerX500Principal())) {
        logger.debug("CRL issuer and certificate issuer do not match.");
        return false;
    }

    return true;
}