Created
November 18, 2014 11:39
-
-
Save anonymous/d4c86b3c43731e7b63c4 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
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