Created
August 24, 2017 11:25
-
-
Save s1monw1/3571b673dfec86daed60276c14c163e6 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
fun connectSSL(host: String, port: Int, protocols: List<String>, kmConfig: Store?, tmConfig: Store?){ | |
val context = createSSLContext(protocols, kmConfig, tmConfig) | |
val sslSocket = context.socketFactory.createSocket(host, port) as SSLSocket | |
sslSocket.startHandshake() | |
} | |
fun createSSLContext(protocols: List<String>, kmConfig: Store?, tmConfig: Store?): SSLContext { | |
if (protocols.isEmpty()) { | |
throw IllegalArgumentException("At least one protocol must be provided.") | |
} | |
return SSLContext.getInstance(protocols[0]).apply { | |
val keyManagerFactory = kmConfig?.let { conf -> | |
val defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm() | |
KeyManagerFactory.getInstance(conf.algorithm ?: defaultAlgorithm).apply { | |
init(loadKeyStore(conf), conf.password) | |
} | |
} | |
val trustManagerFactory = tmConfig?.let { conf -> | |
val defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm() | |
TrustManagerFactory.getInstance(conf.algorithm ?: defaultAlgorithm).apply { | |
init(loadKeyStore(conf)) | |
} | |
} | |
init(keyManagerFactory?.keyManagers, trustManagerFactory?.trustManagers, | |
SecureRandom()) | |
} | |
} | |
fun loadKeyStore(store: Store) = KeyStore.getInstance(store.fileType).apply { | |
load(FileInputStream(store.name), store.password) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment