Example usage for java.security.cert X509CertSelector X509CertSelector

List of usage examples for java.security.cert X509CertSelector X509CertSelector

Introduction

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

Prototype

public X509CertSelector() 

Source Link

Document

Creates an X509CertSelector .

Usage

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

@Test
public void test_4_14_16_Invalid_onlySomeReasons_Test16() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/onlySomeReasonsCA1Cert.crt"), certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/InvalidonlySomeReasonsTest16EE.crt"),
            certStoreParams.getCertStore());

    // add crls//from w  w w .j  av  a 2 s .c o m
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA1compromiseCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA1otherreasonsCRL.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("2"));
    selector.setIssuer("CN=onlySomeReasons CA1, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, testDate);

    assertEquals(RevocationStatus.REVOKED, revocationResult.getStatus());
    assertEquals(RevocationReason.CERTIFICATE_HOLD, revocationResult.getReason());

    RevocationDetail[] detail = revocationResult.getDetails();

    assertEquals(detail.length, 2);
    assertEquals(RevocationStatus.REVOKED, detail[0].getStatus());
    assertEquals(RevocationStatus.UNKNOWN, detail[1].getStatus());
}

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

@Test
public void test_4_14_17_Invalid_onlySomeReasons_Test17() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/onlySomeReasonsCA2Cert.crt"), certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/InvalidonlySomeReasonsTest17EE.crt"),
            certStoreParams.getCertStore());

    // add crls/*from  w  ww  .  j  a va  2 s.  c om*/
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA2CRL1.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA2CRL2.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("1"));
    selector.setIssuer("CN=onlySomeReasons CA2, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, testDate);

    assertEquals(RevocationStatus.UNKNOWN, revocationResult.getStatus());
    assertEquals(null, revocationResult.getReason());

    RevocationDetail[] detail = revocationResult.getDetails();

    assertEquals(detail.length, 2);
    assertEquals(RevocationStatus.UNKNOWN, detail[0].getStatus());
    assertEquals(RevocationStatus.NOT_REVOKED, detail[1].getStatus());
}

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

@Test
public void test_4_14_18_Valid_onlySomeReasons_Test18() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/onlySomeReasonsCA3Cert.crt"), certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/ValidonlySomeReasonsTest18EE.crt"),
            certStoreParams.getCertStore());

    // add crls//from   w  w w. ja  v a 2 s.  com
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA3compromiseCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA3otherreasonsCRL.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("1"));
    selector.setIssuer("OU=onlySomeReasons CA3, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, testDate);

    assertEquals(RevocationStatus.NOT_REVOKED, revocationResult.getStatus());
    assertEquals(null, revocationResult.getReason());

    RevocationDetail[] detail = revocationResult.getDetails();

    assertEquals(detail.length, 2);
    assertEquals(RevocationStatus.NOT_REVOKED, detail[0].getStatus());
    assertEquals(RevocationStatus.NOT_REVOKED, detail[1].getStatus());
}

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

@Test
public void test_4_14_19_Valid_onlySomeReasons_Test19() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/onlySomeReasonsCA4Cert.crt"), certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/ValidonlySomeReasonsTest19EE.crt"),
            certStoreParams.getCertStore());

    // add crls//from w  w  w  .j  a va2s.  c  o m
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA4compromiseCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA4otherreasonsCRL.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("1"));
    selector.setIssuer("OU=onlySomeReasons CA4, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, testDate);

    assertEquals(RevocationStatus.NOT_REVOKED, revocationResult.getStatus());
    assertEquals(null, revocationResult.getReason());

    RevocationDetail[] detail = revocationResult.getDetails();

    assertEquals(detail.length, 2);
    assertEquals(RevocationStatus.NOT_REVOKED, detail[0].getStatus());
    assertEquals(RevocationStatus.NOT_REVOKED, detail[1].getStatus());
}

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

@Test
public void test_4_14_20_Invalid_onlySomeReasons_Test20() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/onlySomeReasonsCA4Cert.crt"), certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/InvalidonlySomeReasonsTest20EE.crt"),
            certStoreParams.getCertStore());

    // add crls/*from   w w  w.  j  a v a2s  . c o  m*/
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA4compromiseCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA4otherreasonsCRL.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("2"));
    selector.setIssuer("OU=onlySomeReasons CA4, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, testDate);

    assertEquals(RevocationStatus.REVOKED, revocationResult.getStatus());
    assertEquals(RevocationReason.KEY_COMPROMISE, revocationResult.getReason());

    RevocationDetail[] detail = revocationResult.getDetails();

    assertEquals(detail.length, 2);
    assertEquals(RevocationStatus.REVOKED, detail[0].getStatus());
    assertEquals(RevocationStatus.UNKNOWN, detail[1].getStatus());
}

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

@Test
public void test_4_14_21_Invalid_onlySomeReasons_Test21() throws Exception {
    // add certificates
    addCertificates(new File(testBase, "certs/onlySomeReasonsCA4Cert.crt"), certStoreParams.getCertStore());
    addCertificates(new File(testBase, "certs/InvalidonlySomeReasonsTest21EE.crt"),
            certStoreParams.getCertStore());

    // add crls//from  w  ww  . j  a v a2s . co m
    addCRL(new File(testBase, "crls/TrustAnchorRootCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA4compromiseCRL.crl"), certStoreParams.getCRLStore());
    addCRL(new File(testBase, "crls/onlySomeReasonsCA4otherreasonsCRL.crl"), certStoreParams.getCRLStore());

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(BigIntegerUtils.hexDecode("3"));
    selector.setIssuer("OU=onlySomeReasons CA4, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);

    PKIXRevocationChecker revocationChecker = new PKIXRevocationChecker(certStoreParams.getCRLStore());

    RevocationResult revocationResult = revocationChecker.getRevocationStatus(certPath, trustAnchor, testDate);

    assertEquals(RevocationStatus.REVOKED, revocationResult.getStatus());
    assertEquals(RevocationReason.AFFILIATION_CHANGED, revocationResult.getReason());

    RevocationDetail[] detail = revocationResult.getDetails();

    assertEquals(detail.length, 2);
    assertEquals(RevocationStatus.REVOKED, detail[0].getStatus());
    assertEquals(RevocationStatus.UNKNOWN, detail[1].getStatus());
}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);//from  ww w .j av a  2  s  . c o m

    for (Certificate c : certs) {
        if (!(c instanceof X509Certificate))
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

        X509Certificate xCert = (X509Certificate) c;

        Principal subject = xCert.getSubjectDN();
        Principal issuer = xCert.getIssuerDN();

        anchors.add(new TrustAnchor(xCert, null));
    }

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java

private void validateChain(final List<Certificate> chain, final Certificate cert) {

    final List<Certificate> certs = new ArrayList<Certificate>();
    final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);/*  w w  w .  j a va2 s .  c  om*/

    for (final Certificate c : certs) {
        if (!(c instanceof X509Certificate)) {
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");
        }
        final X509Certificate xCert = (X509Certificate) c;
        anchors.add(new TrustAnchor(xCert, null));
    }

    final X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);

    } catch (final InvalidAlgorithmParameterException | CertPathBuilderException | NoSuchAlgorithmException e) {
        throw new IllegalStateException("Invalid certificate chain", e);
    } catch (final NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java

/**
 * Verifies the signature on an enveloped digital signature on a UDDI
 * entity, such as a business, service, tmodel or binding template.
 * <br><Br>/* w  ww  . jav a2s.  c o m*/
 * It is expected that either the public key of the signing certificate
 * is included within the signature keyinfo section OR that sufficient
 * information is provided in the signature to reference a public key
 * located within the Trust Store provided<br><Br> Optionally, this
 * function also validate the signing certificate using the options
 * provided to the configuration map.
 *
 * @param obj an enveloped signed JAXB object
 * @param OutErrorMessage a human readable error message explaining the
 * reason for failure
 * @return true if the validation passes the signature validation test,
 * and optionally any certificate validation or trust chain validation
 * @throws IllegalArgumentException for null input
 */
public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage)
        throws IllegalArgumentException {
    if (OutErrorMessage == null) {
        OutErrorMessage = new AtomicReference<String>();
        OutErrorMessage.set("");
    }
    if (obj == null) {
        throw new IllegalArgumentException("obj");
    }
    try {
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);

        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement(); //this is our signed node

        X509Certificate signingcert = getSigningCertificatePublicKey(docElement);

        if (signingcert != null) {
            logger.info(
                    "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString());
            if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) {
                signingcert.checkValidity();
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) {
                logger.info("verifying revocation status via OSCP for X509 public key "
                        + signingcert.getSubjectDN().toString());
                X500Principal issuerX500Principal = signingcert.getIssuerX500Principal();
                logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by "
                        + issuerX500Principal.getName() + ", attempting to retrieve certificate");
                Security.setProperty("ocsp.enable", "false");
                X509Certificate issuer = FindCertByDN(issuerX500Principal);
                if (issuer == null) {
                    OutErrorMessage.set(
                            "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. "
                                    + OutErrorMessage.get());
                    //throw new CertificateException("unable to locate the issuers certificate in the trust store");
                } else {
                    RevocationStatus check = OCSP.check(signingcert, issuer);
                    logger.info("certificate " + signingcert.getSubjectDN().toString()
                            + " revocation status is " + check.getCertStatus().toString() + " reason "
                            + check.getRevocationReason().toString());
                    if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) {
                        OutErrorMessage
                                .set("Certificate status is " + check.getCertStatus().toString() + " reason "
                                        + check.getRevocationReason().toString() + "." + OutErrorMessage.get());

                        //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString());
                    }
                }
            }
            if (map.containsKey(CHECK_REVOCATION_STATUS_CRL)
                    && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) {
                logger.info("verifying revokation status via CRL for X509 public key "
                        + signingcert.getSubjectDN().toString());

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

                X509CertSelector targetConstraints = new X509CertSelector();
                targetConstraints.setCertificate(signingcert);
                PKIXParameters params = new PKIXParameters(GetTrustStore());
                params.setRevocationEnabled(true);
                CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                CertPathValidator certPathValidator = CertPathValidator
                        .getInstance(CertPathValidator.getDefaultType());
                CertPathValidatorResult result = certPathValidator.validate(certPath, params);
                try {
                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
                    logger.info("revokation status via CRL PASSED for X509 public key "
                            + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            if (map.containsKey(CHECK_TRUST_CHAIN)
                    && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) {
                logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString());
                try {
                    PKIXParameters params = new PKIXParameters(GetTrustStore());
                    params.setRevocationEnabled(false);
                    CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert));

                    CertPathValidator certPathValidator = CertPathValidator
                            .getInstance(CertPathValidator.getDefaultType());
                    CertPathValidatorResult result = certPathValidator.validate(certPath, params);

                    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;

                    TrustAnchor ta = pkixResult.getTrustAnchor();
                    X509Certificate cert = ta.getTrustedCert();

                    logger.info(
                            "trust chain validated X509 public key " + signingcert.getSubjectDN().toString());
                } catch (Exception ex) {
                    OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "."
                            + OutErrorMessage.get());
                }
            }
            boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage);
            if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) {
                //no error message and its cryptographically valid
                return true;
            }
            return false;
        }

        //last chance validation
        logger.info(
                "signature did not have an embedded X509 public key. reverting to user specified certificate");
        //cert wasn't included in the signature, revert to some other means
        KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE));
        URL url = Thread.currentThread().getContextClassLoader()
                .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
        if (url == null) {
            try {
                url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL();
            } catch (Exception x) {
            }
        }
        if (url == null) {
            try {
                url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE));
            } catch (Exception x) {
            }
        }
        if (url == null) {
            logger.error("");
            OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and"
                    + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get());
            return false;
        }
        KeyStore.PrivateKeyEntry keyEntry = null;

        ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray());

        if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()));
        } else {
            keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS),
                    new KeyStore.PasswordProtection(
                            map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray()));
        }

        Certificate origCert = keyEntry.getCertificate();
        if (map.containsKey(CHECK_TIMESTAMPS)) {
            if (origCert.getPublicKey() instanceof X509Certificate) {
                X509Certificate x = (X509Certificate) origCert.getPublicKey();
                x.checkValidity();
            }
        }
        PublicKey validatingKey = origCert.getPublicKey();
        return verifySignature(docElement, validatingKey, OutErrorMessage);
    } catch (Exception e) {
        //throw new RuntimeException(e);
        logger.error("Error caught validating signature", e);
        OutErrorMessage.set(e.getMessage());
        return false;
    }
}

From source file:org.glite.slcs.pki.bouncycastle.CMCPKIResponse.java

/**
 * Return all X509Certificate embedded in the response.
 * /*from   w w w. ja  v a2  s  . co m*/
 * @return A Collection of X509Certificate (unordered).
 * @throws GeneralSecurityException
 */
public Collection<X509Certificate> getX509Certificates() throws GeneralSecurityException {
    X509CertSelector selector = new X509CertSelector();
    Collection<? extends Certificate> certs = certificatesStore_.getCertificates(selector);
    return (Collection<X509Certificate>) certs;
}