Create a gist now

Instantly share code, notes, and snippets.

anonymous /SslManager
Created Nov 18, 2014

What would you like to do?
import java.io.{File, FileInputStream}
import java.security.KeyStore
import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLEngine, TrustManagerFactory}
class SslManager(keyStoreFile: File, trustStoreFile: File, keyStorePw: String, trustStorePw: String) {
private[this] val PROTOCOL = "TLS"
val context: SSLContext = {
// Set up key manager factory to use our key store (server certificates)
val ks = KeyStore.getInstance("JKS")
val is = new FileInputStream(keyStoreFile)
ks.load(is, keyStorePw.toCharArray)
is.close()
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
kmf.init(ks, keyStorePw.toCharArray)
// Setup trust store (client certificates)
val trustManagers = {
val ts = KeyStore.getInstance("JKS")
val tis = new FileInputStream(trustStoreFile)
ts.load(tis, trustStorePw.toCharArray)
tis.close()
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
trustManagerFactory.init(ts)
trustManagerFactory.getTrustManagers
}
// Initialize the SSLContext to work with our key managers and optional trust store
val ret = SSLContext.getInstance(PROTOCOL)
ret.init(kmf.getKeyManagers, trustManagers, null)
ret
}
/**
* Creates an SSL engine for encoding/decoding SSL traffic
*/
def createSSLEngine(client: Boolean): SSLEngine = {
val engine = context.createSSLEngine()
engine.setNeedClientAuth(true)
engine.setUseClientMode(client)
engine
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment