Java Code Examples for javax.net.ssl.X509TrustManager#getAcceptedIssuers()

The following examples show how to use javax.net.ssl.X509TrustManager#getAcceptedIssuers() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyStoreHelper.java    From syndesis with Apache License 2.0 10 votes vote down vote up
public static KeyStore defaultKeyStore()
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {

    final KeyStore defaultKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    defaultKeystore.load(null);

    final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init((KeyStore) null);

    for (final TrustManager manager : factory.getTrustManagers()) {
        final X509TrustManager x509Manager = (X509TrustManager) manager;

        final X509Certificate[] issuers = x509Manager.getAcceptedIssuers();
        for (final X509Certificate issuer : issuers) {
            final String alias = issuer.getSerialNumber().toString();
            final TrustedCertificateEntry entry = new TrustedCertificateEntry(issuer);
            defaultKeystore.setEntry(alias, entry, null);
        }
    }

    return defaultKeystore;
}
 
Example 2
Source File: TrustManagers.java    From scipio-erp with Apache License 2.0 7 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
    if (issuerTms.size() == 1) return issuerTms.get(0).getAcceptedIssuers();
    else if (issuerTms.size() == 0) return new X509Certificate[] {};

    List<X509Certificate[]> issuerLists = new ArrayList<>(issuerTms.size());
    int totalIssuers = 0;
    for(X509TrustManager tm : issuerTms) { // pre-loop to determine array size
        X509Certificate[] issuers = tm.getAcceptedIssuers();
        issuerLists.add(issuers);
        totalIssuers += issuers.length;
    }

    X509Certificate[] allIssuers = new X509Certificate[totalIssuers];
    int i = 0;
    for(X509Certificate[] issuerList : issuerLists) {
        if (issuerList.length == 0) continue;
        System.arraycopy(issuerList, 0, allIssuers, i, issuerList.length);
        i += issuerList.length;
    }
    return allIssuers;
}
 
Example 3
Source File: TrustStoreTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void builtFromJKSFile() throws Exception {

    String filePath = classLoader.getResource("truststore.jks").getFile();

    JavaKeyStoreProvider provider = new JavaKeyStoreProvider(filePath, "123456".toCharArray());
    TrustStore trustStore = new TrustStore(filePath, provider);

    assertEquals(filePath, trustStore.getFilePath());
    TrustManager[] trustManagers = trustStore.getTrustManagers();
    assertEquals(1, trustManagers.length);
    X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
    X509Certificate[] acceptedIssuers = trustManager.getAcceptedIssuers();
    assertEquals(1, acceptedIssuers.length);
    X509Certificate certificate = acceptedIssuers[0];
    assertEquals("CN=athenz.production,OU=Testing Domain,O=Athenz,ST=CA,C=US",
        certificate.getIssuerX500Principal().getName());
}
 
Example 4
Source File: ExportControlled.java    From r-course with MIT License 6 votes vote down vote up
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
    this.origTm = tm;
    this.verifyServerCert = verifyServerCertificate;

    if (verifyServerCertificate) {
        try {
            Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
            for (X509Certificate cert : tm.getAcceptedIssuers()) {
                anch.add(new TrustAnchor(cert, null));
            }
            this.validatorParams = new PKIXParameters(anch);
            this.validatorParams.setRevocationEnabled(false);
            this.validator = CertPathValidator.getInstance("PKIX");
            this.certFactory = CertificateFactory.getInstance("X.509");
        } catch (Exception e) {
            throw new CertificateException(e);
        }
    }
}
 
Example 5
Source File: KeyStoresTrustManager.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public KeyStoresTrustManager(KeyStore... keyStores) throws NoSuchAlgorithmException, KeyStoreException {
    super();

    for (KeyStore keystore : keyStores) {
        TrustManagerFactory factory = TrustManagerFactory.getInstance("JKS");
        factory.init(keystore);
        TrustManager[] tms = factory.getTrustManagers();
        if (tms.length == 0) {
            throw new NoSuchAlgorithmException("Unable to load keystore");
        }
        trustManagers.add((X509TrustManager) tms[0]);
    }

    //Build accepted issuers list
    Set<X509Certificate> issuers = new HashSet<X509Certificate>();
    for (X509TrustManager tm : trustManagers) {
        for (X509Certificate issuer : tm.getAcceptedIssuers()) {
            issuers.add(issuer);
        }
    }
    acceptedIssuers = issuers.toArray(new X509Certificate[issuers.size()]);
}
 
Example 6
Source File: ExportControlled.java    From Komondor with GNU General Public License v3.0 6 votes vote down vote up
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
    this.origTm = tm;
    this.verifyServerCert = verifyServerCertificate;

    if (verifyServerCertificate) {
        try {
            Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
            for (X509Certificate cert : tm.getAcceptedIssuers()) {
                anch.add(new TrustAnchor(cert, null));
            }
            this.validatorParams = new PKIXParameters(anch);
            this.validatorParams.setRevocationEnabled(false);
            this.validator = CertPathValidator.getInstance("PKIX");
            this.certFactory = CertificateFactory.getInstance("X.509");
        } catch (Exception e) {
            throw new CertificateException(e);
        }
    }
}
 
Example 7
Source File: TrustUtil.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public X509Certificate[] get() {
    X509TrustManager defaultTrustManager = getDefaultJavaTrustManager();

    X509Certificate[] defaultJavaTrustedCerts = defaultTrustManager.getAcceptedIssuers();

    if (defaultJavaTrustedCerts != null) {
        return defaultJavaTrustedCerts;
    } else {
        return EMPTY_CERTIFICATE_ARRAY;
    }
}
 
Example 8
Source File: TrustUtil.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public X509Certificate[] get() {
    X509TrustManager defaultTrustManager = getDefaultJavaTrustManager();

    X509Certificate[] defaultJavaTrustedCerts = defaultTrustManager.getAcceptedIssuers();

    if (defaultJavaTrustedCerts != null) {
        return defaultJavaTrustedCerts;
    } else {
        return EMPTY_CERTIFICATE_ARRAY;
    }
}
 
Example 9
Source File: TrustUtil.java    From Dream-Catcher with MIT License 5 votes vote down vote up
@Override
public X509Certificate[] get() {
    X509TrustManager defaultTrustManager = getDefaultJavaTrustManager();

    X509Certificate[] defaultJavaTrustedCerts = defaultTrustManager.getAcceptedIssuers();

    if (defaultJavaTrustedCerts != null) {
        return defaultJavaTrustedCerts;
    } else {
        return EMPTY_CERTIFICATE_ARRAY;
    }
}
 
Example 10
Source File: HadoopCMConfigurator.java    From components with Apache License 2.0 5 votes vote down vote up
private void buildCaCerts(StringBuffer caCerts, X509TrustManager xtm) throws CertificateEncodingException {
    if (xtm != null && xtm.getAcceptedIssuers().length > 0) {
        for (Certificate ca : xtm.getAcceptedIssuers()) {
            caCerts.append(CERT_BEGIN);
            caCerts.append(SEPARATOR);
            caCerts.append(Base64.getEncoder().encodeToString(ca.getEncoded()));
            caCerts.append(SEPARATOR);
            caCerts.append(CERT_END);
            caCerts.append(SEPARATOR);
        }
    }
}
 
Example 11
Source File: ReloadingX509TrustManager.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
  X509Certificate[] issuers = EMPTY;
  X509TrustManager tm = trustManagerRef.get();
  if (tm != null) {
    issuers = tm.getAcceptedIssuers();
  }
  return issuers;
}
 
Example 12
Source File: CompositeTrustManager.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public X509Certificate[] getAcceptedIssuers() {
  HashSet<X509Certificate> issuers=new HashSet<X509Certificate>();

  for (X509TrustManager mgr : managers) {
    for (X509Certificate cert : mgr.getAcceptedIssuers()) {
      issuers.add(cert);
    }
  }

  return(issuers.toArray(new X509Certificate[issuers.size()]));
}
 
Example 13
Source File: CompositeX509TrustManager.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
	List<X509Certificate> certificates = new LinkedList<>();
	for (X509TrustManager trustManager : trustManagers) {
		for (X509Certificate cert : trustManager.getAcceptedIssuers()) {
			certificates.add(cert);
		}
	}
	return certificates.toArray(new X509Certificate[certificates.size()]);
}
 
Example 14
Source File: ReloadingX509TrustManager.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
  X509Certificate[] issuers = EMPTY;
  X509TrustManager tm = trustManagerRef.get();
  if (tm != null) {
    issuers = tm.getAcceptedIssuers();
  }
  return issuers;
}
 
Example 15
Source File: LdapClientTrustStoreManager.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Return the list of accepted issuers for this trust manager.
 *
 * @return array of accepted issuers
 */
public synchronized X509Certificate[] getAcceptedIssuers()
{
    List<X509Certificate> certificates = new ArrayList<>();
    
    for ( X509TrustManager trustManager : x509TrustManagers )
    {
        for ( X509Certificate certificate : trustManager.getAcceptedIssuers() )
        { 
            certificates.add( certificate );
        }
    }
        
    return certificates.toArray( new X509Certificate[]{} );
}
 
Example 16
Source File: XMLDSigVerifier.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private void validateCertificateChain(List<X509Certificate> certList)
        throws NoSuchAlgorithmException,
        KeyStoreException,
        InvalidAlgorithmParameterException,
        CertificateException,
        CertPathValidatorException
{
    // By default on Oracle JRE, algorithm is PKIX
    TrustManagerFactory tmf = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    // 'null' will initialise the tmf with the default CA certs installed
    // with the JRE.
    tmf.init((KeyStore) null);

    X509TrustManager tm = (X509TrustManager) tmf.getTrustManagers()[0];
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    Set<TrustAnchor> anch = new HashSet<>();
    for (X509Certificate cert : tm.getAcceptedIssuers())
    {
        anch.add(new TrustAnchor(cert, null));
    }
    PKIXParameters params = new PKIXParameters(anch);
    Security.setProperty("ocsp.enable", "true");
    params.setRevocationEnabled(true);
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    try
    {
        cpv.validate(factory.generateCertPath(certList), params);
    }
    catch (CertPathValidatorException e)
    {
        System.out.println(e.getIndex());
        //if the timestamp check fails because the cert is expired
        //we allow this to continue (code 0)
        if(e.getIndex() != 0)
        {
            throw e;
        }
    }
}
 
Example 17
Source File: SslCertificateTrusterTest.java    From cloudfoundry-certificate-truster with Apache License 2.0 5 votes vote down vote up
@Test
public void appendToTruststore() throws Exception {
	// get self-signed cert
	KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
	String password = "changeit";
	keystore.load(SslCertificateTrusterTest.class.getResourceAsStream("/selfsigned.jks"), password.toCharArray());
	X509Certificate selfsigned = (X509Certificate) keystore.getCertificate("mykey");

	SslCertificateTruster.appendToTruststore(new X509Certificate[] { selfsigned });

	// verify defaultTrustManager contains cert
	TrustManagerFactory trustManagerFactory =
			TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// this will initialize with the first valid keystore
	// 1. javax.net.ssl.trustStore
	// 2. jssecerts
	// 3. cacerts
	// see https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/sun/security/ssl/TrustManagerFactoryImpl.java#L130
	trustManagerFactory.init((KeyStore) null);
	X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
	X509Certificate[] cacerts = defaultTrustManager.getAcceptedIssuers();
	for (X509Certificate certificate : cacerts) {
		if (certificate.getSubjectDN().equals(selfsigned.getSubjectDN())) {
			return;
		}
	}
	Assert.fail();
}
 
Example 18
Source File: TrustUtil.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] get() {
    X509TrustManager defaultTrustManager = getDefaultJavaTrustManager();

    X509Certificate[] defaultJavaTrustedCerts = defaultTrustManager.getAcceptedIssuers();

    if (defaultJavaTrustedCerts != null) {
        return defaultJavaTrustedCerts;
    } else {
        return EMPTY_CERTIFICATE_ARRAY;
    }
}
 
Example 19
Source File: TrustManagerBuilder.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private void addFromTrustManager(X509TrustManager trustManager) {
  for (Certificate certificate : trustManager.getAcceptedIssuers()) {
    certificates.add(certificate);
  }
}
 
Example 20
Source File: SSLImplementation.java    From tn5250j with GNU General Public License v2.0 4 votes vote down vote up
public void checkServerTrusted(X509Certificate[] chain, String type)
		throws CertificateException {
	try {
		for (int i = 0; i < userTrustManagers.length; i++) {
			if (userTrustManagers[i] instanceof X509TrustManager) {
				X509TrustManager trustManager = (X509TrustManager) userTrustManagers[i];
				X509Certificate[] calist = trustManager
						.getAcceptedIssuers();
				if (calist.length > 0) {
					trustManager.checkServerTrusted(chain, type);
				} else {
					throw new CertificateException(
							"Empty list of accepted issuers (a.k.a. root CA list).");
				}
			}
		}
		return;
	} catch (CertificateException ce) {
		X509Certificate cert = chain[0];
		String certInfo = "Version: " + cert.getVersion() + "\n";
		certInfo = certInfo.concat("Serial Number: "
				+ cert.getSerialNumber() + "\n");
		certInfo = certInfo.concat("Signature Algorithm: "
				+ cert.getSigAlgName() + "\n");
		certInfo = certInfo.concat("Issuer: "
				+ cert.getIssuerDN().getName() + "\n");
		certInfo = certInfo.concat("Valid From: " + cert.getNotBefore()
				+ "\n");
		certInfo = certInfo
				.concat("Valid To: " + cert.getNotAfter() + "\n");
		certInfo = certInfo.concat("Subject DN: "
				+ cert.getSubjectDN().getName() + "\n");
		certInfo = certInfo.concat("Public Key: "
				+ cert.getPublicKey().getFormat() + "\n");

		int accept = JOptionPane
				.showConfirmDialog(null, certInfo, "Unknown Certificate - Do you accept it?",
						javax.swing.JOptionPane.YES_NO_OPTION);
		if (accept != JOptionPane.YES_OPTION) {
			throw new java.security.cert.CertificateException(
					"Certificate Rejected");
		}

		int save = JOptionPane.showConfirmDialog(null,
				"Remember this certificate?", "Save Certificate",
				javax.swing.JOptionPane.YES_NO_OPTION);

		if (save == JOptionPane.YES_OPTION) {
			try {
				userks.setCertificateEntry(cert.getSubjectDN().getName(),
						cert);
				userks.store(new FileOutputStream(userKsPath),
						userksPassword);
			} catch (Exception e) {
				logger.error("Error saving certificate [" + e.getMessage()
						+ "]");
				e.printStackTrace();
			}
		}
	}

}