Created
July 30, 2015 13:43
-
-
Save barlog-m/bd6b2825c9eabcaeddbd to your computer and use it in GitHub Desktop.
Loading default java trusted store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.security.KeyStore; | |
import java.security.KeyStoreException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.Security; | |
import java.security.cert.CertificateException; | |
public final class DefaultTrustStoreUtils { | |
private DefaultTrustStoreUtils() { | |
} | |
public static KeyStore loadDefaultTrustStore() { | |
Path location = null; | |
String type = null; | |
String password = null; | |
String locationProperty = System.getProperty("javax.net.ssl.trustStore"); | |
if ((null != locationProperty) && (locationProperty.length() > 0)) { | |
Path p = Paths.get(locationProperty); | |
File f = p.toFile(); | |
if (f.exists() && f.isFile() && f.canRead()) { | |
location = p; | |
} | |
} else { | |
String javaHome = System.getProperty("java.home"); | |
location = Paths.get(javaHome, "lib", "security", "jssecacerts"); | |
if (!location.toFile().exists()) { | |
location = Paths.get(javaHome, "lib", "security", "cacerts"); | |
} | |
} | |
String passwordProperty = System.getProperty("javax.net.ssl.trustStorePassword"); | |
if ((null != passwordProperty) && (passwordProperty.length() > 0)) { | |
password = passwordProperty; | |
} else { | |
password = "changeit"; | |
} | |
String typeProperty = System.getProperty("javax.net.ssl.trustStoreType"); | |
if ((null != typeProperty) && (typeProperty.length() > 0)) { | |
type = passwordProperty; | |
} else { | |
type = KeyStore.getDefaultType(); | |
} | |
KeyStore trustStore = null; | |
try { | |
trustStore = KeyStore.getInstance(type, Security.getProvider("SUN")); | |
} catch (KeyStoreException e) { | |
throw new RuntimeException(e); | |
} | |
try (InputStream is = Files.newInputStream(location)) { | |
trustStore.load(is, password.toCharArray()); | |
} catch (IOException | |
| CertificateException | |
| NoSuchAlgorithmException e) { | |
throw new RuntimeException(e); | |
} | |
return trustStore; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment