javax.net.ssl.KeyManagerFactory Scala Examples
The following examples show how to use javax.net.ssl.KeyManagerFactory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
package lol.http import java.security.KeyStore import java.security.SecureRandom import java.security.cert.X509Certificate import javax.net.ssl.{SSLContext, KeyManagerFactory, X509TrustManager} import org.http4s.blaze.util.BogusKeystore lazy val selfSigned = new ServerConfiguration({ val ksStream = BogusKeystore.asInputStream() val ks = KeyStore.getInstance("JKS") ks.load(ksStream, BogusKeystore.getKeyStorePassword) val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()) kmf.init(ks, BogusKeystore.getCertificatePassword) val sslContext = SSLContext.getInstance("SSL") sslContext.init(kmf.getKeyManagers(), null, null) sslContext }, "selfSigned") }
Example 2
Source File: SSLContextHelper.scala From iotchain with MIT License | 5 votes |
package jbok.crypto.ssl import java.nio.file.Paths import java.security.KeyStore import cats.effect.Sync import cats.implicits._ import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLEngine, TrustManagerFactory} import jbok.common.FileUtil import jbok.common.log.Logger final class ClientSSLEngine(val engine: SSLEngine) extends AnyVal final class ServerSSLEngine(val engine: SSLEngine) extends AnyVal object SSLContextHelper { def apply[F[_]](config: SSLConfig)(implicit F: Sync[F]): F[Option[SSLContext]] = if (!config.enabled) { F.pure(None) } else { Logger[F].i(s"init SSLContext from keyStore=${config.keyStorePath} trustStore=${config.trustStorePath}") >> FileUtil[F] .inputStream(Paths.get(config.keyStorePath)) .use { keyStoreIS => FileUtil[F].inputStream(Paths.get(config.trustStorePath)).use { trustStoreIS => F.delay { val keyStore = KeyStore.getInstance("JKS") keyStore.load(keyStoreIS, "changeit".toCharArray) val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm) keyManagerFactory.init(keyStore, "changeit".toCharArray) val trustStore = KeyStore.getInstance("JKS") trustStore.load(trustStoreIS, "changeit".toCharArray) val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm) trustManagerFactory.init(trustStore) val ctx = SSLContext.getInstance(config.protocol) ctx.init(keyManagerFactory.getKeyManagers, trustManagerFactory.getTrustManagers, null) ctx } } } .map(_.some) } def clientEngine(ctx: SSLContext): ClientSSLEngine = { val engine = ctx.createSSLEngine() engine.setUseClientMode(true) engine.setNeedClientAuth(true) new ClientSSLEngine(engine) } def serverEngine(ctx: SSLContext): ServerSSLEngine = { val engine = ctx.createSSLEngine() engine.setUseClientMode(false) engine.setNeedClientAuth(true) new ServerSSLEngine(engine) } }
Example 3
Source File: JsonRpcHttpsServer.scala From mantis with Apache License 2.0 | 5 votes |
package io.iohk.ethereum.jsonrpc.server import java.io.{File, FileInputStream} import java.security.{KeyStore, SecureRandom} import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory} import akka.actor.ActorSystem import akka.http.scaladsl.model.headers.HttpOriginRange import akka.http.scaladsl.{ConnectionContext, Http} import akka.stream.ActorMaterializer import io.iohk.ethereum.jsonrpc.JsonRpcController import io.iohk.ethereum.jsonrpc.server.JsonRpcHttpsServer.HttpsSetupResult import io.iohk.ethereum.jsonrpc.server.JsonRpcServer.JsonRpcServerConfig import io.iohk.ethereum.utils.Logger import scala.concurrent.ExecutionContext.Implicits.global import scala.io.Source import scala.util.{Failure, Success, Try} class JsonRpcHttpsServer(val jsonRpcController: JsonRpcController, config: JsonRpcServerConfig, secureRandom: SecureRandom)(implicit val actorSystem: ActorSystem) extends JsonRpcServer with Logger { def run(): Unit = { implicit val materializer = ActorMaterializer() val maybeSslContext = validateCertificateFiles(config.certificateKeyStorePath, config.certificateKeyStoreType, config.certificatePasswordFile).flatMap{ case (keystorePath, keystoreType, passwordFile) => val passwordReader = Source.fromFile(passwordFile) try { val password = passwordReader.getLines().mkString obtainSSLContext(keystorePath, keystoreType, password) } finally { passwordReader.close() } } val maybeHttpsContext = maybeSslContext.map(sslContext => ConnectionContext.https(sslContext)) maybeHttpsContext match { case Right(httpsContext) => Http().setDefaultServerHttpContext(httpsContext) val bindingResultF = Http().bindAndHandle(route, config.interface, config.port, connectionContext = httpsContext) bindingResultF onComplete { case Success(serverBinding) => log.info(s"JSON RPC HTTPS server listening on ${serverBinding.localAddress}") case Failure(ex) => log.error("Cannot start JSON HTTPS RPC server", ex) } case Left(error) => log.error(s"Cannot start JSON HTTPS RPC server due to: $error") } } private def validateCertificateFiles(maybeKeystorePath: Option[String], maybeKeystoreType: Option[String], maybePasswordFile: Option[String]): HttpsSetupResult[(String, String, String)] = (maybeKeystorePath, maybeKeystoreType, maybePasswordFile) match { case (Some(keystorePath), Some(keystoreType), Some(passwordFile)) => val keystoreDirMissing = !new File(keystorePath).isFile val passwordFileMissing = !new File(passwordFile).isFile if(keystoreDirMissing && passwordFileMissing) Left("Certificate keystore path and password file configured but files are missing") else if(keystoreDirMissing) Left("Certificate keystore path configured but file is missing") else if(passwordFileMissing) Left("Certificate password file configured but file is missing") else Right((keystorePath, keystoreType, passwordFile)) case _ => Left("HTTPS requires: certificate-keystore-path, certificate-keystore-type and certificate-password-file to be configured") } override def corsAllowedOrigins: HttpOriginRange = config.corsAllowedOrigins } object JsonRpcHttpsServer { type HttpsSetupResult[T] = Either[String, T] }
Example 4
Source File: Https.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.common import java.io.{FileInputStream, InputStream} import java.security.{KeyStore, SecureRandom} import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory} import akka.http.scaladsl.ConnectionContext import akka.stream.TLSClientAuth import com.typesafe.sslconfig.akka.AkkaSSLConfig object Https { case class HttpsConfig(keystorePassword: String, keystoreFlavor: String, keystorePath: String, clientAuth: String) def getCertStore(password: Array[Char], flavor: String, path: String): KeyStore = { val cs: KeyStore = KeyStore.getInstance(flavor) val certStore: InputStream = new FileInputStream(path) cs.load(certStore, password) cs } def connectionContext(httpsConfig: HttpsConfig, sslConfig: Option[AkkaSSLConfig] = None) = { val keyFactoryType = "SunX509" val clientAuth = { if (httpsConfig.clientAuth.toBoolean) Some(TLSClientAuth.need) else Some(TLSClientAuth.none) } val keystorePassword = httpsConfig.keystorePassword.toCharArray val keyStore: KeyStore = KeyStore.getInstance(httpsConfig.keystoreFlavor) val keyStoreStream: InputStream = new FileInputStream(httpsConfig.keystorePath) keyStore.load(keyStoreStream, keystorePassword) val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance(keyFactoryType) keyManagerFactory.init(keyStore, keystorePassword) // Currently, we are using the keystore as truststore as well, because the clients use the same keys as the // server for client authentication (if enabled). // So this code is guided by https://doc.akka.io/docs/akka-http/10.0.9/scala/http/server-side-https-support.html // This needs to be reworked, when we fix the keys and certificates. val trustManagerFactory: TrustManagerFactory = TrustManagerFactory.getInstance(keyFactoryType) trustManagerFactory.init(keyStore) val sslContext: SSLContext = SSLContext.getInstance("TLS") sslContext.init(keyManagerFactory.getKeyManagers, trustManagerFactory.getTrustManagers, new SecureRandom) ConnectionContext.https(sslContext, sslConfig, clientAuth = clientAuth) } }
Example 5
Source File: SSLSupport.scala From sparta with Apache License 2.0 | 5 votes |
package com.stratio.sparkta.serving.api.ssl import java.io.FileInputStream import java.security.{KeyStore, SecureRandom} import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory} import com.stratio.sparta.serving.api.helpers.SpartaHelper.log import com.stratio.sparta.serving.core.config.SpartaConfig import spray.io._ import scala.util.{Failure, Success, Try} trait SSLSupport { implicit def sslContext: SSLContext = { val context = SSLContext.getInstance("TLS") if(isHttpsEnabled) { val keyStoreResource = SpartaConfig.apiConfig.get.getString("certificate-file") val password = SpartaConfig.apiConfig.get.getString("certificate-password") val keyStore = KeyStore.getInstance("jks") keyStore.load(new FileInputStream(keyStoreResource), password.toCharArray) val keyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(keyStore, password.toCharArray) val trustManagerFactory = TrustManagerFactory.getInstance("SunX509") trustManagerFactory.init(keyStore) context.init(keyManagerFactory.getKeyManagers, trustManagerFactory.getTrustManagers, new SecureRandom) } context } implicit def sslEngineProvider: ServerSSLEngineProvider = { ServerSSLEngineProvider { engine => engine.setEnabledCipherSuites(Array( "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA")) engine.setEnabledProtocols(Array( "TLSv1.2" )) engine } } def isHttpsEnabled: Boolean = SpartaConfig.getSprayConfig match { case Some(config) => Try(config.getValue("ssl-encryption")) match { case Success(value) => "on".equals(value.unwrapped()) case Failure(e) => log.error("Incorrect value in ssl-encryption option, setting https disabled", e) false } case None => log.warn("Impossible to get spray config, setting https disabled") false } }
Example 6
Source File: UsesSslContext.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package redis import java.io.FileInputStream import java.security.{KeyStore, SecureRandom} import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLEngine, TrustManagerFactory} trait UsesSslContext { lazy val sslContext: SSLContext = SSLContext.getInstance("TLSv1.2").setup { sslc => val ks = KeyStore.getInstance("PKCS12") ks.load(new FileInputStream("./tls/redis.p12"), Array.empty) val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm) kmf.init(ks, Array.empty) val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm) tmf.init(ks) sslc.init(kmf.getKeyManagers, tmf.getTrustManagers, new SecureRandom) } }
Example 7
Source File: package.scala From hail with MIT License | 5 votes |
package is.hail.services import is.hail.utils._ import org.json4s.{DefaultFormats, Formats} import java.io.{File, FileInputStream} import java.security.KeyStore import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory} import org.apache.log4j.{LogManager, Logger} import org.json4s.jackson.JsonMethods class NoSSLConfigFound( message: String, cause: Throwable ) extends Exception(message, cause) { def this() = this(null, null) def this(message: String) = this(message, null) } case class SSLConfig( outgoing_trust: String, outgoing_trust_store: String, incoming_trust: String, incoming_trust_store: String, key: String, cert: String, key_store: String) package object tls { lazy val log: Logger = LogManager.getLogger("is.hail.tls") private[this] lazy val _getSSLConfig: SSLConfig = { var configFile = System.getenv("HAIL_SSL_CONFIG_FILE") if (configFile == null) configFile = "/ssl-config/ssl-config.json" if (!new File(configFile).isFile) throw new NoSSLConfigFound(s"no ssl config file found at $configFile") log.info(s"ssl config file found at $configFile") using(new FileInputStream(configFile)) { is => implicit val formats: Formats = DefaultFormats JsonMethods.parse(is).extract[SSLConfig] } } lazy val getSSLContext: SSLContext = { val sslConfig = _getSSLConfig val pw = "dummypw".toCharArray val ks = KeyStore.getInstance("PKCS12") using(new FileInputStream(sslConfig.key_store)) { is => ks.load(is, pw) } val kmf = KeyManagerFactory.getInstance("SunX509") kmf.init(ks, pw) val ts = KeyStore.getInstance("JKS") using(new FileInputStream(sslConfig.outgoing_trust_store)) { is => ts.load(is, pw) } val tmf = TrustManagerFactory.getInstance("SunX509") tmf.init(ts) val ctx = SSLContext.getInstance("TLS") ctx.init(kmf.getKeyManagers, tmf.getTrustManagers, null) ctx } }
Example 8
Source File: Main.scala From akka-grpc with Apache License 2.0 | 5 votes |
package example.myapp import java.io.InputStream import java.security.{KeyStore, SecureRandom} import javax.net.ssl.{KeyManagerFactory, SSLContext} import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.grpc.scaladsl.ServiceHandler import akka.http.scaladsl.{Http2, HttpsConnectionContext} import example.myapp.echo.EchoServiceImpl import example.myapp.echo.grpc.EchoServiceHandler import example.myapp.helloworld.GreeterServiceImpl import example.myapp.helloworld.grpc.GreeterServiceHandler object Main extends App { implicit val system = ActorSystem() implicit val mat = ActorMaterializer() val echoHandler = EchoServiceHandler.partial(new EchoServiceImpl) val greeterHandler = GreeterServiceHandler.partial(new GreeterServiceImpl) val serviceHandler = ServiceHandler.concatOrNotFound(echoHandler, greeterHandler) Http2().bindAndHandleAsync( serviceHandler, interface = "localhost", port = 8443, parallelism = 256, // Needed to allow running multiple requests concurrently, see https://github.com/akka/akka-http/issues/2145 connectionContext = serverHttpContext()) private def serverHttpContext() = { // never put passwords into code! val password = "abcdef".toCharArray val ks = KeyStore.getInstance("PKCS12") ks.load(Option(getClass.getClassLoader.getResourceAsStream("server.p12")).get, password) val keyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(ks, password) val context = SSLContext.getInstance("TLS") context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom) new HttpsConnectionContext(context) } }
Example 9
Source File: AkkaGrpcServerScala.scala From akka-grpc with Apache License 2.0 | 5 votes |
package akka.grpc.interop import java.io.FileInputStream import java.nio.file.{ Files, Paths } import java.security.cert.CertificateFactory import java.security.spec.PKCS8EncodedKeySpec import java.security.{ KeyFactory, KeyStore, SecureRandom } import scala.concurrent.duration._ import akka.actor.ActorSystem import akka.util.ByteString import akka.http.scaladsl.Http.ServerBinding import akka.http.scaladsl.model.{ HttpRequest, HttpResponse } import akka.http.scaladsl.{ Http2, HttpsConnectionContext } import akka.stream.SystemMaterializer import io.grpc.internal.testing.TestUtils import javax.net.ssl.{ KeyManagerFactory, SSLContext } import scala.concurrent.{ Await, Future } case class AkkaGrpcServerScala(serverHandlerFactory: ActorSystem => HttpRequest => Future[HttpResponse]) extends GrpcServer[(ActorSystem, ServerBinding)] { override def start() = { implicit val sys = ActorSystem() implicit val mat = SystemMaterializer(sys).materializer val testService = serverHandlerFactory(sys) val bindingFuture = Http2().bindAndHandleAsync( testService, interface = "127.0.0.1", port = 0, parallelism = 256, // TODO remove once https://github.com/akka/akka-http/pull/2146 is merged connectionContext = serverHttpContext()) val binding = Await.result(bindingFuture, 10.seconds) (sys, binding) } override def stop(binding: (ActorSystem, ServerBinding)) = binding match { case (sys, binding) => sys.log.info("Exception thrown, unbinding") Await.result(binding.unbind(), 10.seconds) Await.result(sys.terminate(), 10.seconds) } private def serverHttpContext() = { val keyEncoded = new String(Files.readAllBytes(Paths.get(TestUtils.loadCert("server1.key").getAbsolutePath)), "UTF-8") .replace("-----BEGIN PRIVATE KEY-----\n", "") .replace("-----END PRIVATE KEY-----\n", "") .replace("\n", "") val decodedKey = ByteString(keyEncoded).decodeBase64.toArray val spec = new PKCS8EncodedKeySpec(decodedKey) val kf = KeyFactory.getInstance("RSA") val privateKey = kf.generatePrivate(spec) val fact = CertificateFactory.getInstance("X.509") val is = new FileInputStream(TestUtils.loadCert("server1.pem")) val cer = fact.generateCertificate(is) val ks = KeyStore.getInstance("PKCS12") ks.load(null) ks.setKeyEntry("private", privateKey, Array.empty, Array(cer)) val keyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(ks, null) val context = SSLContext.getInstance("TLS") context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom) new HttpsConnectionContext(context) } override def getPort(binding: (ActorSystem, ServerBinding)): Int = binding._2.localAddress.getPort }
Example 10
Source File: SslContexts.scala From kubernetes-client with Apache License 2.0 | 5 votes |
package com.goyeau.kubernetes.client.util import java.io.{ByteArrayInputStream, File, FileInputStream, InputStreamReader} import java.security.cert.{CertificateFactory, X509Certificate} import java.security.{KeyStore, SecureRandom, Security} import java.util.Base64 import com.goyeau.kubernetes.client.KubeConfig import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory} import org.bouncycastle.jce.provider.BouncyCastleProvider import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter import org.bouncycastle.openssl.{PEMKeyPair, PEMParser} object SslContexts { private val TrustStoreSystemProperty = "javax.net.ssl.trustStore" private val TrustStorePasswordSystemProperty = "javax.net.ssl.trustStorePassword" private val KeyStoreSystemProperty = "javax.net.ssl.keyStore" private val KeyStorePasswordSystemProperty = "javax.net.ssl.keyStorePassword" def fromConfig(config: KubeConfig): SSLContext = { val sslContext = SSLContext.getInstance("TLS") sslContext.init(keyManagers(config), trustManagers(config), new SecureRandom) sslContext } private def keyManagers(config: KubeConfig) = { // Client certificate val certDataStream = config.clientCertData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data))) val certFileStream = config.clientCertFile.map(new FileInputStream(_)) // Client key val keyDataStream = config.clientKeyData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data))) val keyFileStream = config.clientKeyFile.map(new FileInputStream(_)) for { keyStream <- keyDataStream.orElse(keyFileStream) certStream <- certDataStream.orElse(certFileStream) } yield { Security.addProvider(new BouncyCastleProvider()) val pemKeyPair = new PEMParser(new InputStreamReader(keyStream)).readObject().asInstanceOf[PEMKeyPair] // scalafix:ok val privateKey = new JcaPEMKeyConverter().setProvider("BC").getPrivateKey(pemKeyPair.getPrivateKeyInfo) val certificateFactory = CertificateFactory.getInstance("X509") val certificate = certificateFactory.generateCertificate(certStream).asInstanceOf[X509Certificate] // scalafix:ok defaultKeyStore.setKeyEntry( certificate.getSubjectX500Principal.getName, privateKey, config.clientKeyPass.fold(Array.empty[Char])(_.toCharArray), Array(certificate) ) } val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm) keyManagerFactory.init(defaultKeyStore, Array.empty) keyManagerFactory.getKeyManagers } private lazy val defaultKeyStore = { val propertyKeyStoreFile = Option(System.getProperty(KeyStoreSystemProperty, "")).filter(_.nonEmpty).map(new File(_)) val keyStore = KeyStore.getInstance(KeyStore.getDefaultType) keyStore.load( propertyKeyStoreFile.map(new FileInputStream(_)).orNull, System.getProperty(KeyStorePasswordSystemProperty, "").toCharArray ) keyStore } private def trustManagers(config: KubeConfig) = { val certDataStream = config.caCertData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data))) val certFileStream = config.caCertFile.map(new FileInputStream(_)) certDataStream.orElse(certFileStream).foreach { certStream => val certificateFactory = CertificateFactory.getInstance("X509") val certificate = certificateFactory.generateCertificate(certStream).asInstanceOf[X509Certificate] // scalafix:ok defaultTrustStore.setCertificateEntry(certificate.getSubjectX500Principal.getName, certificate) } val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm) trustManagerFactory.init(defaultTrustStore) trustManagerFactory.getTrustManagers } private lazy val defaultTrustStore = { val securityDirectory = s"${System.getProperty("java.home")}/lib/security" val propertyTrustStoreFile = Option(System.getProperty(TrustStoreSystemProperty, "")).filter(_.nonEmpty).map(new File(_)) val jssecacertsFile = Option(new File(s"$securityDirectory/jssecacerts")).filter(f => f.exists && f.isFile) val cacertsFile = new File(s"$securityDirectory/cacerts") val keyStore = KeyStore.getInstance(KeyStore.getDefaultType) keyStore.load( new FileInputStream(propertyTrustStoreFile.orElse(jssecacertsFile).getOrElse(cacertsFile)), System.getProperty(TrustStorePasswordSystemProperty, "changeit").toCharArray ) keyStore } }
Example 11
Source File: ClientFlowHttpsSpec.scala From squbs with Apache License 2.0 | 5 votes |
package org.squbs.httpclient import java.io.InputStream import java.security.{KeyStore, SecureRandom} import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory} import akka.actor.ActorSystem import akka.http.scaladsl.model._ import akka.http.scaladsl.{ConnectionContext, Http} import akka.stream.ActorMaterializer import akka.stream.scaladsl.{Sink, Source} import akka.util.ByteString import com.typesafe.config.ConfigFactory import org.scalatest.{AsyncFlatSpec, BeforeAndAfterAll, Matchers} import org.squbs.resolver.ResolverRegistry import org.squbs.testkit.Timeouts._ import scala.concurrent.{Await, Future} import scala.util.{Success, Try} object ClientFlowHttpsSpec { val config = ConfigFactory.parseString( """ |helloHttps { | type = squbs.httpclient | akka.ssl-config.loose.disableHostnameVerification = true |} """.stripMargin) implicit val system = ActorSystem("ClientFlowHttpsSpec", config) implicit val materializer = ActorMaterializer() ResolverRegistry(system).register[HttpEndpoint]("LocalhostHttpsEndpointResolver") { (name, _) => name match { case "helloHttps" => Some(HttpEndpoint(s"https://localhost:$port", Some(sslContext("exampletrust.jks", "changeit")), None)) case _ => None } } import akka.http.scaladsl.server.Directives._ import system.dispatcher val route = path("hello") { get { complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "Hello World!")) } } val serverBinding = Await.result(Http().bindAndHandle(route, "localhost", 0, ConnectionContext.https(sslContext("example.com.jks", "changeit"))), awaitMax) val port = serverBinding.localAddress.getPort } class ClientFlowHttpsSpec extends AsyncFlatSpec with Matchers with BeforeAndAfterAll { import ClientFlowHttpsSpec._ override def afterAll: Unit = { serverBinding.unbind() map {_ => system.terminate()} } it should "make a call to Hello Service" in { val clientFlow = ClientFlow[Int]("helloHttps") val responseFuture: Future[(Try[HttpResponse], Int)] = Source.single(HttpRequest(uri = "/hello") -> 42) .via(clientFlow) .runWith(Sink.head) val (Success(response), _) = Await.result(responseFuture, awaitMax) response.status should be (StatusCodes.OK) val entity = response.entity.dataBytes.runFold(ByteString(""))(_ ++ _) map(_.utf8String) entity map { e => e shouldEqual "Hello World!" } } }
Example 12
Source File: MqttSSLSocketFactory.scala From stream-reactor with Apache License 2.0 | 5 votes |
package com.datamountaineer.streamreactor.connect.mqtt.source import java.io.FileReader import java.security.{KeyStore, Security} import com.typesafe.scalalogging.StrictLogging import javax.net.ssl.{KeyManagerFactory, SSLContext, SSLSocketFactory, TrustManagerFactory} import org.bouncycastle.cert.X509CertificateHolder import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter import org.bouncycastle.jce.provider.BouncyCastleProvider import org.bouncycastle.openssl.jcajce.{JcaPEMKeyConverter, JcePEMDecryptorProviderBuilder} import org.bouncycastle.openssl.{PEMEncryptedKeyPair, PEMKeyPair, PEMParser} object MqttSSLSocketFactory extends StrictLogging { def apply(caCrtFile: String, crtFile: String, keyFile: String, password: String): SSLSocketFactory = { try { context.getSocketFactory } catch { case e: Exception => logger.warn(e.getMessage, e) null } } }
Example 13
Source File: SslContextModule.scala From scala-server-toolkit with MIT License | 5 votes |
package com.avast.sst.ssl import cats.effect.Sync import cats.syntax.functor._ import com.typesafe.config.{Config, ConfigFactory} import com.typesafe.sslconfig.ssl.{ ConfigSSLContextBuilder, DefaultKeyManagerFactoryWrapper, DefaultTrustManagerFactoryWrapper, SSLConfigFactory } import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory} object SslContextModule { private val SslContextEnabledKey = "enabled" def makeIfEnabled[F[_]: Sync](config: Config, withReference: Boolean = true): F[Option[SSLContext]] = { if (config.hasPath(SslContextEnabledKey) && config.getBoolean(SslContextEnabledKey)) { make(config, withReference).map(Some(_)) } else { Sync[F].delay(None) } } private def referenceConfigUnsafe(): Config = ConfigFactory.defaultReference().getConfig("ssl-config") }