java.security.SecureRandom Scala Examples

The following examples show how to use java.security.SecureRandom. 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: package.scala    From mantis   with Apache License 2.0 6 votes vote down vote up
package io.iohk.ethereum

import java.io.{File, PrintWriter}
import java.net.{Inet6Address, InetAddress}
import java.security.SecureRandom

import io.iohk.ethereum.crypto._
import org.spongycastle.crypto.AsymmetricCipherKeyPair
import org.spongycastle.crypto.params.ECPublicKeyParameters
import org.spongycastle.math.ec.ECPoint
import org.spongycastle.util.encoders.Hex

import scala.io.Source

package object network {

  val ProtocolVersion = 4

  implicit class ECPublicKeyParametersNodeId(val pubKey: ECPublicKeyParameters) extends AnyVal {
    def toNodeId: Array[Byte] =
      pubKey.asInstanceOf[ECPublicKeyParameters].getQ
      .getEncoded(false)
      .drop(1) // drop type info
  }

  def publicKeyFromNodeId(nodeId: String): ECPoint = {
    val bytes = ECDSASignature.uncompressedIndicator +: Hex.decode(nodeId)
    curve.getCurve.decodePoint(bytes)
  }

  def loadAsymmetricCipherKeyPair(filePath: String, secureRandom: SecureRandom): AsymmetricCipherKeyPair = {
    val file = new File(filePath)
    if(!file.exists()){
      val keysValuePair = generateKeyPair(secureRandom)

      //Write keys to file
      val (priv, _) = keyPairToByteArrays(keysValuePair)
      require(file.getParentFile.exists() || file.getParentFile.mkdirs(), "Key's file parent directory creation failed")
      val writer = new PrintWriter(filePath)
      try {
        writer.write(Hex.toHexString(priv))
      } finally {
        writer.close()
      }

      keysValuePair
    } else {
      val reader = Source.fromFile(filePath)
      try {
        val privHex = reader.mkString
        keyPairFromPrvKey(Hex.decode(privHex))
      } finally {
        reader.close()
      }
    }
  }

  
  def getHostName(address: InetAddress): String = {
    val hostName = address.getHostAddress
    address match {
      case _: Inet6Address => s"[$hostName]"
      case _ => hostName
    }
  }

} 
Example 2
Source File: SSL.scala    From lolhttp   with Apache License 2.0 6 votes vote down vote up
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 3
Source File: HttpClientProvider.scala    From reactive-nakadi   with MIT License 5 votes vote down vote up
package org.zalando.react.nakadi.client.providers

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, TrustManager, X509TrustManager}

import akka.actor.ActorContext
import akka.http.scaladsl.Http.OutgoingConnection
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.settings.ClientConnectionSettings
import akka.http.scaladsl.{Http, HttpsConnectionContext}
import akka.stream.scaladsl.Flow

import scala.concurrent.Future
import scala.concurrent.duration._


class HttpClientProvider(actorContext: ActorContext,
                         server: String, port: Int,
                         isConnectionSSL: Boolean = false,
                         acceptAnyCertificate: Boolean = false,
                         connectionTimeout: FiniteDuration) {

  val http = Http(actorContext.system)

  private val settings = {
    ClientConnectionSettings
      .apply(actorContext.system)
      .withConnectingTimeout(connectionTimeout)
      .withIdleTimeout(Duration.Inf)
  }

  val connection: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = {

    isConnectionSSL match {
      case true =>
        val sslContext = if (!acceptAnyCertificate) SSLContext.getDefault else {

          val permissiveTrustManager: TrustManager = new X509TrustManager() {
            override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def getAcceptedIssuers(): Array[X509Certificate] = Array.empty
          }

          val ctx = SSLContext.getInstance("TLS")
          ctx.init(Array.empty, Array(permissiveTrustManager), new SecureRandom())
          ctx
        }
        http.outgoingConnectionHttps(server, port, new HttpsConnectionContext(sslContext), settings = settings)
      case false =>
        http.outgoingConnection(server, port, settings = settings)
    }
  }

} 
Example 4
Source File: Sessions.scala    From peregrine   with Apache License 2.0 5 votes vote down vote up
package io.peregrine

import com.twitter.finagle.http.Cookie
import com.twitter.util.Future

import scala.collection.mutable

trait Sessions extends BaseSessions {

  // needs to be overridden in order to create a different session type
  protected def createSession[S >: Session](sessionId: String) = new CookieBasedSession(sessionId)

  // needs to be overridden in order to create a different session type
  protected def getOrCreateSession(sessionId: String): Session = {
    CookieSessionsHolder.getOrElseUpdate(sessionId, createSession(sessionId))
  }
}

trait BaseSessions {

  protected def createSessionCookie: Cookie = {
    buildSessionCookie(IdGenerator.hexString(64))
  }

  protected def cookieBuilder: CookieBuilder = {
    new CookieBuilder
  }

  protected def buildSessionCookie(value: String): Cookie = {
    cookieBuilder.name("_session_id")
      .value(value)
      .httpOnly(httpOnly = true)
      // enables cookies for secure session if cert and key are provided
      .secure(!config.certificatePath().isEmpty && !config.keyPath().isEmpty)
      .build()
  }

  // needs to be overridden in order to create a different session type
  def session(implicit req: Request): Future[Session] = Future {
    req.cookies.get("_session_id") match {
      case Some(cookie) =>
        req.response.addCookie(buildSessionCookie(cookie.value))
        getOrCreateSession(cookie.value)
      case None         =>
        val cookie = createSessionCookie
        req.response.addCookie(cookie)
        getOrCreateSession(cookie.value)
    }
  }

  // needs to be overridden in order to create a different session type
  protected def createSession[S >: Session](sessionId: String): S

  // needs to be overridden in order to create a different session type
  protected def getOrCreateSession(sessionId: String): Session
}

trait Session {
  type Seconds = Long

  def get[T](key: String): Future[Option[T]]
  def put[T](key: String, value: T, expiresIn: Seconds = 3600000): Future[Unit]
  def del(key: String): Future[Unit]
  def getOrElseUpdate[T](key: String, value: T): Future[T]
}

class CookieBasedSession(val sessionId: String) extends Session {

  private val values = mutable.Map[String, Any]()

  override def get[T](key: String): Future[Option[T]] = Future(values.get(key).map(_.asInstanceOf[T]))
  override def put[T](key: String, value: T, expiresIn: Seconds = 3600000): Future[Unit] = Future(values.put(key, value))
  override def del(key: String): Future[Unit] = Future(values.remove(key))
  override def getOrElseUpdate[T](key: String, value: T):Future[T] = get[T](key).flatMap {
    case Some(t) => Future(t)
    case None    => put[T](key, value).map(_ => value)
  }
}

private[this] object CookieSessionsHolder {

  private val sessions = mutable.Map[String, CookieBasedSession]()

  def get(id: String): Option[Session] = sessions.get(id)
  def put(id: String, session: CookieBasedSession): Unit = sessions.put(id, session)
  def del(id: String): Unit = sessions.remove(id)
  def getOrElseUpdate(id: String, session: CookieBasedSession) = sessions.getOrElseUpdate(id, session)
}

private[peregrine] object IdGenerator {

  import java.security.SecureRandom

  private val secureRandom = new SecureRandom()

  def hexString(bytes: Int): String = {
    val data = new Array[Byte](bytes)
    secureRandom.nextBytes(data)
    data.map("%02x" format _).mkString
  }
} 
Example 5
Source File: ExecuteContext.scala    From hail   with MIT License 5 votes vote down vote up
package is.hail.expr.ir

import java.io._
import java.security.SecureRandom

import is.hail.HailContext
import is.hail.utils._
import is.hail.annotations.Region
import is.hail.backend.{Backend, BackendContext, BroadcastValue}
import is.hail.io.fs.FS

import scala.collection.mutable

object ExecuteContext {
  def scoped[T]()(f: ExecuteContext => T): T = HailContext.sparkBackend("ExecuteContext.scoped").withExecuteContext()(f)

  def scoped[T](tmpdir: String, localTmpdir: String, backend: Backend, fs: FS)(f: ExecuteContext => T): T = {
    Region.scoped { r =>
      val ctx = new ExecuteContext(tmpdir, localTmpdir, backend, fs, r, new ExecutionTimer)
      f(ctx)
    }
  }

  def scopedNewRegion[T](ctx: ExecuteContext)(f: ExecuteContext => T): T = {
    Region.scoped { r =>
      val oldR = ctx.r
      ctx.r = r
      val t = f(ctx)
      ctx.r = oldR
      t
    }
  }

  def createTmpPathNoCleanup(tmpdir: String, prefix: String, extension: String = null): String = {
    val random = new SecureRandom()
    val alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    val token = (0 until 22).map(_ => alphabet(random.nextInt(alphabet.length))).mkString
    if (extension != null)
      s"$tmpdir/$prefix-$token.$extension"
    else
      s"$tmpdir/$prefix-$token"
  }
}

class ExecuteContext(
  val tmpdir: String,
  val localTmpdir: String,
  val backend: Backend,
  val fs: FS,
  var r: Region,
  val timer: ExecutionTimer
) extends Closeable {
  var backendContext: BackendContext = _

  def fsBc: BroadcastValue[FS] = fs.broadcast

  private val tmpPaths = mutable.ArrayBuffer[String]()

  def createTmpPath(prefix: String, extension: String = null): String = {
    val path = ExecuteContext.createTmpPathNoCleanup(tmpdir, prefix, extension)
    tmpPaths += path
    path
  }

  def close(): Unit = {
    for (p <- tmpPaths)
      fs.delete(p, recursive = true)
    tmpPaths.clear()
  }
} 
Example 6
Source File: Application.scala    From auth0-scala-samples   with MIT License 5 votes vote down vote up
package controllers

import javax.inject.Inject
import play.api.cache._
import play.api.mvc.{Action, AnyContent, Controller}
import helpers.Auth0Config
import java.security.SecureRandom
import java.math.BigInteger
import java.util.UUID.randomUUID

import play.api.Configuration


class Application @Inject() (cache: CacheApi, configuration: Configuration) extends Controller {

  private val config = Auth0Config.get(configuration)

  def index: Action[AnyContent] = Action {
    Ok(views.html.index())
  }

  def login: Action[AnyContent] = Action {
    // Generate random state parameter
    object RandomUtil {
      private val random = new SecureRandom()

      def alphanumeric(nrChars: Int = 24): String = {
        new BigInteger(nrChars * 5, random).toString(32)
      }
    }
    val state = RandomUtil.alphanumeric()

    var audience = config.audience
    if (config.audience == ""){
      audience = String.format("https://%s/userinfo", config.domain)
    }

    val id = randomUUID().toString
    cache.set(id + "state", state)
    val query = String.format(
      "authorize?client_id=%s&redirect_uri=%s&response_type=code&scope=openid profile&audience=%s&state=%s",
      config.clientId,
      config.callbackURL,
      audience,
      state
    )
    Redirect(String.format("https://%s/%s", config.domain, query)).withSession("id" -> id)
  }

  def logout: Action[AnyContent] = Action { request =>
    val host = request.host
    var scheme = "http"
    if (request.secure) {
      scheme = "https"
    }
    val returnTo = scheme + "://" + host
    Redirect(String.format(
      "https://%s/v2/logout?client_id=%s&returnTo=%s",
      config.domain,
      config.clientId,
      returnTo)
    ).withNewSession
  }
} 
Example 7
Source File: Utils.scala    From nacl4s   with MIT License 5 votes vote down vote up
package com.emstlk.nacl4s.crypto

import java.security.SecureRandom

object Utils {

  private val sigma = "expand 32-byte k".map(_.toByte).toArray

  def getSigma = sigma.clone()

  lazy val random = new SecureRandom

  @inline def checkLength(a: Array[Byte], length: Int) = {
    require(Option(a).exists(_.length == length), s"Wrong length, required $length")
  }

  @inline def loadInt(a: Array[Byte], offset: Int): Int = {
    a(offset) & 0xff |
      (a(offset + 1) & 0xff) << 8 |
      (a(offset + 2) & 0xff) << 16 |
      (a(offset + 3) & 0xff) << 24
  }

  @inline def storeInt(a: Array[Byte], offset: Int, value: Int) = {
    a(offset) = value.toByte
    a(offset + 1) = (value >>> 8).toByte
    a(offset + 2) = (value >>> 16).toByte
    a(offset + 3) = (value >>> 24).toByte
  }

} 
Example 8
Source File: ApplicationKeystore.scala    From OUTDATED_ledger-wallet-android   with MIT License 5 votes vote down vote up
package co.ledger.wallet.core.security

import java.io.File
import java.math.BigInteger
import java.security.KeyStore.{PasswordProtection, PrivateKeyEntry}
import java.security.{KeyStore, SecureRandom}
import java.util.Calendar
import javax.security.auth.x500.X500Principal

import android.content.Context
import co.ledger.wallet.core.crypto.Crypto
import org.spongycastle.x509.X509V3CertificateGenerator

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class ApplicationKeystore(context: Context, val keystoreName: String) extends Keystore(context) {

  def install(passwordProtection: PasswordProtection): Future[Keystore] = {
    assert(!file.exists(), "The keystore already exists")
    val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)
    keyStore.load(null)
    val output = context.openFileOutput(keystoreName, Context.MODE_PRIVATE)
    keyStore.store(output, passwordProtection.getPassword)
    output.close()
    load(passwordProtection)
  }

  def setPassword(password: String): Unit = {
    require(password != null, "Password cannot be null")
    _password = password.toCharArray
    store()
  }

  override protected def loadJavaKeyStore(passwordProtection: PasswordProtection): Future[JavaKeyStore] = {
    Future {
      assert(file.exists(), "The keystore is not installed yet")
      val keystore = KeyStore.getInstance(KeyStore.getDefaultType)
      val input = context.openFileInput(keystoreName)
      keystore.load(input, passwordProtection.getPassword)
      input.close()
      _password = passwordProtection.getPassword
      keystore
    }
  }

  override def generateKey(alias: String): JavaKeyPair = {
    Crypto.ensureSpongyIsInserted()
    val kpg = java.security.KeyPairGenerator.getInstance("RSA")
    val calendar = Calendar.getInstance()
    val now = calendar.getTime
    calendar.add(Calendar.YEAR, 100)
    val end = calendar.getTime
    kpg.initialize(1024, new SecureRandom())
    val keypair = kpg.generateKeyPair()
    val certGen = new X509V3CertificateGenerator()
    val dnName = new X500Principal("CN=Ledger")
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()))
    certGen.setSubjectDN(dnName)
    certGen.setIssuerDN(dnName)
    certGen.setNotBefore(now)
    certGen.setNotAfter(end)
    certGen.setPublicKey(keypair.getPublic)
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption")
    val certificate = certGen.generate(keypair.getPrivate, "SC")
    javaKeystore.get.setEntry(alias, new PrivateKeyEntry(keypair.getPrivate, Array(certificate)), null)
    store()
    Crypto.ensureSpongyIsRemoved()
    keypair
  }

  def delete(): Unit = {
    file.delete()
  }

  def isInstalled = file.exists()

  private[this] def store(): Unit = {
    file.delete()
    val output = context.openFileOutput(keystoreName, Context.MODE_PRIVATE)
    javaKeystore.get.store(output, _password)
    output.close()
  }

  @inline private[this] def file = new File(context.getFilesDir, keystoreName)
  private var _password: Array[Char] = null
} 
Example 9
Source File: ECKeyPair.scala    From OUTDATED_ledger-wallet-android   with MIT License 5 votes vote down vote up
package co.ledger.wallet.core.crypto

import java.math.BigInteger
import java.security.SecureRandom

import org.spongycastle.asn1.sec.SECNamedCurves
import org.spongycastle.crypto.AsymmetricCipherKeyPair
import org.spongycastle.crypto.generators.ECKeyPairGenerator
import org.spongycastle.crypto.params.{ECPrivateKeyParameters, ECPublicKeyParameters, ECDomainParameters, ECKeyGenerationParameters}
import org.spongycastle.math.ec.ECPoint
import org.spongycastle.util.encoders.Hex

import scala.util.Try

abstract class ECKeyPair {

  Try(PRNGFixes.apply())

  def publicKeyPoint: ECPoint
  def privateKeyInteger: BigInteger

  def privateKey = privateKeyInteger.toByteArray
  def publicKey = publicKeyPoint.getEncoded
  def compressedPublicKey = new ECPoint.Fp(ECKeyPair.Domain.getCurve, publicKeyPoint.getXCoord, publicKeyPoint.getYCoord, true).getEncoded

  def privateKeyHexString = Hex.toHexString(privateKey)
  def publicKeyHexString = Hex.toHexString(publicKey)
  def compressedPublicKeyHexString = Hex.toHexString(compressedPublicKey)

  def generateAgreementSecret(publicKeyHex: String): Array[Byte] = generateAgreementSecret(Hex.decode(publicKeyHex))

  def generateAgreementSecret(publicKey: Array[Byte]): Array[Byte] = {
    Crypto.ensureSpongyIsInserted()
    val publicKeyPoint = ECKeyPair.bytesToEcPoint(publicKey)
    val P = publicKeyPoint.multiply(ECKeyPair.Domain.getH.multiply(privateKeyInteger))
    P.normalize().getXCoord.getEncoded
  }
}

object ECKeyPair {
 Crypto.ensureSpongyIsInserted()
  val Curve = SECNamedCurves.getByName("secp256k1")
  val Domain = new ECDomainParameters(Curve.getCurve, Curve.getG, Curve.getN, Curve.getH)
  val SecureRandom = new SecureRandom
  private[this] val generator = new ECKeyPairGenerator
  private[this] val keygenParams = new ECKeyGenerationParameters(ECKeyPair.Domain, ECKeyPair.SecureRandom)
  generator.init(keygenParams)

  def generate(): ECKeyPair = new ECKeyPairFromAsymmetricCipherKeyPair(generator.generateKeyPair())
  def create(privateKey: Array[Byte]): ECKeyPair = new ECKeyPairFromPrivateKey(privateKey)
  def bytesToEcPoint(bytes: Array[Byte]): ECPoint = Curve.getCurve.decodePoint(bytes)

  private sealed class ECKeyPairFromAsymmetricCipherKeyPair(keyPair: AsymmetricCipherKeyPair) extends ECKeyPair {
    def publicKeyParameters = keyPair.getPublic.asInstanceOf[ECPublicKeyParameters]
    def privateKeyParameters = keyPair.getPrivate.asInstanceOf[ECPrivateKeyParameters]

    def publicKeyPoint = publicKeyParameters.getQ
    def privateKeyInteger = privateKeyParameters.getD
  }

  private sealed class ECKeyPairFromPrivateKey(bytes: Array[Byte]) extends ECKeyPair {

    private[this] val _privateKey = new BigInteger(1, bytes).mod(Curve.getN)
    private[this] val _publicKey = Curve.getG.multiply(_privateKey)

    def publicKeyPoint = _publicKey
    def privateKeyInteger = _privateKey
  }

} 
Example 10
Source File: Main.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
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 11
Source File: AkkaGrpcServerScala.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
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 12
Source File: SslContexts.scala    From kubernetes-client   with Apache License 2.0 5 votes vote down vote up
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 13
Source File: Crypto.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.libs.scala

import java.nio.ByteBuffer
import java.security.{Key, MessageDigest, SecureRandom}
import java.util.Base64

import javax.crypto.spec.IvParameterSpec
import javax.crypto.{Cipher, KeyGenerator}

import scala.util.Try

object Crypto {
  private val charEnc = "UTF-8"
  private val aesKeyLength = 128
  private val aesTransformationString = "AES/CFB/NoPadding"

  def base64Encode(message: String): String =
    base64Encode(message.getBytes)

  def base64Encode(message: Array[Byte]): String =
    new String(Base64.getEncoder.encode(message), charEnc)

  def base64Decode(base64: String): Try[String] =
    base64DecodeBytes(base64).map(new String(_, charEnc))

  def base64DecodeBytes(base64: String): Try[Array[Byte]] =
    Try(Base64.getDecoder.decode(base64.getBytes(charEnc)))

  def md5(message: String): String =
    MessageDigest.getInstance("MD5").digest(message.getBytes).map("%02x".format(_)).mkString

  def sha1(message: String): String =
    MessageDigest.getInstance("SHA1").digest(message.getBytes).map("%02x".format(_)).mkString

  def secureRandom(): Try[Double] = {
    Try(SecureRandom.getInstance("SHA1PRNG")).map { sr =>
      val seedByteCount = 10
      val seed = sr.generateSeed(seedByteCount)
      sr.setSeed(seed)
      sr.nextDouble()
    }
  }

  final case class AesSecretKey(value: String) extends Key {
    override def getAlgorithm: String = "AES"

    override def getFormat: String = "RAW"

    override def getEncoded: Array[Byte] = base64DecodeBytes(value).get

    override def toString: String = "AesSecretKey(*****)"
  }

  final case class AesEncrypted(cipher: String)

  def aesGenerateKey(): Try[AesSecretKey] = for {
    // Generate an AES key of the desired length (in bits) using an AES KeyGenerator.
    keyGen <- Try(KeyGenerator.getInstance("AES"))
    _ <- Try(keyGen.init(aesKeyLength))
    secretKey <- Try(keyGen.generateKey)
  } yield AesSecretKey(base64Encode(secretKey.getEncoded))

  // adapted from https://www.owasp.org/index.php/Using_the_Java_Cryptographic_Extensions
  def aesEncrypt(message: String, secretKey: AesSecretKey): Try[AesEncrypted] = {
    for {
      // Get a Cipher instance of the desired algorithm, mode, and padding.
      aesCipherForEncryption <- Try(Cipher.getInstance(aesTransformationString))
      // Generate an initialization vector for our message of the same size as the Cipher's blocksize.
      iv <- Try(aesCipherForEncryption.getBlockSize).map(new Array[Byte](_))
      prng <- Try(new SecureRandom())
      _ = prng.nextBytes(iv)
      // Initialize the Cipher instance for encryption using the key and initialization vector.
      p <- Try(new IvParameterSpec(iv))
      _ <- Try(aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey, p))
      // Use the Cipher to encrypt the message (after encoding it to a byte[] using the named Charset), and then append the encrypted data to the IV and Base64-encode the result.
      m <- Try(message.getBytes(charEnc))
      encrypted <- Try(aesCipherForEncryption.doFinal(m))
      cipherData = ByteBuffer.allocate(iv.length + encrypted.length)
      _ = cipherData.put(iv)
      _ = cipherData.put(encrypted)
    } yield AesEncrypted(base64Encode(cipherData.array))
  }

  def aesDecrypt(message: AesEncrypted, secretKey: AesSecretKey): Try[String] = {
    for {
      // Get a new Cipher instance of the same algorithm, mode, and padding used for encryption.
      aesCipherForDecryption <- Try(Cipher.getInstance(aesTransformationString))
      // Base64-decode and split the data into the IV and the encrypted data, and then initialize the cipher for decryption with the same key used for encryption (symmetric), the IV, and the encrypted data.
      cipherData <- base64DecodeBytes(message.cipher).map(ByteBuffer.wrap)
      iv = new Array[Byte](aesCipherForDecryption.getBlockSize)
      _ <- Try(cipherData.get(iv))
      encrypted = new Array[Byte](cipherData.remaining)
      _ <- Try(cipherData.get(encrypted))
      _ <- Try(aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)))
      // Use the Cipher to decrypt the data, convert it to a String using the named Charset, and display the message.
      decrypted <- Try(aesCipherForDecryption.doFinal(encrypted))
    } yield new String(decrypted, charEnc)
  }
} 
Example 14
Source File: ClientFlowHttpsSpec.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
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 15
Source File: InfinispanClient.scala    From infinispan-spark   with Apache License 2.0 5 votes vote down vote up
package org.infinispan.spark.test

import java.net.HttpURLConnection
import java.security.SecureRandom
import java.security.cert.X509Certificate

import javax.net.ssl._
import sttp.client.{HttpURLConnectionBackend, basicRequest, _}


case class InfinispanClient(port: Int = 11222, tls: Boolean) {
   val SkipSSLValidation: HttpURLConnection => Unit = {
      case connection: HttpsURLConnection =>
         val sc = SSLContext.getInstance("TLS")
         sc.init(null, Array(new TrustAllX509TrustManager), new SecureRandom)
         connection.setSSLSocketFactory(sc.getSocketFactory)
         connection.setHostnameVerifier(new HostnameVerifier {
            override def verify(s: String, sslSession: SSLSession) = true
         })
      case _ =>
   }

   implicit val backend = HttpURLConnectionBackend(customizeConnection = SkipSSLValidation)

   val protocol = if (tls) "https" else "http"

   val baseURL = s"$protocol://localhost:$port/rest/v2"

   def shutdownServer(): Unit = {
      shutDownResource("server")
   }

   def shutdownCluster(): Unit = {
      shutDownResource("cluster")
   }

   private def shutDownResource(resource: String): Unit = {
      val request = basicRequest.get(uri"$baseURL/$resource?action=stop")
      val response = request.send()
      val code = response.code.code
      if (code < 200 || code > 204) throw new Exception(s"Failed to stop $resource, code $code")
   }

   def cacheExists(name: String): Boolean = {
      val request = basicRequest.get(uri"$baseURL/caches/")
      val response = request.send()
      response.body match {
         case Right(x) => ujson.read(x).arr.map(_.str).contains(name)
         case _ => false
      }
   }

   def isHealthy(cacheManager: String, members: Int): Boolean = {
      val request = basicRequest.get(uri"$baseURL/cache-managers/$cacheManager/health/")
      val response = request.send()
      response.body match {
         case Right(x) =>
            val json = ujson.read(x)
            val clusterHealth = json("cluster_health")
            val health = clusterHealth("health_status")
            val nodes = clusterHealth("number_of_nodes")
            health.str == "HEALTHY" && nodes.num == members
         case Left(x) => throw new RuntimeException(x)
      }
   }

   def createCache(cacheName: String, cfg: String) = {
      if (!cacheExists(cacheName)) {
         val response = basicRequest.post(uri"$baseURL/caches/$cacheName")
           .contentType("application/json")
           .body(cfg).send()
         val status = response.code.code
         if (status < 200 || status > 204) throw new RuntimeException(s"Failed to create cache, code $status")
      }
   }

   class TrustAllX509TrustManager extends X509TrustManager {
      def getAcceptedIssuers = new Array[X509Certificate](0)

      def checkClientTrusted(certs: Array[X509Certificate], authType: String): Unit = {}

      def checkServerTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
   }

} 
Example 16
Source File: TLS.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.api.security

import java.net.Socket
import javax.net.ssl._
import java.security.cert.X509Certificate
import java.security.SecureRandom

import skuber.api.client.{AuthInfo, CertAuth, Context, PathOrData}


object TLS {
  
  // This trust manager supports the InsecureSkipTLSVerify flag in kubeconfig files -
  // it always trusts the server i.e. skips verifying the server cert for a TLS connection
  object InsecureSkipTLSVerifyTrustManager extends X509ExtendedTrustManager
  {
    def getAcceptedIssuers = Array.empty[X509Certificate]
    def checkClientTrusted(certs: Array[X509Certificate], authType: String) : Unit = {}
    def checkServerTrusted(certs: Array[X509Certificate], authType: String) : Unit = {}
    def checkClientTrusted(certs: Array[X509Certificate], s: String, socket: Socket): Unit = {}
    def checkClientTrusted(certs: Array[X509Certificate], s: String, sslEngine: SSLEngine): Unit = {}
    def checkServerTrusted(certs: Array[X509Certificate], s: String, socket: Socket): Unit = {}
    def checkServerTrusted(certs: Array[X509Certificate], s: String, sslEngine: SSLEngine): Unit = {}
  }
   
  val skipTLSTrustManagers = Array[TrustManager](InsecureSkipTLSVerifyTrustManager)
 
  val HttpsPattern = "https:.*".r
  val HttpPattern = "http:.*".r
  
  def establishSSLContext(k8sContext: Context): Option[SSLContext] = {
    k8sContext.cluster.server match {
      case HttpPattern(_*) => None // not using SSL so return no context
      case HttpsPattern(_*) => Some(buildSSLContext(k8sContext))
      case _ => throw new Exception("Kubernetes cluster API server URL does not begin with either http or https : "
                                    + k8sContext.cluster.server)
    }
  }
  
   private def buildSSLContext(k8sContext: Context): SSLContext = {
     val sslContext = SSLContext.getInstance("TLS")
     
     val skipTLSVerify = k8sContext.cluster.insecureSkipTLSVerify
     val clusterCertConfig = k8sContext.cluster.certificateAuthority
     val trustManagers = getTrustManagers(skipTLSVerify,clusterCertConfig) 

     val keyManagers = getKeyManagers(k8sContext.authInfo)
     
     sslContext.init(keyManagers.orNull, trustManagers.orNull, new SecureRandom())
     sslContext
   }
   
   private def getTrustManagers(skipTLSVerify: Boolean, serverCertConfig: Option[PathOrData]) : Option[Array[TrustManager]] =
     if (skipTLSVerify) 
       Some(skipTLSTrustManagers)
     else
       serverCertConfig map { certPathOrData =>
           val clusterServerCerts = SecurityHelper.getCertificates(certPathOrData)
           val trustStore = SecurityHelper.createTrustStore(clusterServerCerts)
           val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
           tmf.init(trustStore)
           tmf.getTrustManagers
       }
  
   private def getKeyManagers(authInfo: AuthInfo) : Option[Array[KeyManager]] =
     authInfo match {
       case CertAuth(clientCert, clientKey, userName) =>
         val certs = SecurityHelper.getCertificates(clientCert)
         val key = SecurityHelper.getPrivateKey(clientKey)
         val keyStore = SecurityHelper.createKeyStore(userName.getOrElse("skuber"), certs, key)
         val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
         kmf.init(keyStore, "changeit".toCharArray)
         Some(kmf.getKeyManagers)
       case _ => None
     }
       
} 
Example 17
Source File: IdGenerator.scala    From korolev   with Apache License 2.0 5 votes vote down vote up
package korolev.state

import java.security.SecureRandom

import korolev.effect.Effect

trait IdGenerator[F[_]] {
  def generateDeviceId()(implicit F: Effect[F]): F[DeviceId]
  def generateSessionId()(implicit F: Effect[F]): F[SessionId]
}

object IdGenerator {

  val DefaultDeviceIdLength = 64
  val DefaultSessionIdLength = 64

  def default[F[_]](deviceIdLength: Int = DefaultDeviceIdLength,
                     sessionIdLength: Int = DefaultSessionIdLength): IdGenerator[F] =
    new DefaultIdGenerator[F](DefaultDeviceIdLength, DefaultSessionIdLength)

  private class DefaultIdGenerator[F[_]](deviceIdLength: Int,
                                          sessionIdLength: Int) extends IdGenerator[F] {
    def generateDeviceId()(implicit F: Effect[F]): F[DeviceId] =
      Effect[F].delay {
        secureRandomString(deviceIdLength)
      }

    def generateSessionId()(implicit F: Effect[F]): F[SessionId] =
      Effect[F].delay {
        secureRandomString(sessionIdLength)
      }

    private val Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    private val rnd = new SecureRandom

    private def secureRandomString(len: Int): String = {
      val sb = new StringBuilder(len)
      var i = 0
      while (i < len) {
        sb.append(Alphabet.charAt(rnd.nextInt(Alphabet.length)))
        i += 1
      }
      sb.toString
    }
  }

} 
Example 18
Source File: package.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform

import java.security.SecureRandom

import com.google.common.base.Charsets
import com.google.protobuf.ByteString
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.common.state.ByteStr._
import com.wavesplatform.common.utils.Base58
import org.apache.commons.lang3.time.DurationFormatUtils
import play.api.libs.json._

import scala.annotation.tailrec

package object utils extends ScorexLogging {

  private val BytesMaxValue  = 256
  private val Base58MaxValue = 58

  private val BytesLog = math.log(BytesMaxValue)
  private val BaseLog  = math.log(Base58MaxValue)

  def base58Length(byteArrayLength: Int): Int = math.ceil(BytesLog / BaseLog * byteArrayLength).toInt

  def forceStopApplication(reason: ApplicationStopReason = Default): Unit =
    System.exit(reason.code)

  def humanReadableSize(bytes: Long, si: Boolean = true): String = {
    val (baseValue, unitStrings) =
      if (si)
        (1000, Vector("B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"))
      else
        (1024, Vector("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"))

    @tailrec
    def getExponent(curBytes: Long, baseValue: Int, curExponent: Int = 0): Int =
      if (curBytes < baseValue) curExponent
      else {
        val newExponent = 1 + curExponent
        getExponent(curBytes / (baseValue * newExponent), baseValue, newExponent)
      }

    val exponent   = getExponent(bytes, baseValue)
    val divisor    = Math.pow(baseValue, exponent)
    val unitString = unitStrings(exponent)

    f"${bytes / divisor}%.1f $unitString"
  }

  def humanReadableDuration(duration: Long): String =
    DurationFormatUtils.formatDurationHMS(duration)

  implicit class Tap[A](a: A) {
    def tap(g: A => Unit): A = {
      g(a)
      a
    }
  }

  def randomBytes(howMany: Int = 32): Array[Byte] = {
    val r = new Array[Byte](howMany)
    new SecureRandom().nextBytes(r) //overrides r
    r
  }

  implicit val byteStrFormat: Format[ByteStr] = new Format[ByteStr] {
    override def writes(o: ByteStr): JsValue = JsString(o.toString)

    override def reads(json: JsValue): JsResult[ByteStr] = json match {
      case JsString(v) if v.startsWith("base64:") =>
        decodeBase64(v.substring(7)).fold(e => JsError(s"Error parsing base64: ${e.getMessage}"), b => JsSuccess(b))
      case JsString(v) if v.length > Base58.defaultDecodeLimit => JsError(s"Length ${v.length} exceeds maximum length of 192")
      case JsString(v)                                         => decodeBase58(v).fold(e => JsError(s"Error parsing base58: ${e.getMessage}"), b => JsSuccess(b))
      case _                                                   => JsError("Expected JsString")
    }
  }

  implicit class StringBytes(val s: String) extends AnyVal {
    def utf8Bytes: Array[Byte]   = s.getBytes(Charsets.UTF_8)
    def toByteString: ByteString = ByteString.copyFromUtf8(s)
  }
} 
Example 19
Source File: UserAuthService.scala    From akka-http-rest-api   with MIT License 5 votes vote down vote up
package authentication

import java.math.BigInteger
import java.security.SecureRandom

import authentication.UserAuthResult.{UserNotExists, UserExists, Success, InvalidData}
import core.authentication.Identity
import org.joda.time.DateTime
import org.mindrot.jbcrypt.BCrypt
import redis.RedisClient
import token.TokenRepository
import user.{UserRepository, User}
import core.authentication.UserSerializer._

import scala.concurrent.{Future, ExecutionContext}

class UserAuthService(tokenRepo: TokenRepository, userAuthRepo: UserAuthRepository, userRepo: UserRepository)
                     (implicit ec: ExecutionContext, redisClient: RedisClient) {

  def register(request: UserRegistrationRequest): Future[UserAuthResult] = {
    if (!RegistrationValidator.isDataValid(request.email, request.password)) {
      Future.successful(InvalidData("E-mail or password is invalid"))
    } else {
      userAuthRepo.findByUserEmail(request.email).flatMap {
        case Some(userAuth) => Future.successful(UserExists("E-mail already in use"))
        case None =>
          val now = DateTime.now().getMillis
          val token = generateToken
          for {
            user <- userRepo.insert(User(None, now, request.firstName, request.lastName, request.gender, None, None, None, request.role))
            _ <- userAuthRepo.insert(UserAuth(None, request.email, hashPassword(request.password), user.id.get))
            _ <- tokenRepo.insert(token, user.id.get)
            _ <- redisClient.setnx(token, Identity.User(user.id.get, user.role))
          } yield {
            Success(token)
          }
      }
    }
  }

  def login(request: UserLoginRequest): Future[UserAuthResult] = {
    userAuthRepo.findByUserEmail(request.email).flatMap {
      case Some(userAuth) if checkPassword(request.password, userAuth.password) =>
        val token = generateToken
        for {
          Some(user) <- userRepo.findByUserId(userAuth.userId)
          _ <- tokenRepo.insert(token, user.id.get)
          _ <- redisClient.setnx(token, Identity.User(user.id.get, user.role))
        } yield {
          Success(token)
        }
      case Some(_) => Future.successful(InvalidData("Password is invalid"))
      case None => Future.successful(UserNotExists("E-mail does not exist"))
    }
  }

  private lazy val random = new SecureRandom()

  private def generateToken: String = new BigInteger(255, random).toString(32)

  private def hashPassword(password: String): String = BCrypt.hashpw(password, BCrypt.gensalt(12))

  private def checkPassword(password: String, passwordHash: String): Boolean = BCrypt.checkpw(password, passwordHash)
}

trait UserAuthResult

object UserAuthResult {

  case class InvalidData(msg: String) extends UserAuthResult

  case class UserExists(msg: String) extends UserAuthResult

  case class UserNotExists(msg: String) extends UserAuthResult

  case class Success(token: String) extends UserAuthResult

} 
Example 20
Source File: EncryptedKeySpec.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.core.keystore

import java.security.SecureRandom

import cats.effect.IO
import io.circe.parser._
import jbok.crypto._
import jbok.crypto.signature.KeyPair
import io.circe.syntax._
import jbok.core.CoreSpec

class EncryptedKeySpec extends CoreSpec {

  val gethKey =
    """{
      |  "id": "033b7a63-30f2-47fc-bbbe-d22925a14ab3",
      |  "address": "932245e1c40ec2026a2c7acc80befb68816cdba4",
      |  "crypto": {
      |    "cipher": "aes-128-ctr",
      |    "ciphertext": "8fb53f8695795d1f0480cad7954bd7a888392bb24c414b9895b4cb288b4897dc",
      |    "cipherparams": {
      |      "iv": "7a754cfd548a351aed270f6b1bfd306d"
      |    },
      |    "kdf": "scrypt",
      |    "kdfparams": {
      |      "dklen": 32,
      |      "n": 262144,
      |      "p": 1,
      |      "r": 8,
      |      "salt": "2321125eff8c3172a05a5947726004075b30e0a01534061fa5c13fb4e5e32465"
      |    },
      |    "mac": "6383677d3b0f34b1dcb9e1c767f8130daf6233266e35f28e00467af97bf2fbfa"
      |  },
      |  "version": 3
      |}
    """.stripMargin

  "EncryptedKey" should {
    "decrypt a key encrypted by Geth" in {
      val key = decode[EncryptedKey](gethKey)
      key.isRight shouldBe true
    }

    "securely store private keys" in {
      val secureRandom = new SecureRandom
      val prvKey       = KeyPair.Secret(randomByteString(secureRandom, 32))
      val passphrase   = "P4S5W0rd"
      val encKey       = EncryptedKey[IO](prvKey, passphrase, secureRandom).unsafeRunSync()

      val json    = encKey.asJson.spaces2
      val decoded = decode[EncryptedKey](json)

      decoded shouldBe Right(encKey)
      decoded.flatMap(_.decrypt(passphrase)) shouldBe Right(prvKey)
    }
  }
} 
Example 21
Source File: SSLSupport.scala    From sparta   with Apache License 2.0 5 votes vote down vote up
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 22
Source File: JsonRpcServer.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.jsonrpc.server

import java.security.SecureRandom

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.HttpOriginRange
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{MalformedRequestContentRejection, RejectionHandler, Route}
import ch.megard.akka.http.cors.javadsl.CorsRejection
import ch.megard.akka.http.cors.scaladsl.CorsDirectives._
import ch.megard.akka.http.cors.scaladsl.settings.CorsSettings
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import io.iohk.ethereum.jsonrpc.{JsonRpcController, JsonRpcErrors, JsonRpcRequest, JsonRpcResponse}
import io.iohk.ethereum.utils.Logger
import org.json4s.JsonAST.JInt
import org.json4s.{DefaultFormats, native}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

trait JsonRpcServer extends Json4sSupport {
  val jsonRpcController: JsonRpcController

  implicit val serialization = native.Serialization

  implicit val formats = DefaultFormats

  def corsAllowedOrigins: HttpOriginRange

  val corsSettings = CorsSettings.defaultSettings.copy(
    allowGenericHttpRequests = true,
    allowedOrigins = corsAllowedOrigins
  )

  implicit def myRejectionHandler: RejectionHandler =
    RejectionHandler.newBuilder()
      .handle {
        case _: MalformedRequestContentRejection =>
          complete((StatusCodes.BadRequest, JsonRpcResponse("2.0", None, Some(JsonRpcErrors.ParseError), JInt(0))))
        case _: CorsRejection =>
          complete(StatusCodes.Forbidden)
      }
      .result()

  val route: Route = cors(corsSettings) {
    (pathEndOrSingleSlash & post) {
      entity(as[JsonRpcRequest]) { request =>
        handleRequest(request)
      } ~ entity(as[Seq[JsonRpcRequest]]) { request =>
        handleBatchRequest(request)
      }
    }
  }

  
  def run(): Unit

  private def handleRequest(request: JsonRpcRequest) = {
    complete(jsonRpcController.handleRequest(request))
  }

  private def handleBatchRequest(requests: Seq[JsonRpcRequest]) = {
    complete(Future.sequence(requests.map(request => jsonRpcController.handleRequest(request))))
  }
}

object JsonRpcServer extends Logger {

  def apply(jsonRpcController: JsonRpcController, config: JsonRpcServerConfig, secureRandom: SecureRandom)
           (implicit actorSystem: ActorSystem): Either[String, JsonRpcServer] = config.mode match {
    case "http" => Right(new JsonRpcHttpServer(jsonRpcController, config)(actorSystem))
    case "https" => Right(new JsonRpcHttpsServer(jsonRpcController, config, secureRandom)(actorSystem))
    case _ => Left(s"Cannot start JSON RPC server: Invalid mode ${config.mode} selected")
  }

  trait JsonRpcServerConfig {
    val mode: String
    val enabled: Boolean
    val interface: String
    val port: Int
    val certificateKeyStorePath: Option[String]
    val certificateKeyStoreType: Option[String]
    val certificatePasswordFile: Option[String]
    val corsAllowedOrigins: HttpOriginRange
  }


} 
Example 23
Source File: JsonRpcHttpsServer.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
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 24
Source File: ECIESCoder.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.crypto

import java.io.{ByteArrayInputStream, IOException}
import java.math.BigInteger
import java.security.SecureRandom

import org.spongycastle.crypto.digests.{SHA1Digest, SHA256Digest}
import org.spongycastle.crypto.engines.AESEngine
import org.spongycastle.crypto.generators.ECKeyPairGenerator
import org.spongycastle.crypto.macs.HMac
import org.spongycastle.crypto.modes.SICBlockCipher
import org.spongycastle.crypto.params._
import org.spongycastle.crypto.parsers.ECIESPublicKeyParser
import org.spongycastle.crypto.{BufferedBlockCipher, InvalidCipherTextException}
import org.spongycastle.math.ec.ECPoint

object ECIESCoder {

  val KeySize = 128
  val PublicKeyOverheadSize = 65
  val MacOverheadSize = 32
  val OverheadSize = PublicKeyOverheadSize + KeySize / 8 + MacOverheadSize

  @throws[IOException]
  @throws[InvalidCipherTextException]
  def decrypt(privKey: BigInteger, cipher: Array[Byte], macData: Option[Array[Byte]] = None): Array[Byte] = {
    val is = new ByteArrayInputStream(cipher)
    val ephemBytes = new Array[Byte](2 * ((curve.getCurve.getFieldSize + 7) / 8) + 1)
    is.read(ephemBytes)
    val ephem = curve.getCurve.decodePoint(ephemBytes)
    val IV = new Array[Byte](KeySize / 8)
    is.read(IV)
    val cipherBody = new Array[Byte](is.available)
    is.read(cipherBody)
    decrypt(ephem, privKey, Some(IV), cipherBody, macData)
  }

  @throws[InvalidCipherTextException]
  def decrypt(ephem: ECPoint, prv: BigInteger, IV: Option[Array[Byte]], cipher: Array[Byte], macData: Option[Array[Byte]]): Array[Byte] = {
    val aesEngine = new AESEngine

    val iesEngine = new EthereumIESEngine(
      kdf = Left(new ConcatKDFBytesGenerator(new SHA256Digest)),
      mac = new HMac(new SHA256Digest),
      hash = new SHA256Digest,
      cipher = Some(new BufferedBlockCipher(new SICBlockCipher(aesEngine))),
      IV = IV,
      prvSrc = Left(new ECPrivateKeyParameters(prv, curve)),
      pubSrc = Left(new ECPublicKeyParameters(ephem, curve)))


    iesEngine.processBlock(cipher, 0, cipher.length, forEncryption = false, macData)
  }

  
  @throws[IOException]
  @throws[InvalidCipherTextException]
  def encryptSimple(pub: ECPoint, secureRandom: SecureRandom, plaintext: Array[Byte]): Array[Byte] = {

    val eGen = new ECKeyPairGenerator
    val gParam = new ECKeyGenerationParameters(curve, secureRandom)
    eGen.init(gParam)

    val iesEngine = new EthereumIESEngine(
      kdf = Right(new MGF1BytesGeneratorExt(new SHA1Digest)),
      mac = new HMac(new SHA1Digest),
      hash = new SHA1Digest,
      cipher = None,
      IV = Some(new Array[Byte](0)),
      prvSrc = Right(eGen),
      pubSrc = Left(new ECPublicKeyParameters(pub, curve)),
      hashMacKey = false)

    iesEngine.processBlock(plaintext, 0, plaintext.length, forEncryption = true)
  }

  private def makeIESEngine(pub: ECPoint, prv: BigInteger, IV: Option[Array[Byte]]) = {
    val aesEngine = new AESEngine

    val iesEngine = new EthereumIESEngine(
      kdf = Left(new ConcatKDFBytesGenerator(new SHA256Digest)),
      mac = new HMac(new SHA256Digest),
      hash = new SHA256Digest,
      cipher = Some(new BufferedBlockCipher(new SICBlockCipher(aesEngine))),
      IV = IV,
      prvSrc = Left(new ECPrivateKeyParameters(prv, curve)),
      pubSrc = Left(new ECPublicKeyParameters(pub, curve)))

    iesEngine
  }

} 
Example 25
Source File: EncryptedKey.scala    From mantis   with Apache License 2.0 5 votes vote down vote up
package io.iohk.ethereum.keystore

import java.security.SecureRandom
import java.util.UUID

import akka.util.ByteString
import io.iohk.ethereum.crypto
import io.iohk.ethereum.crypto.SymmetricCipher
import io.iohk.ethereum.domain.Address
import io.iohk.ethereum.keystore.EncryptedKey._

object EncryptedKey {
  val AES128CTR = "aes-128-ctr"
  val AES128CBC = "aes-128-cbc"
  val Scrypt = "scrypt"
  val Pbkdf2 = "pbkdf2"

  sealed trait KdfParams
  case class ScryptParams(salt: ByteString, n: Int, r: Int, p: Int, dklen: Int) extends KdfParams
  case class Pbkdf2Params(salt: ByteString, prf: String, c: Int, dklen: Int) extends KdfParams

  case class CryptoSpec(
    cipher: String,
    ciphertext: ByteString,
    iv: ByteString,
    kdfParams: KdfParams,
    mac: ByteString)

  def apply(prvKey: ByteString, passphrase: String, secureRandom: SecureRandom): EncryptedKey = {
    val version = 3
    val uuid = UUID.randomUUID()
    val pubKey = crypto.pubKeyFromPrvKey(prvKey)
    val address = Address(crypto.kec256(pubKey))

    val salt = crypto.secureRandomByteString(secureRandom, 32)
    val kdfParams = ScryptParams(salt, 1 << 18, 8, 1, 32) //params used by Geth
    val dk = deriveKey(passphrase, kdfParams)

    val cipherName = AES128CTR
    val iv = crypto.secureRandomByteString(secureRandom, 16)
    val secret = dk.take(16)
    val ciphertext = getCipher(cipherName).encrypt(secret, iv, prvKey)

    val mac = createMac(dk, ciphertext)

    val cryptoSpec = CryptoSpec(cipherName, ciphertext, iv, kdfParams, mac)
    EncryptedKey(uuid, address, cryptoSpec, version)
  }

  private def getCipher(cipherName: String): SymmetricCipher =
    Map(AES128CBC -> crypto.AES_CBC, AES128CTR -> crypto.AES_CTR)(cipherName.toLowerCase)

  private def deriveKey(passphrase: String, kdfParams: KdfParams): ByteString =
    kdfParams match {
      case ScryptParams(salt, n, r, p, dklen) =>
        crypto.scrypt(passphrase, salt, n, r, p, dklen)

      case Pbkdf2Params(salt, prf, c, dklen) =>
        // prf is currently ignored, only hmac sha256 is used
        crypto.pbkdf2HMacSha256(passphrase, salt, c, dklen)
    }

  private def createMac(dk: ByteString, ciphertext: ByteString): ByteString =
    crypto.kec256(dk.slice(16, 32) ++ ciphertext)
}


case class EncryptedKey(
  id: UUID,
  address: Address,
  cryptoSpec: CryptoSpec,
  version: Int
) {

  def decrypt(passphrase: String): Either[String, ByteString] = {
    val dk = deriveKey(passphrase, cryptoSpec.kdfParams)
    val secret = dk.take(16)
    val decrypted = getCipher(cryptoSpec.cipher).decrypt(secret, cryptoSpec.iv, cryptoSpec.ciphertext)
    decrypted
      .filter(_ => createMac(dk, cryptoSpec.ciphertext) == cryptoSpec.mac)
      .map(Right(_))
      .getOrElse(Left("Couldn't decrypt key with given passphrase"))
  }
} 
Example 26
Source File: SecureRandomProvider.scala    From akka-persistence-dynamodb   with Apache License 2.0 5 votes vote down vote up
package com.github.j5ik2o.akka.persistence.dynamodb.client.v1

import java.security.SecureRandom

import akka.actor.DynamicAccess
import com.github.j5ik2o.akka.persistence.dynamodb.config.PluginConfig
import com.github.j5ik2o.akka.persistence.dynamodb.exception.PluginException

import scala.collection.immutable._
import scala.util.{ Failure, Success }

trait SecureRandomProvider {
  def create: SecureRandom
}

object SecureRandomProvider {

  def create(dynamicAccess: DynamicAccess, pluginConfig: PluginConfig): SecureRandomProvider = {
    val className = pluginConfig.clientConfig.v1ClientConfig.clientConfiguration.secureRandomProviderClassName
    dynamicAccess
      .createInstanceFor[SecureRandomProvider](
        className,
        Seq(
          classOf[DynamicAccess] -> dynamicAccess,
          classOf[PluginConfig]  -> pluginConfig
        )
      ) match {
      case Success(value) => value
      case Failure(ex) =>
        throw new PluginException("Failed to initialize SecureRandomProvider", Some(ex))
    }
  }

  final class Default(dynamicAccess: DynamicAccess, pluginConfig: PluginConfig) extends SecureRandomProvider {
    override def create: SecureRandom = new SecureRandom()
  }
} 
Example 27
Source File: Util.scala    From lila-ws   with GNU Affero General Public License v3.0 5 votes vote down vote up
package lila.ws
package util

import java.security.SecureRandom

object Util {

  def nowSeconds: Int = (System.currentTimeMillis() / 1000).toInt

  object random {
    private val secureRandom     = new SecureRandom()
    private val chars            = (('0' to '9') ++ ('a' to 'z') ++ ('A' to 'Z')).mkString
    private val nbChars          = chars.size
    def char: Char               = chars(secureRandom nextInt nbChars)
    def string(len: Int): String = new String(Array.fill(len)(char))
  }
} 
Example 28
Source File: ManagedRandom.scala    From tsec   with MIT License 5 votes vote down vote up
package tsec.common

import java.security.SecureRandom


  private[tsec] val cachedRand: SecureRandom = {
    val r = SecureRandom.getInstance(ManagedRandom.UnixURandom)
    r.nextBytes(new Array[Byte](20)) //Force reseed
    r
  }

  def nextBytes(bytes: Array[Byte]): Unit =
    cachedRand.nextBytes(bytes)
}

object ManagedRandom {
  private[ManagedRandom] val UnixURandom = "NativePRNGNonBlocking"
} 
Example 29
Source File: Https.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
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 30
Source File: Service.scala    From reactive-microservices   with MIT License 5 votes vote down vote up
import akka.actor.ActorSystem
import akka.event.Logging
import java.math.BigInteger
import java.security.SecureRandom
import scala.concurrent.{ExecutionContext, Future}

class Service(repository: Repository)(implicit actorSystem: ActorSystem, ec: ExecutionContext) extends Config {
  def relogin(reloginRequest: ReloginRequest): Future[Option[Token]] = {
    repository.addMethodToValidTokenByValue(reloginRequest.tokenValue, reloginRequest.authMethod)
  }

  def login(loginRequest: LoginRequest): Future[Token] = {
    val newToken = createFreshToken(loginRequest.identityId, loginRequest.authMethod)
    repository.insertToken(newToken).map(_ => newToken)
  }

  def findAndRefreshToken(tokenValue: String): Future[Option[Token]] = {
    repository.findValidTokenByValue(tokenValue).map { tokenOption =>
      tokenOption.map { token =>
        val newToken = refreshToken(token)
        if (newToken != token)
          repository.updateTokenByValue(token.value, newToken).onFailure { case t => logger.error(t, "Token refreshment failed") }
        newToken
      }
    }
  }

  def logout(tokenValue: String): Unit = {
    repository.deleteTokenByValue(tokenValue).onFailure { case t => logger.error(t, "Token deletion failed") }
  }

  private def createFreshToken(identityId: Long, authMethod: String): Token = {
    Token(generateToken, System.currentTimeMillis() + tokenTtl, identityId, Set(authMethod))
  }

  private def generateToken: String = new BigInteger(255, random).toString(32)

  private def refreshToken(token: Token): Token = token.copy(validTo = math.max(token.validTo, System.currentTimeMillis() + sessionTtl))

  private val random = new SecureRandom()

  private val logger = Logging(actorSystem, getClass)
} 
Example 31
Source File: OAuthAccessToken.scala    From scala-oauth2-provider-example-skinny-orm   with MIT License 5 votes vote down vote up
package models

import java.security.SecureRandom

import org.joda.time.DateTime
import scalikejdbc._
import skinny.orm.SkinnyCRUDMapper

import scala.util.Random

case class OauthAccessToken(
  id: Long,
  accountId: Long,
  account: Option[Account] = None,
  oauthClientId: Long,
  oauthClient: Option[OauthClient] = None,
  accessToken: String,
  refreshToken: String,
  createdAt: DateTime
)

object OauthAccessToken extends SkinnyCRUDMapper[OauthAccessToken] {

  override val tableName = "oauth_access_token"
  override def defaultAlias = createAlias("oat")

  belongsTo[Account](Account, (oat, account) => oat.copy(account = account)).byDefault
  belongsTo[OauthClient](OauthClient, (oat, client) => oat.copy(oauthClient = client)).byDefault

  override def extract(rs: WrappedResultSet, oat: ResultName[OauthAccessToken]) = new OauthAccessToken(
    id = rs.long(oat.id),
    accountId = rs.long(oat.accountId),
    oauthClientId = rs.long(oat.oauthClientId),
    accessToken = rs.string(oat.accessToken),
    refreshToken = rs.string(oat.refreshToken),
    createdAt = rs.jodaDateTime(oat.createdAt)
  )

  def create(account: Account, client: OauthClient)(implicit session: DBSession): OauthAccessToken = {
    def randomString(length: Int) = new Random(new SecureRandom()).alphanumeric.take(length).mkString
    val accessToken = randomString(40)
    val refreshToken = randomString(40)
    val createdAt = new DateTime()

    val oauthAccessToken = new OauthAccessToken(
      id = 0,
      accountId = account.id,
      oauthClientId = client.id,
      accessToken = accessToken,
      refreshToken = refreshToken,
      createdAt = createdAt
    )

    val generatedId = OauthAccessToken.createWithNamedValues(
      column.accountId -> oauthAccessToken.accountId,
      column.oauthClientId -> oauthAccessToken.oauthClientId,
      column.accessToken -> oauthAccessToken.accessToken,
      column.refreshToken -> oauthAccessToken.refreshToken,
      column.createdAt -> oauthAccessToken.createdAt
    )
    oauthAccessToken.copy(id = generatedId)
  }

  def delete(account: Account, client: OauthClient)(implicit session: DBSession): Int = {
    OauthAccessToken.deleteBy(sqls
      .eq(column.accountId, account.id).and
      .eq(column.oauthClientId, client.id)
    )
  }

  def refresh(account: Account, client: OauthClient)(implicit session: DBSession): OauthAccessToken = {
    delete(account, client)
    create(account, client)
  }

  def findByAccessToken(accessToken: String)(implicit session: DBSession): Option[OauthAccessToken] = {
    val oat = OauthAccessToken.defaultAlias
    OauthAccessToken.where(sqls.eq(oat.accessToken, accessToken)).apply().headOption
  }

  def findByAuthorized(account: Account, clientId: String)(implicit session: DBSession): Option[OauthAccessToken] = {
    val oat = OauthAccessToken.defaultAlias
    val oac = OauthClient.defaultAlias
    OauthAccessToken.where(sqls
      .eq(oat.accountId, account.id).and
      .eq(oac.clientId, clientId)
    ).apply().headOption
  }

  def findByRefreshToken(refreshToken: String)(implicit session: DBSession): Option[OauthAccessToken] = {
    val expireAt = new DateTime().minusMonths(1)
    val oat = OauthAccessToken.defaultAlias
    OauthAccessToken.where(sqls
      .eq(oat.refreshToken, refreshToken).and
      .gt(oat.createdAt, expireAt)
    ).apply().headOption
  }
} 
Example 32
Source File: Utils.scala    From incubator-livy   with Apache License 2.0 5 votes vote down vote up
package org.apache.livy

import java.io.{Closeable, File, InputStreamReader}
import java.net.URL
import java.nio.charset.StandardCharsets.UTF_8
import java.security.SecureRandom
import java.util.Properties

import scala.annotation.tailrec
import scala.collection.JavaConverters._
import scala.concurrent.TimeoutException
import scala.concurrent.duration.Duration

import org.apache.commons.codec.binary.Base64

object Utils {
  def getPropertiesFromFile(file: File): Map[String, String] = {
    loadProperties(file.toURI().toURL())
  }

  def loadProperties(url: URL): Map[String, String] = {
    val inReader = new InputStreamReader(url.openStream(), UTF_8)
    try {
      val properties = new Properties()
      properties.load(inReader)
      properties.stringPropertyNames().asScala.map { k =>
        (k, properties.getProperty(k).trim())
      }.toMap
    } finally {
      inReader.close()
    }
  }

  
  def isProcessAlive(process: Process): Boolean = {
    try {
      process.exitValue()
      false
    } catch {
      case _: IllegalThreadStateException =>
        true
    }
  }

  def startDaemonThread(name: String)(f: => Unit): Thread = {
    val thread = new Thread(name) {
      override def run(): Unit = f
    }
    thread.setDaemon(true)
    thread.start()
    thread
  }

  def usingResource[A <: Closeable, B](resource: A)(f: A => B): B = {
    try {
      f(resource)
    } finally {
      resource.close()
    }
  }

  def createSecret(secretBitLength: Int): String = {
    val rnd = new SecureRandom()
    val secretBytes = new Array[Byte](secretBitLength / java.lang.Byte.SIZE)
    rnd.nextBytes(secretBytes)

    Base64.encodeBase64String(secretBytes)
  }
} 
Example 33
Source File: BigNumber.scala    From wowchat   with GNU General Public License v3.0 5 votes vote down vote up
package wowchat.realm


object BigNumber {

  def apply(value: BigInt): BigNumber = {
    new BigNumber(value)
  }

  def apply(value: String): BigNumber = {
    BigNumber(value, 16)
  }

  def apply(value: String, radix: Int): BigNumber = {
    new BigNumber(BigInt(value, radix))
  }

  def apply(array: Array[Byte], reverse: Boolean = false): BigNumber = {
    if (reverse) {
      val length = array.length
      (0 until length / 2).foreach(i => {
        val j = array(i)
        array(i) = array(length - i - 1)
        array(length - i - 1) = j
      })
    }

    if (array(0) < 0) {
      val tmp = new Array[Byte](array.length + 1)
      System.arraycopy(array, 0, tmp, 1, array.length)
      new BigNumber(BigInt(tmp))
    } else {
      new BigNumber(BigInt(array))
    }
  }

  def rand(amount: Int): BigNumber = {
    new BigNumber(BigInt(1, new SecureRandom().generateSeed(amount)))
  }
}

class BigNumber(private val bigInt: BigInt) {

  def *(number: BigNumber): BigNumber = {
    new BigNumber(bigInt * number.bigInt.abs)
  }

  def -(number: BigNumber): BigNumber = {
    new BigNumber(bigInt - number.bigInt.abs)
  }

  def +(number: BigNumber): BigNumber = {
    new BigNumber(bigInt + number.bigInt.abs)
  }

  def modPow(val1: BigNumber, val2: BigNumber): BigNumber = {
    new BigNumber(bigInt.modPow(val1.bigInt.abs, val2.bigInt.abs))
  }

  def toHexString: String = {
    bigInt.toString(16).toUpperCase
  }

  def asByteArray(reqSize: Int = 0, reverse: Boolean = true): Array[Byte] = {
    var array = bigInt.toByteArray
    if (array(0) == 0) {
      val tmp = new Array[Byte](array.length - 1)
      System.arraycopy(array, 1, tmp, 0, tmp.length)
      array = tmp
    }

    val length = array.length
    if (reverse) {
      (0 until length / 2).foreach(i => {
        val j = array(i)
        array(i) = array(length - 1 - i)
        array(length - 1 - i) = j
      })
    }

    if (reqSize > length) {
      val newArray = new Array[Byte](reqSize)
      System.arraycopy(array, 0, newArray, 0, length)
      return newArray
    }

    array
  }
} 
Example 34
Source File: Ident.scala    From docspell   with GNU General Public License v3.0 5 votes vote down vote up
package docspell.common

import java.security.SecureRandom
import java.util.UUID

import cats.Eq
import cats.effect.Sync
import cats.implicits._

import io.circe.{Decoder, Encoder}
import scodec.bits.ByteVector

case class Ident(id: String) {
  def isEmpty: Boolean =
    id.trim.isEmpty

  def nonEmpty: Boolean =
    !isEmpty

  def /(next: Ident): Ident =
    new Ident(id + "." + next.id)
}

object Ident {
  implicit val identEq: Eq[Ident] =
    Eq.by(_.id)

  val chars: Set[Char] = (('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9') ++ "-_.").toSet

  def randomUUID[F[_]: Sync]: F[Ident] =
    Sync[F].delay(unsafe(UUID.randomUUID.toString))

  def randomId[F[_]: Sync]: F[Ident] =
    Sync[F].delay {
      val random = new SecureRandom()
      val buffer = new Array[Byte](32)
      random.nextBytes(buffer)
      unsafe(ByteVector.view(buffer).toBase58.grouped(11).mkString("-"))
    }

  def apply(str: String): Either[String, Ident] =
    fromString(str)

  def fromString(s: String): Either[String, Ident] =
    if (s.forall(chars.contains)) Right(new Ident(s))
    else Left(s"Invalid identifier: '$s'. Allowed chars: ${chars.toList.sorted.mkString}")

  def fromBytes(bytes: ByteVector): Ident =
    unsafe(bytes.toBase58)

  def fromByteArray(bytes: Array[Byte]): Ident =
    fromBytes(ByteVector.view(bytes))

  def unsafe(s: String): Ident =
    fromString(s) match {
      case Right(id) => id
      case Left(err) => sys.error(err)
    }

  def unapply(arg: String): Option[Ident] =
    fromString(arg).toOption

  implicit val encodeIdent: Encoder[Ident] =
    Encoder.encodeString.contramap(_.id)

  implicit val decodeIdent: Decoder[Ident] =
    Decoder.decodeString.emap(Ident.fromString)

} 
Example 35
Source File: MultiLoginCacheIdContainer.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package jp.t2v.lab.play2.auth

import java.security.SecureRandom
import java.util.concurrent.TimeUnit

import play.api.cache.CacheApi

import scala.annotation.tailrec
import scala.concurrent.duration.Duration
import scala.reflect.ClassTag
import scala.util.Random

class MultiLoginCacheIdContainer[Id: ClassTag](cache: CacheApi) extends IdContainer[Id] {

  private val log = play.api.Logger(getClass)

  private[auth] val tokenSuffix = ":multitoken"
  private[auth] val random = new Random(new SecureRandom())

  override def startNewSession(userId: Id, timeoutInSeconds: Int): AuthenticityToken = {
    log.info(s"Starting new session for user '$userId'.")
    val token = generate
    store(token, userId, Duration(timeoutInSeconds.toLong, TimeUnit.SECONDS))
    token
  }

  @tailrec
  private[auth] final def generate: AuthenticityToken = {
    val table = "abcdefghijklmnopqrstuvwxyz1234567890_.~*'()"
    val token = Iterator.continually(random.nextInt(table.size)).map(table).take(64).mkString
    if (get(token).isDefined) generate else token
  }

  def remove(token: AuthenticityToken) {
    log.info(s"Deleting session of user '${get(token)}'")
    cache.remove(token + tokenSuffix)
  }

  def get(token: AuthenticityToken): Option[Id] =
    cache.get(token + tokenSuffix).map(_.asInstanceOf[Id])

  private[auth] def store(token: AuthenticityToken, userId: Id, duration: Duration) {
    cache.set(token + tokenSuffix, userId, duration)
  }

  override def prolongTimeout(token: AuthenticityToken, timeoutInSeconds: Int) {
    get(token).foreach(store(token, _, Duration(timeoutInSeconds.toLong, TimeUnit.SECONDS)))
  }

} 
Example 36
Source File: UsesSslContext.scala    From scala-commons   with MIT License 5 votes vote down vote up
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 37
Source File: OAuthAuthorizationTokensDal.scala    From slick-akka-http-oauth2   with Apache License 2.0 5 votes vote down vote up
package persistence.dals

import java.security.SecureRandom
import java.sql.Timestamp

import org.joda.time.DateTime
import persistence.entities.SlickTables.OauthAccessTokenTable
import persistence.entities.{Account, OAuthAccessToken, OAuthClient}
import slick.driver.H2Driver.api._
import slick.driver.JdbcProfile
import utils.{Configuration, PersistenceModule}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Random


trait OAuthAccessTokensDal extends BaseDalImpl[OauthAccessTokenTable,OAuthAccessToken]{
  def create(account: Account, client: OAuthClient): Future[OAuthAccessToken]
  def delete(account: Account, client: OAuthClient): Future[Int]
  def refresh(account: Account, client: OAuthClient): Future[OAuthAccessToken]
  def findByAccessToken(accessToken: String): Future[Option[OAuthAccessToken]]
  def findByAuthorized(account: Account, clientId: String): Future[Option[OAuthAccessToken]]
  def findByRefreshToken(refreshToken: String): Future[Option[OAuthAccessToken]]
}

class OAuthAccessTokensDalImpl (modules: Configuration with PersistenceModule)(implicit override val db: JdbcProfile#Backend#Database) extends OAuthAccessTokensDal {
  override def create(account: Account, client: OAuthClient): Future[OAuthAccessToken] = {
    def randomString(length: Int) = new Random(new SecureRandom()).alphanumeric.take(length).mkString
    val accessToken = randomString(40)
    val refreshToken = randomString(40)
    val createdAt = new Timestamp(new DateTime().getMillis)
    val oauthAccessToken = new OAuthAccessToken(
      id = 0,
      accountId = account.id,
      oauthClientId = client.id,
      accessToken = accessToken,
      refreshToken = refreshToken,
      createdAt = createdAt
    )
    insert(oauthAccessToken).map(id => oauthAccessToken.copy(id = id))
  }

  override def delete(account: Account, client: OAuthClient): Future[Int] = {
    deleteByFilter( oauthToken => oauthToken.accountId === account.id && oauthToken.oauthClientId === client.id)
  }

  override def refresh(account: Account, client: OAuthClient): Future[OAuthAccessToken] = {
    delete(account, client)
    create(account, client)
  }

  override def findByAuthorized(account: Account, clientId: String): Future[Option[OAuthAccessToken]] = {
    val query = for {
      oauthClient <- modules.oauthClientsDal.tableQ
      token <- tableQ if oauthClient.id === token.oauthClientId && oauthClient.clientId === clientId && token.accountId === account.id
    } yield token
    db.run(query.result).map(_.headOption)
  }

  override def findByAccessToken(accessToken: String): Future[Option[OAuthAccessToken]] = {
    findByFilter(_.accessToken === accessToken).map(_.headOption)
  }

  override def findByRefreshToken(refreshToken: String): Future[Option[OAuthAccessToken]] = {
    val expireAt = new Timestamp(new DateTime().minusMonths(1).getMillis)
    findByFilter( token => token.refreshToken === refreshToken && token.createdAt > expireAt).map(_.headOption)

  }
} 
Example 38
Source File: Service.scala    From reactive-microservices   with MIT License 5 votes vote down vote up
import java.security.SecureRandom
import scala.concurrent.{Future, ExecutionContext}

class Service(gateway: Gateway, repository: Repository)(implicit ec: ExecutionContext) extends Config {
  def register(tokenValueOption: Option[String]): Future[Either[String, RegisterResponse]] =
    acquireIdentity(tokenValueOption).map {
      case Right(identity) =>
        val authEntry = generateAuthEntry(identity)
        val codeCard = generateCodeCard(1, authEntry.userIdentifier)
        repository.saveAuthEntryAndCodeCard(authEntry, codeCard)
        Right(RegisterResponse(identity, codeCard))
      case Left(l) => Left(l)
    }

  def activateCode(request: ActivateCodeRequest): Future[Either[String, ActivateCodeResponse]] = {
    Future.successful {
      val codes = repository.getInactiveCodesForUser(request.userIdentifier)
      codes.length match {
        case 0 => Left("You don't have available codes")
        case _ =>
          val codeAct = codes(random.nextInt(codes.length))
          repository.activateCode(request.userIdentifier, codeAct.cardIndex, codeAct.codeIndex)
          Right(ActivateCodeResponse(codeAct.cardIndex, codeAct.codeIndex))
      }
    }
  }

  def login(request: LoginRequest, tokenValueOption: Option[String]): Future[Either[String, Token]] = {
    repository.useCode(request.userIdentifier, request.cardIndex, request.codeIndex, request.code) match {
      case 1 =>
        tokenValueOption match {
          case None => gateway.requestLogin(repository.getIdentity(request.userIdentifier)).map(Right(_))
          case Some(tokenValue) =>
            gateway.requestRelogin(tokenValue).map {
              case Some(token) => Right(token)
              case None => Left("Token expired or not found")
            }
        }
      case 0 => Future.successful(Left(s"Invalid code"))
    }
  }

  def getCodeCard(request: GetCodeCardRequest, tokenValueOption: Option[String]): Future[Either[String, GetCodeCardResponse]] = {
    tokenValueOption match {
      case Some(tokenValue) =>
        gateway.requestRelogin(tokenValue).map {
          case None => Left("Token expired or not found")
          case Some(token) if repository.getIdentity(request.userIdentifier) == token.identityId =>
            Right(GetCodeCardResponse(request.userIdentifier, generateCodeCard(repository.getNextCardIndex(request.userIdentifier), request.userIdentifier)))
          case Some(token) => Left("Token expired or not found")
        }
      case None => Future.successful(Left("Token expired or not found"))
    }
  }

  private def acquireIdentity(tokenValueOption: Option[String]): Future[Either[String, Identity]] = {
    tokenValueOption match {
      case Some(tokenValue) => gateway.requestToken(tokenValue).map(_.right.map(token => Identity(token.identityId)))
      case None => gateway.requestNewIdentity().map(Right(_))
    }
  }

  private def generateAuthEntry(identity: Identity) = {
    AuthEntry(f"${random.nextInt(100000)}%05d${random.nextInt(100000)}%05d", identity.id, System.currentTimeMillis(), 1)
  }

  private def generateCodeCard(cardIndex: Long, userIdentifier: String) = {
    CodeCard(cardIndex, Seq.fill(cardSize) {f"${random.nextInt(1000000)}%06d" }, userIdentifier)
  }

  private val random = new SecureRandom
}