Last active
August 24, 2017 16:44
-
-
Save s1monw1/baadbeb280a3ac5946510a28b0849a8d to your computer and use it in GitHub Desktop.
This file contains 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
public class TLSConfiguration { ... } | |
public class StoreType { ... } | |
public void connectSSL(String host, int port, | |
TLSConfiguration tlsConfiguration) throws IOException { | |
String tlsVersion = tlsConfiguration.getProtocol(); | |
StoreType keystore = tlsConfiguration.getKeystore(); | |
StoreType trustStore = tlsConfiguration.getTruststore(); | |
try { | |
SSLContext ctx = SSLContext.getInstance(tlsVersion); | |
TrustManager[] tm = null; | |
KeyManager[] km = null; | |
if (trustStore != null) { | |
tm = getTrustManagers(trustStore.getFilename(), | |
trustStore.getPassword().toCharArray(), | |
trustStore.getStoretype(), trustStore.getAlgorithm()); | |
} | |
if (keystore != null) { | |
km = createKeyManagers(keystore.getFilename(), | |
keystore.getPassword(), | |
keystore.getStoretype(), keystore.getAlgorithm()); | |
} | |
ctx.init(km, tm, new SecureRandom()); | |
SSLSocketFactory sslSocketFactory = ctx.getSocketFactory(); | |
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket( | |
host, port); | |
sslSocket.startHandshake(); | |
} catch (Exception e) { | |
throw new IllegalStateException("Not working :-(", e); | |
} | |
} | |
private static TrustManager[] getTrustManagers( | |
final String path, final char[] password, | |
final String storeType, final String algorithm) throws Exception { | |
TrustManagerFactory fac = TrustManagerFactory.getInstance( | |
algorithm == null ? "SunX509" : algorithm); | |
KeyStore ks = KeyStore.getInstance( | |
storeType == null ? "JKS" : storeType); | |
Path storeFile = Paths.get(path); | |
ks.load(new FileInputStream(storeFile.toFile()), password); | |
fac.init(ks); | |
return fac.getTrustManagers(); | |
} | |
private static KeyManager[] createKeyManagers( | |
final String filename, final String password, | |
final String keyStoreType, final String algorithm) throws Exception { | |
KeyStore ks = KeyStore.getInstance( | |
keyStoreType == null ? "PKCS12" : keyStoreType); | |
ks.load(new FileInputStream(filename), password.toCharArray()); | |
KeyManagerFactory kmf = KeyManagerFactory.getInstance( | |
algorithm == null ? "SunX509" : algorithm); | |
kmf.init(ks, password.toCharArray()); | |
return kmf.getKeyManagers(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment