java.security.Security Scala Examples
The following examples show how to use java.security.Security.
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
Source File: BouncyHash.scala From iotchain with MIT License | 5 votes |
package jbok.crypto.hash import java.security.{MessageDigest, Security} import org.bouncycastle.jcajce.provider.digest.Keccak import org.bouncycastle.jce.provider.BouncyCastleProvider import scodec.bits.ByteVector object BouncyHash { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()) } def genInstance(algorithm: String): MessageDigest = MessageDigest.getInstance(algorithm, "BC") val sha256 = genInstance("SHA-256") val ripemd160 = genInstance("RipeMD160") def kec256(bytes: ByteVector) = new Keccak.Digest256().digest(bytes.toArray) def kec512(bytes: ByteVector) = new Keccak.Digest512().digest(bytes.toArray) }
Example 2
Source File: InetAddressDnsResolver.scala From perf_tester with Apache License 2.0 | 5 votes |
package akka.io import java.net.{ InetAddress, UnknownHostException } import java.security.Security import java.util.concurrent.TimeUnit import akka.actor.Actor import com.typesafe.config.Config import scala.collection.immutable import akka.util.Helpers.Requiring import scala.util.Try class InetAddressDnsResolver(cache: SimpleDnsCache, config: Config) extends Actor { // Controls the cache policy for successful lookups only private final val CachePolicyProp = "networkaddress.cache.ttl" // Deprecated JVM property key, keeping for legacy compatibility; replaced by CachePolicyProp private final val CachePolicyPropFallback = "sun.net.inetaddr.ttl" // Controls the cache policy for negative lookups only private final val NegativeCachePolicyProp = "networkaddress.cache.negative.ttl" // Deprecated JVM property key, keeping for legacy compatibility; replaced by NegativeCachePolicyProp private final val NegativeCachePolicyPropFallback = "sun.net.inetaddr.negative.ttl" // default values (-1 and 0 are magic numbers, trust them) private final val Forever = -1 private final val Never = 0 private final val DefaultPositive = 30 private lazy val cachePolicy: Int = { val n = Try(Security.getProperty(CachePolicyProp).toInt) .orElse(Try(Security.getProperty(CachePolicyPropFallback).toInt)) .getOrElse(DefaultPositive) // default if (n < 0) Forever else n } private lazy val negativeCachePolicy = { val n = Try(Security.getProperty(NegativeCachePolicyProp).toInt) .orElse(Try(Security.getProperty(NegativeCachePolicyPropFallback).toInt)) .getOrElse(0) // default if (n < 0) Forever else n } private def getTtl(path: String, positive: Boolean): Long = config.getString(path) match { case "default" ⇒ (if (positive) cachePolicy else negativeCachePolicy) match { case Never ⇒ Never case n if n > 0 ⇒ TimeUnit.SECONDS.toMillis(n) case _ ⇒ Long.MaxValue // forever if negative } case "forever" ⇒ Long.MaxValue case "never" ⇒ Never case _ ⇒ config.getDuration(path, TimeUnit.MILLISECONDS) .requiring(_ > 0, s"akka.io.dns.$path must be 'default', 'forever', 'never' or positive duration") } val positiveTtl: Long = getTtl("positive-ttl", positive = true) val negativeTtl: Long = getTtl("negative-ttl", positive = false) override def receive = { case Dns.Resolve(name) ⇒ val answer = cache.cached(name) match { case Some(a) ⇒ a case None ⇒ try { val answer = Dns.Resolved(name, InetAddress.getAllByName(name)) if (positiveTtl != Never) cache.put(answer, positiveTtl) answer } catch { case e: UnknownHostException ⇒ val answer = Dns.Resolved(name, immutable.Seq.empty, immutable.Seq.empty) if (negativeTtl != Never) cache.put(answer, negativeTtl) answer } } sender() ! answer } }
Example 3
Source File: PlainSaslHelper.scala From kyuubi with Apache License 2.0 | 5 votes |
package yaooqinn.kyuubi.auth import java.io.IOException import java.security.Security import javax.security.auth.callback._ import javax.security.auth.login.LoginException import javax.security.sasl.{AuthenticationException, AuthorizeCallback} import scala.collection.JavaConverters._ import org.apache.hive.service.cli.thrift.TCLIService.Iface import org.apache.spark.SparkConf import org.apache.thrift.{TProcessor, TProcessorFactory} import org.apache.thrift.transport.{TSaslServerTransport, TTransport, TTransportFactory} import yaooqinn.kyuubi.auth.AuthMethods.AuthMethods import yaooqinn.kyuubi.auth.PlainSaslServer.SaslPlainProvider object PlainSaslHelper { // Register Plain SASL server provider Security.addProvider(new SaslPlainProvider()) def getProcessFactory(service: Iface): TProcessorFactory = { SQLPlainProcessorFactory(service) } @throws[LoginException] def getTransportFactory(authTypeStr: String, conf: SparkConf): TTransportFactory = { val saslFactory = new TSaslServerTransport.Factory() try { val handler = new PlainServerCallbackHandler(authTypeStr, conf) val props = Map.empty[String, String] saslFactory.addServerDefinition("PLAIN", authTypeStr, null, props.asJava, handler) } catch { case e: AuthenticationException => throw new LoginException("Error setting callback handler" + e); } saslFactory } private class PlainServerCallbackHandler private(authMethod: AuthMethods, conf: SparkConf) extends CallbackHandler { @throws[AuthenticationException] def this(authMethodStr: String, conf: SparkConf) = this(AuthMethods.getValidAuthMethod(authMethodStr), conf) @throws[IOException] @throws[UnsupportedCallbackException] override def handle(callbacks: Array[Callback]): Unit = { var username: String = null var password: String = null var ac: AuthorizeCallback = null for (callback <- callbacks) { callback match { case nc: NameCallback => username = nc.getName case pc: PasswordCallback => password = new String(pc.getPassword) case a: AuthorizeCallback => ac = a case _ => throw new UnsupportedCallbackException(callback) } } val provider = AuthenticationProviderFactory.getAuthenticationProvider(authMethod, conf) provider.authenticate(username, password) if (ac != null) ac.setAuthorized(true) } } private case class SQLPlainProcessorFactory(service: Iface) extends TProcessorFactory(null) { override def getProcessor(trans: TTransport): TProcessor = new TSetIpAddressProcessor[Iface](service) } }
Example 4
Source File: PlainSaslHelperSuite.scala From kyuubi with Apache License 2.0 | 5 votes |
package yaooqinn.kyuubi.auth import java.security.Security import javax.security.auth.login.LoginException import org.apache.spark.{KyuubiSparkUtil, SparkConf, SparkFunSuite} import org.apache.thrift.transport.{TSaslServerTransport, TSocket} import yaooqinn.kyuubi.auth.PlainSaslServer.SaslPlainProvider import yaooqinn.kyuubi.server.KyuubiServer class PlainSaslHelperSuite extends SparkFunSuite { test("Plain Sasl Helper") { val conf = new SparkConf(loadDefaults = true) KyuubiSparkUtil.setupCommonConfig(conf) val server = new KyuubiServer() val fe = server.feService val tProcessorFactory = PlainSaslHelper.getProcessFactory(fe) assert(!tProcessorFactory.isAsyncProcessor) val tSocket = new TSocket("0.0.0.0", 0) val tProcessor = tProcessorFactory.getProcessor(tSocket) assert(tProcessor.isInstanceOf[TSetIpAddressProcessor[_]]) intercept[LoginException](PlainSaslHelper.getTransportFactory("KERBEROS", conf)) intercept[LoginException](PlainSaslHelper.getTransportFactory("NOSASL", conf)) intercept[LoginException](PlainSaslHelper.getTransportFactory("ELSE", conf)) val tTransportFactory = PlainSaslHelper.getTransportFactory("NONE", conf) assert(tTransportFactory.isInstanceOf[TSaslServerTransport.Factory]) Security.getProviders.exists(_.isInstanceOf[SaslPlainProvider]) } test("Sasl Plain Provider") { val saslPlainProvider = new SaslPlainProvider() assert(saslPlainProvider.containsKey("SaslServerFactory.PLAIN")) assert(saslPlainProvider.getName === "KyuubiSaslPlain") } }
Example 5
Source File: Crypto.scala From OUTDATED_ledger-wallet-android with MIT License | 5 votes |
package co.ledger.wallet.core.crypto import java.security.Security object Crypto { val SpongyCastleProviderName = org.spongycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME def ensureSpongyIsInserted(): Unit = { val ProviderName = org.spongycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME if (Security.getProvider(ProviderName) == null) { Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider, 1) } } def ensureSpongyIsRemoved(): Unit = { val ProviderName = org.spongycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME if (Security.getProvider(ProviderName) != null) { Security.removeProvider(ProviderName) } } def splitAndXor(bytes: Array[Byte]) = { val resultLength = bytes.length / 2 val result = new Array[Byte](resultLength) for (i <- 0 until resultLength) result(i) = (bytes(i) ^ bytes(i + resultLength)).asInstanceOf[Byte] result } }
Example 6
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 7
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 } } }