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:MainClass.java

public static void main(String args[]) throws Exception {
    X509CertSelector selec = new X509CertSelector();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    System.out.println(selec.match(c));
    selec.setIssuer("CN=Peter,OU=Network Center," + "O=University,L=ZB,ST=Vancouver,C=CN");

    System.out.println(selec.match(c));

    Calendar cld = Calendar.getInstance();
    int year = Integer.parseInt(args[1]);
    int month = Integer.parseInt(args[2]) - 1;
    int day = Integer.parseInt(args[3]);
    cld.set(year, month, day);/* w ww.j  av  a  2s  .c o  m*/
    Date d = cld.getTime();
    selec.setCertificateValid(d);

    System.out.println(selec.match(c));
    BigInteger sn = new BigInteger("1039056963");
    selec.setSerialNumber(sn);

    System.out.println(selec.match(c));
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);//from ww  w  .j av a  2  s.c  o m

    CertStoreParameters cparam = new CollectionCertStoreParameters(mylist);
    CertStore cs = CertStore.getInstance("Collection", cparam);
    X509CertSelector selec = new X509CertSelector();
    selec.setIssuer("CN=YourName,OU=Network Center," + "O=University,L=ZB,ST=Toronto,C=CN");
    Set clct = (Set) cs.getCertificates(selec);
    Object o[] = clct.toArray();
    for (int i = 0; i < o.length; i++) {
        X509Certificate ct = (X509Certificate) o[i];
        System.out.println("Certificate " + i + " ");
        System.out.println(ct.getSubjectDN());

    }
}

From source file:mitm.common.security.cms.KeyTransRecipientIdImpl.java

@Override
public CertSelector getSelector() throws IOException {
    X509CertSelector selector = new X509CertSelector();

    selector.setIssuer(issuer);//w  w  w.j a  v a  2s. c  o m
    selector.setSerialNumber(serialNumber);

    if (subjectKeyIdentifier != null) {
        /* 
         * X509CertSelector expects a DER encoded subjectKeyIdentifier.
         */
        X509CertSelectorBuilder.setSubjectKeyIdentifier(selector, subjectKeyIdentifier);
    }

    return selector;
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Verify that a given certificate is trusted.
 * /*from ww w.j  a v  a 2  s  . c om*/
 * @param chain certificate chain
 * @throws CertPathBuilderException thrown on verification error
 * @throws CertificateVerificationException thrown on any error
 */
public void verify(X509Certificate[] chain) throws CertificateVerificationException, CertPathBuilderException {
    try {
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(chain[0]);

        // Root certificates
        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
        for (X509Certificate rootCert : rootCerts) {
            trustAnchors.add(new TrustAnchor(rootCert, null));
        }

        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);

        pkixParams.setRevocationEnabled(true);

        // Built-in intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts)));

        // Additional intermediate certificates
        pkixParams.addCertStore(
                CertStore.getInstance("Collection", new CollectionCertStoreParameters(Arrays.asList(chain))));

        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
        builder.build(pkixParams); // Will error on failure to verify
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateVerificationException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateVerificationException(e);
    }
}

From source file:mitm.application.djigzo.ws.impl.CACertStoreViewWSImpl.java

private CloseableIterator<? extends X509CertStoreEntry> getIterator(CACertStoreViewFilter filter)
        throws CertStoreException {
    X509CertSelector selector = new X509CertSelector();

    /*/*  w w  w. j a  va2  s . c o  m*/
     * Make sure we only get CA certificates
     */
    selector.setBasicConstraints(0);

    Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.KEYCERTSIGN);

    if (filter == CACertStoreViewFilter.CRL_SIGN) {
        keyUsage.add(KeyUsageType.CRLSIGN);
    }

    selector.setKeyUsage(KeyUsageType.getKeyUsageArray(keyUsage));

    return certStore.getCertStoreIterator(selector, MissingKeyAlias.NOT_ALLOWED, null, null);
}

From source file:com.vmware.identity.idm.IDPConfig.java

/**
 * Validate the chain is in the required order user's certificate first,
 * root CA certificate last including the case of only root CA is present.
 * Also validate that there is only one chain, which consists of all the
 * certificates listed./*from w  w w .  j  a  va2s .com*/
 */
private static boolean validateSingleX509CertChain(List<X509Certificate> chain)
        throws ExternalIDPExtraneousCertsInCertChainException, ExternalIDPCertChainInvalidTrustedPathException {
    final String ALGO_PKIX = "PKIX"; //for X.509

    final String CERTSTORE_PROVIDER_COLLECTION = "Collection";

    try {
        Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
        anchors.add(new TrustAnchor(chain.get(chain.size() - 1), null));

        X509CertSelector targetCertSelector = new X509CertSelector();
        targetCertSelector.setCertificate(chain.get(0));

        CertStore builderStore = CertStore.getInstance(CERTSTORE_PROVIDER_COLLECTION,
                new CollectionCertStoreParameters(chain));

        PKIXBuilderParameters buildParams = new PKIXBuilderParameters(anchors, targetCertSelector);
        buildParams.addCertStore(builderStore);
        buildParams.setRevocationEnabled(false);

        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(ALGO_PKIX);
        CertPathBuilderResult builderResult = pathBuilder.build(buildParams);

        if (chain.size() - 1 != builderResult.getCertPath().getCertificates().size()) {
            throw new ExternalIDPExtraneousCertsInCertChainException(chain);
        }
        return true;

    } catch (CertPathBuilderException cpbe) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(cpbe.getMessage(), chain); // no need to chain the exception.
    } catch (GeneralSecurityException gse) {
        throw new ExternalIDPCertChainInvalidTrustedPathException(gse.getMessage(), chain);
    }
}

From source file:mitm.common.security.certificate.GenerateTestCertificates.java

private void exportToP7B(KeyStore keyStore, File file) throws Exception {
    X509BasicCertStore certStore = new BasicCertStoreKeyStore(keyStore);

    X509CertSelector selector = new X509CertSelector();

    Collection<X509Certificate> certificates = certStore.getCertificates(selector);

    CertificateUtils.writeCertificates(certificates, file);
}

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Create and init PKIXBuilderParameters for CertPathBuilder.
 *
 * @param endCert/*from  www  .  ja  va2  s.  com*/
 *            the target user certificate to use for building certificate
 *            path
 * @return
 * @throws CertificatePathBuildingException
 */
private PKIXBuilderParameters CreatePKIXBuilderParameters(X509Certificate endCert)
        throws CertificatePathBuildingException {
    X509CertSelector targetConstraints = new X509CertSelector();
    targetConstraints.setCertificate(endCert);
    PKIXBuilderParameters params;

    try {
        params = new PKIXBuilderParameters(trustStore, targetConstraints);

        // Do not validate the certificate at cert path building stage.
        // This would result in unknown failures.
        params.setRevocationEnabled(false);
    } catch (KeyStoreException e) {
        throw new CertificatePathBuildingException(
                "Error creating PKIXBuilderParameters: Please check trust store" + e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificatePathBuildingException("Error creating PKIXBuilderParameters:" + e.getMessage(), e);
    } catch (Throwable e) {
        // have this block in case a new type of error was thrown
        throw new CertificatePathBuildingException("Error creating PKIXBuilderParameters:" + e.getMessage(), e);
    }

    Collection<Object> certCollection = new ArrayList<Object>();
    // add trusted CAs to the collection
    addCertificateCandidates(endCert, certCollection);

    if (!certCollection.isEmpty()) {
        try {
            CertStore certStore = CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(certCollection));
            params.addCertStore(certStore);
        } catch (InvalidAlgorithmParameterException e) {
            throw new CertificatePathBuildingException(
                    "Error creating CertStore for PKIXBuilderParameters:" + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new CertificatePathBuildingException(
                    "Error creating CertStore for  PKIXBuilderParameters:" + e.getMessage(), e);
        }
    } else {
        logger.debug("Revocation check: CRL list empty");
    }
    return params;

}

From source file:mitm.common.security.certpath.CertPathBuilderSpeedTest.java

@Test
public void testLoadCertificates() throws Exception {
    long start = System.currentTimeMillis();

    X509CertSelector selector = new X509CertSelector();

    CloseableIterator<X509Certificate> it = certStoreParams.getCertStore().getCertificateIterator(selector);

    int i = 0;/*from w ww .  j  a v  a2s  .c  om*/

    while (it.hasNext()) {
        X509Certificate certificate = it.next();

        assertNotNull(certificate);

        i++;

        if (i == 10000) {
            break;
        }
    }
    // close it again (should not be a problem);
    it.close();

    assertTrue(it.isClosed());

    // close it again (should not be a problem);
    it.close();

    double secondsPerCertificate = ((System.currentTimeMillis() - start) * 0.001 / i);

    System.out.println("Total certificates: " + i + ". seconds / certificate: " + secondsPerCertificate);

    if (secondsPerCertificate > 9E-4) {
        /***************************************************
         * Note: This might fail on slower systems!!
         ***************************************************/
        fail("Seconds / certificate too slow. Note: This might fail on slower systems!!!");
    }
}

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

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

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

    X509CertSelector selector = new X509CertSelector();

    selector.setSerialNumber(new BigInteger("1"));
    selector.setIssuer("CN=No CRL CA, O=Test Certificates, C=US");

    PKIXCertPathBuilderResult result = getCertPathBuilderResult(selector);

    CertPath certPath = result.getCertPath();

    TrustAnchor trustAnchor = result.getTrustAnchor();

    assertNotNull(trustAnchor);
    assertEquals("CN=Trust Anchor, O=Test Certificates, C=US",
            trustAnchor.getTrustedCert().getSubjectX500Principal().toString());

    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());
}