Tuesday, 10 November 2015

Mutual SSL with HTTPClient in Scala

Follows a Scala code snippet to use mutual SSL when talking to a server. This code uses Apache HC
package org.tj.mssl

import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import java.security.KeyStore
import java.io.FileInputStream
import java.io.File
import org.apache.http.conn.ssl.TrustStrategy
import java.security.cert.X509Certificate
import org.apache.http.ssl.SSLContexts
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.impl.client.HttpClients

object MutualSSL {

  def buildHTTPClient(useSSL: Boolean): CloseableHttpClient = {
    if (!useSSL) {
    } else {
      val keyStorePassword = "[your keystore password]".toCharArray()
      val importedKeyPassword = "[your imported key password]".toCharArray()
      val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)
      val keyStorePath = new FileInputStream(new File("[your key store path .jks]"))
      keyStore.load(keyStorePath, keyStorePassword)
      val trustStrategy = new TrustStrategy() {
        override def isTrusted(x509Certs: Array[X509Certificate], s: String): Boolean = true
      val sslContext = SSLContexts.custom()
                                  .loadKeyMaterial(keyStore, importedKeyPassword)
      val sslSocketFactory = new SSLConnectionSocketFactory(sslContext)
  def main(args: Array[String]): Unit = {

No comments:

Blog Archive