001/* 002 * Copyright 2015-2024 the original author or authors 003 * 004 * This software is licensed under the Apache License, Version 2.0, 005 * the GNU Lesser General Public License version 2 or later ("LGPL") 006 * and the WTFPL. 007 * You may choose either license to govern your use of this software only 008 * upon the condition that you accept all of the terms of either 009 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL. 010 */ 011package org.minidns.dane; 012 013import java.security.KeyStore; 014import java.security.KeyStoreException; 015import java.security.NoSuchAlgorithmException; 016 017import javax.net.ssl.TrustManager; 018import javax.net.ssl.TrustManagerFactory; 019import javax.net.ssl.X509TrustManager; 020 021public class X509TrustManagerUtil { 022 023 public static X509TrustManager getDefault() { 024 return getDefault(null); 025 } 026 027 public static X509TrustManager getDefault(KeyStore keyStore) { 028 String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); 029 TrustManagerFactory trustManagerFactory; 030 try { 031 trustManagerFactory = TrustManagerFactory.getInstance(defaultAlgorithm); 032 trustManagerFactory.init(keyStore); 033 } catch (NoSuchAlgorithmException | KeyStoreException e) { 034 throw new AssertionError(e); 035 } 036 037 for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { 038 if (trustManager instanceof X509TrustManager) { 039 return (X509TrustManager) trustManager; 040 } 041 } 042 throw new AssertionError("No trust manager for the default algorithm " + defaultAlgorithm + " found"); 043 } 044}