Skip to content

Instantly share code, notes, and snippets.

@s1monw1
Created August 24, 2017 11:25
Show Gist options
  • Save s1monw1/3571b673dfec86daed60276c14c163e6 to your computer and use it in GitHub Desktop.
Save s1monw1/3571b673dfec86daed60276c14c163e6 to your computer and use it in GitHub Desktop.
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