• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala SecureRandom类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.security.SecureRandom的典型用法代码示例。如果您正苦于以下问题:Scala SecureRandom类的具体用法?Scala SecureRandom怎么用?Scala SecureRandom使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了SecureRandom类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: Crypt

//设置package包名称以及导入依赖的类
package akka.util

import java.security.{ MessageDigest, SecureRandom }
//FIXME DOCS
object Crypt {
  val hex = "0123456789ABCDEF"
  val lineSeparator = System.getProperty("line.separator")

  lazy val random = SecureRandom.getInstance("SHA1PRNG")

  def md5(text: String): String = md5(unifyLineSeparator(text).getBytes("ASCII"))

  def md5(bytes: Array[Byte]): String = digest(bytes, MessageDigest.getInstance("MD5"))

  def sha1(text: String): String = sha1(unifyLineSeparator(text).getBytes("ASCII"))

  def sha1(bytes: Array[Byte]): String = digest(bytes, MessageDigest.getInstance("SHA1"))

  def generateSecureCookie: String = {
    val bytes = Array.fill(32)(0.byteValue)
    random.nextBytes(bytes)
    sha1(bytes)
  }

  def digest(bytes: Array[Byte], md: MessageDigest): String = {
    md.update(bytes)
    hexify(md.digest)
  }

  def hexify(bytes: Array[Byte]): String = {
    val builder = new java.lang.StringBuilder(bytes.length * 2)
    bytes.foreach { byte ? builder.append(hex.charAt((byte & 0xF0) >> 4)).append(hex.charAt(byte & 0xF)) }
    builder.toString
  }

  private def unifyLineSeparator(text: String): String = text.replaceAll(lineSeparator, "\n")
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:38,代码来源:Crypt.scala


示例2: Prover

//设置package包名称以及导入依赖的类
package scapi.sigma.dlog

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

import akka.actor.{Actor, ActorLogging, ActorRef}
import edu.biu.scapi.interactiveMidProtocols.sigmaProtocol.utility.{SigmaBIMsg, SigmaGroupElementMsg}
import edu.biu.scapi.primitives.dlog.GroupElement
import org.bouncycastle.util.BigIntegers
import scapi.sigma.rework.SigmaProtocolFunctions.{FirstMessage, RandomChallenge, SecondMessage, StartInteraction}


class Prover(commonInput: CommonInput,
             proverInput: ProverInput,
             verifierActor: ActorRef) extends Actor with ActorLogging {

  val dlog = commonInput.dlogGroup
  val w = proverInput.w
  val random = new SecureRandom()

  override def receive = beforeFirstMessage

  private def beforeFirstMessage: Receive = {
    case StartInteraction =>
      val qMinusOne = dlog.getOrder.subtract(BigInteger.ONE)

      val r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random)

      //Compute a = g^r.
      val a: GroupElement = dlog.exponentiate(dlog.getGenerator, r)

      val sigmaProtocolMsg = new SigmaGroupElementMsg(a.generateSendableData)
      verifierActor ! FirstMessage(sigmaProtocolMsg)
      context become beforeSecondMessage(r)
  }

  private def beforeSecondMessage(r: BigInteger): Receive = {
    case RandomChallenge(challenge) =>
      require(challenge.bytes.length * 8 == commonInput.protocolParams.soundness, "wrong challenge length")

      //Compute z = (r+ew) mod q
      val q: BigInteger = dlog.getOrder
      val e: BigInteger = new BigInteger(1, challenge.bytes)
      val ew: BigInteger = e.multiply(w).mod(q)
      val z: BigInteger = r.add(ew).mod(q)
      verifierActor ! SecondMessage(new SigmaBIMsg(z))
      context become finished
  }

  private def finished: Receive = {
    case a: Any => log.warning(s"Got a message after protocol being finished: $a")
  }
} 
开发者ID:kushti,项目名称:scala-scapi,代码行数:54,代码来源:Prover.scala


示例3: KeyGenerator

//设置package包名称以及导入依赖的类
package com.hypertino.services.authtoken

import java.security.SecureRandom

import com.hypertino.hyperbus.util.IdGeneratorBase

class KeyGenerator(keySize: Int) extends IdGeneratorBase{
  private val random = new SecureRandom()

  def nextKey(): String = {
    val sb = new StringBuilder(30)
    0 to keySize foreach { _ ?
      appendInt(sb, random.nextInt())
    }
    sb.toString
  }
} 
开发者ID:hypertino,项目名称:auth-token-service,代码行数:18,代码来源:KeyGenerator.scala


示例4: generate

//设置package包名称以及导入依赖的类
package proton.game

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

trait GameIdGenerator {
  def generate(moduleName: String): UUID
}

class NameHashedGameIdGenerator(clusterName: String) extends GameIdGenerator{
  override def generate(moduleName: String): UUID = {
    var mostSigBits = asUnsigned(clusterName.hashCode.toLong) << 32
    mostSigBits |= asUnsigned(moduleName.hashCode.toLong)

    val numberGenerator: SecureRandom = new SecureRandom()
    numberGenerator.setSeed(System.nanoTime())

    val leastSigBits = numberGenerator.nextLong()

    new UUID(mostSigBits.toLong, leastSigBits)
  }

  private def asUnsigned(unsignedLong: Long) =
    (BigInt(unsignedLong >>> 1) << 1) + (unsignedLong & 1)
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:26,代码来源:GameIdGenerator.scala


示例5: sslContext

//设置package包名称以及导入依赖的类
package org.packtpublishing.security

import java.security.{SecureRandom, KeyStore}
import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory}
import spray.io.ServerSSLEngineProvider
import resource._

trait SslSupport {
  val random = SecureRandom.getInstance("SHA1PRNG")
  
  val keyStoreLocation = "/spray-book-catalog.jks"
  val keyStorePassword = "passw0rd"

  implicit def sslContext: SSLContext = {    
    val keyStore = KeyStore.getInstance("jks")
    
    for (jks <- managed(getClass.getResourceAsStream(keyStoreLocation))) {
      keyStore.load(jks, keyStorePassword.toCharArray)
    }
    
    val keyManagerFactory = KeyManagerFactory.getInstance("SunX509")
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray)
    
    val trustManagerFactory = TrustManagerFactory.getInstance("SunX509")
    trustManagerFactory.init(keyStore)
    
    val context = SSLContext.getInstance("TLS")
    context.init(keyManagerFactory.getKeyManagers, trustManagerFactory.getTrustManagers, random)
    context
  }
   
  implicit def sslEngineProvider: ServerSSLEngineProvider = {
    ServerSSLEngineProvider { engine =>
      engine.setEnabledProtocols(Array("TLSv1", "TLSv1.1", "TLSv1.2"))
      engine
    }
  }
} 
开发者ID:allansene,项目名称:spray-scala-akka-book-catalog,代码行数:39,代码来源:SslSupport.scala


示例6: PasswordHasher

//设置package包名称以及导入依赖的类
package org.packtpublishing.security

import javax.crypto.spec.PBEKeySpec
import javax.crypto.SecretKeyFactory
import java.security.SecureRandom

object PasswordHasher { 
  lazy val random = SecureRandom.getInstance("SHA1PRNG")
  
  def hash(password: String): (Array[Byte], Array[Byte]) = {
    val salt = random.generateSeed(32)
    (hash(password, salt), salt)
  }
  
  def hash(password: String, salt: Array[Byte]) = {
    val secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
    val keySpec = new PBEKeySpec(password.toCharArray(), salt, 1000, 256)
    val secretKey = secretKeyFactory.generateSecret(keySpec)
    secretKey.getEncoded()
  }    
} 
开发者ID:allansene,项目名称:spray-scala-akka-book-catalog,代码行数:22,代码来源:PasswordHasher.scala


示例7: SecureIdGenerator

//设置package包名称以及导入依赖的类
package com.galacticfog.gestalt.lambda.utils

import java.security.SecureRandom

object SecureIdGenerator {

  val random = new SecureRandom()

  val alpha62 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  val alpha64 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+"

  def genId62(len: Int) = {
    val id = new StringBuilder(len)
    (1 to len) foreach(_ => id += alpha62.charAt(random.nextInt(alpha62.size)))
    id.toString
  }

  def genId64(len: Int) = {
    val id = new StringBuilder(len)
    (1 to len) foreach(_ => id += alpha64.charAt(random.nextInt(alpha64.size)))
    id.toString
  }

  def main(args: Array[String]) {
    val num = if (args.size > 0) args(0).toInt else 10
    for (i <- 1 to num) println(genId62(24))
  }

} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:30,代码来源:SecureIdGenerator.scala


示例8: SecureIdGenerator

//设置package包名称以及导入依赖的类
package com.galacticfog.gestalt.lambda.util

import java.security.SecureRandom

object SecureIdGenerator {

  val random = new SecureRandom()

  val alpha62 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  val alpha64 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+"

  def genId62(len: Int) = {
    val id = new StringBuilder(len)
    (1 to len) foreach(_ => id += alpha62.charAt(random.nextInt(alpha62.size)))
    id.toString
  }

  def genId64(len: Int) = {
    val id = new StringBuilder(len)
    (1 to len) foreach(_ => id += alpha64.charAt(random.nextInt(alpha64.size)))
    id.toString
  }

  def main(args: Array[String]) {
    val num = if (args.size > 0) args(0).toInt else 10
    for (i <- 1 to num) println(genId62(24))
  }

} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:30,代码来源:SecureIdGenerator.scala


示例9: RandomVal

//设置package包名称以及导入依赖的类
package com.jetprobe.fastgen.generators.entity

import java.security.SecureRandom

import com.jetprobe.fastgen.generators.{
  EntityGenerator,
  FieldOption,
  StringType
}
import com.typesafe.config.Config

import scala.util.matching.Regex


class RandomVal(datasetConfig: Config, regexMatcher: Regex.MatchIterator)
    extends EntityGenerator(datasetConfig, regexMatcher)

object RandomVal {
  val abc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  val numberStr = "0123456789"
  lazy val rnd = new SecureRandom()

  def apply(datasetConfig: Config,
            regexMatcher: Regex.MatchIterator): RandomVal = {
    val random = new RandomVal(datasetConfig, regexMatcher)

    random.addField("Random.String", StringType, (fieldOpt: FieldOption) => {
      val sb = new StringBuilder(10)
      for (i <- 0 until 20) {
        sb.append(abc(rnd.nextInt(abc.length)))
      }
      sb.toString
    })

    random.addField(
      "Random.number",
      StringType,
      (fieldOpt: FieldOption) => {
        val sb = new StringBuilder(10)
        for (i <- 0 until 10) {
          sb.append(abc(rnd.nextInt(numberStr.length)))
        }
        sb.toString
      }
    )

    random
  }
} 
开发者ID:amezng,项目名称:fastgen,代码行数:50,代码来源:RandomVal.scala


示例10: HttpClientProvider

//设置package包名称以及导入依赖的类
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)
    }
  }

} 
开发者ID:zalando-nakadi,项目名称:reactive-nakadi,代码行数:56,代码来源:HttpClientProvider.scala


示例11: Boot

//设置package包名称以及导入依赖的类
package com.zhranklin.homepage

import java.io.InputStream
import java.security.{KeyStore, SecureRandom}
import javax.net.ssl._

import akka.http.scaladsl._
import akka.util.Timeout
import com.typesafe.config.ConfigFactory

import scala.concurrent.duration._
import scala.io.{Source, StdIn}

object Boot extends App with MyRouteService {

  import ActorImplicits._

  implicit val timeout = Timeout(5.seconds)

  val conf = ConfigFactory.load().getConfig("settings.server")
  val host = conf.getString("host")
  val httpBindingFuture = Http().bindAndHandle(myRoute, host, conf.getInt("http_port"))
  val httpsBindingFuture =
    Http().bindAndHandle(myRoute, host, conf.getInt("https_port"), SSLConfig.https)
  println(s"Server online at http://$host:8080/\nPress RETURN to stop...")
  if (System.getProperty("dev") != null) {
    StdIn.readLine() // let it run until user presses return
    Seq(httpBindingFuture, httpsBindingFuture).foreach { _
      .flatMap(_.unbind())
      .onComplete(_ ? system.terminate())
    }
  }
}

object SSLConfig {
  val https: HttpsConnectionContext = {

    val password: Array[Char] = Source.fromInputStream(getClass.getClassLoader.getResourceAsStream("password")).toArray.filter(_ != '\n')

    val ks: KeyStore = KeyStore.getInstance("jks")
    val keystore: InputStream = getClass.getClassLoader.getResourceAsStream("zhranklin.com.jks")

    require(keystore != null, "Keystore required!")
    ks.load(keystore, password)

    val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance("SunX509")
    keyManagerFactory.init(ks, password)

    val tmf: TrustManagerFactory = TrustManagerFactory.getInstance("SunX509")
    tmf.init(ks)

    val sslContext: SSLContext = SSLContext.getInstance("TLS")
    sslContext.init(keyManagerFactory.getKeyManagers, tmf.getTrustManagers, new SecureRandom)
    ConnectionContext.https(sslContext)
  }

} 
开发者ID:zhranklin,项目名称:Private_Blog,代码行数:58,代码来源:Boot.scala


示例12: StringUtils

//设置package包名称以及导入依赖的类
package utils

import java.text.Normalizer
import java.util.regex.Pattern
import java.security.SecureRandom
import scala.util.Try

object StringUtils {

  def generateUuid(): String = {
    java.util.UUID.randomUUID().toString
  }

  def deAccent(str: String): String = {
    if (str == null || str.isEmpty) {
      ""
    } else {
      val nfdNormalizedString: String = Normalizer.normalize(str, Normalizer.Form.NFD);
      val pattern: Pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
      pattern.matcher(nfdNormalizedString).replaceAll("");
    }
  }

  
  //Random Generator
  private[this] val random = new SecureRandom()

  // Generate a random string of length n from the given alphabet
  private[this] def randomString(alphabet: String)(n: Int): String = {
    Stream.continually(random.nextInt(alphabet.size)).map(alphabet).take(n).mkString
  }

  // Generate a random alphabnumeric string of length n
  def randomAlphanumericString(n: Int): String = {
    randomString("abcdefghijklmnopqrstuvwxyz0123456789")(n)
  }
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:38,代码来源:StringUtil.scala


示例13: generateToken

//设置package包名称以及导入依赖的类
package controllers.stack

import jp.t2v.lab.play2.stackc.{RequestAttributeKey, RequestWithAttributes, StackableController}
import scala.concurrent.Future
import play.api.mvc.{Result, Request, Controller}
import play.api.data._
import play.api.data.Forms._
import scala.util.Random
import java.security.SecureRandom

trait TokenValidateElement extends StackableController {
    self: Controller =>

  private val PreventingCsrfTokenSessionKey = "preventingCsrfToken"

  private val tokenForm = Form(PreventingCsrfToken.FormKey -> text)

  private val random = new Random(new SecureRandom)
  private val table = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') ++ "^`~:/?,.{[}}|+_()*^%$#@!"

  private def generateToken: PreventingCsrfToken = PreventingCsrfToken {
    Iterator.continually(random.nextInt(table.size)).map(table).take(32).mkString
  }

  case object PreventingCsrfTokenKey extends RequestAttributeKey[PreventingCsrfToken]
  case object IgnoreTokenValidation extends RequestAttributeKey[Boolean]

  private def validateToken(request: Request[_]): Boolean = (for {
    tokenInForm    <- tokenForm.bindFromRequest()(request).value
    tokenInSession <- request.session.get(PreventingCsrfTokenSessionKey)
  } yield tokenInForm == tokenInSession) getOrElse false

  override def proceed[A](request: RequestWithAttributes[A])(f: RequestWithAttributes[A] => Future[Result]): Future[Result] = {
    if (isIgnoreTokenValidation(request) || validateToken(request)) {
      implicit val ctx = StackActionExecutionContext(request)
      val newToken = generateToken
      super.proceed(request.set(PreventingCsrfTokenKey, newToken))(f) map {
        _.withSession(PreventingCsrfTokenSessionKey -> newToken.value)
      }
    } else {
      Future.successful(BadRequest("Invalid preventing CSRF token"))
    }
  }

  implicit def isIgnoreTokenValidation(implicit request: RequestWithAttributes[_]): Boolean =
    request.get(IgnoreTokenValidation).exists(identity)

  implicit def preventingCsrfToken(implicit request: RequestWithAttributes[_]): PreventingCsrfToken =
    request.get(PreventingCsrfTokenKey).get


}

case class PreventingCsrfToken(value: String)

object PreventingCsrfToken {

  val FormKey = "preventingCsrfToken"

} 
开发者ID:bananapianist,项目名称:playfw_sample,代码行数:61,代码来源:TokenValidateElement.scala


示例14: SessionContainer

//设置package包名称以及导入依赖的类
package authes

import java.security.SecureRandom

import jp.t2v.lab.play2.auth.{AuthenticityToken, IdContainer}
import models.Session
import scalikejdbc._

import scala.annotation.tailrec
import scala.util.Random

class SessionContainer extends IdContainer[Long] {
  import SessionContainer._

  val random = new Random(new SecureRandom())

  override def startNewSession(userId: Long, timeoutInSeconds: Int): AuthenticityToken = {
    val now = System.currentTimeMillis()
    val token = generate
    Session(0L, userId, token, now, now + timeoutInSeconds.toLong).save()(AutoSession)
    token
  }

  override def remove(token: AuthenticityToken): Unit =
    Session.deleteBy(sqls.eq(Session.column.token, token))

  override def get(token: AuthenticityToken): Option[Long] =
    Session.findByToken(token).map(_.accountId)

  override def prolongTimeout(token: AuthenticityToken, timeoutInSeconds: Int): Unit =
    Session.findByToken(token).map { s =>
      s.copy(expire = System.currentTimeMillis() + timeoutInSeconds).save()
    }

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

}

object SessionContainer {
  val TokenSize = 64
  implicit val db: DBSession = AutoSession
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:48,代码来源:SessionContainer.scala


示例15: SecurityHandlers

//设置package包名称以及导入依赖的类
package im.actor.server.cli

import java.security.SecureRandom

import akka.http.scaladsl.util.FastFuture
import better.files._
import im.actor.crypto.Curve25519

import scala.concurrent.Future

final class SecurityHandlers {
  private val random = new SecureRandom()

  def createKey(path: String): Future[Unit] = {
    val pubPath = path + ".pub"
    val privatePath = path + ".private"

    val pubFile = File(pubPath)
    val privateFile = File(privatePath)

    if (pubFile.exists) {
      println(s"File $pubPath already exists!")
      FastFuture.successful(())
    } else if (privateFile.exists) {
      println(s"File $privatePath already exists!")
      FastFuture.successful(())
    } else {
      val randomBytes = new Array[Byte](32)
      random.nextBytes(randomBytes)

      val pair = Curve25519.keyGen(randomBytes)
      pubFile.write(pair.getPublicKey)
      privateFile.write(pair.getPrivateKey)

      println(
        s"""
           |Created $pubFile and $privateFile
           |You need to add the following to your server.conf:
           |
           |
           |modules: {
           |  # ... other modules
           |  security {
           |  # ... other settings
           |    server-keys: [
           |    # ... other server keys
           |      {
           |        public: "$pubPath"
           |        private: "$privatePath"
           |      }
           |    ]
           |  }
           |}
           |""".stripMargin
      )
      FastFuture.successful(())
    }
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:60,代码来源:SecurityHandlers.scala


示例16: SessionHandler

//设置package包名称以及导入依赖的类
package controllers.api.auth

import java.security.SecureRandom

import com.github.sample.utils.Loggable
import jp.t2v.lab.play2.auth.{AuthenticityToken, IdContainer}

import scala.reflect.ClassTag
import scala.collection.mutable
import scala.util.Random

//???????????????
class SessionHandler[Id: ClassTag](
  tokenMap: mutable.Map[Id, AuthenticityToken],
  tokenMap2: mutable.Map[AuthenticityToken, Id]
) extends IdContainer[Id] with Loggable {

  val random = new Random(new SecureRandom())


  //???timeout?expire??????
  override def startNewSession(userId: Id, timeoutInSeconds: Int): AuthenticityToken = {
    val oldToken = tokenMap.get(userId)
    if(oldToken.isDefined) tokenMap2.remove(oldToken.get)
    tokenMap.remove(userId)

    val newToken = "%064d".format(random.nextInt(1000000))
    tokenMap.put(userId, newToken)
    tokenMap2.put(newToken, userId)
    newToken
  }

  override def remove(token: AuthenticityToken): Unit = {
    val id = tokenMap2.get(token)
    if(id.isEmpty) return

    tokenMap.remove(id.get)
    tokenMap2.remove(token)
  }

  override def get(token: AuthenticityToken): Option[Id] = {
    tokenMap2.get(token)
  }

  override def prolongTimeout(token: AuthenticityToken, timeoutInSeconds: Int): Unit = {
    //???timeout????????
  }
} 
开发者ID:tm-sukehiro,项目名称:play2-sandbox,代码行数:49,代码来源:SessionHandler.scala


示例17: OAuth2Controller

//设置package包名称以及导入依赖的类
package controllers

import java.security.SecureRandom
import javax.inject.{Inject, Singleton}

import auth.{DefaultEnv, OAuthDataHandlerImpl}
import com.mohiva.play.silhouette.api.Silhouette
import models.daos.AccessTokenDAO
import play.api.Configuration
import play.api.libs.json.Json
import play.api.mvc.{Controller, Request, Result}

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.ExecutionContext.Implicits._
import scalaoauth2.provider.{AuthorizationHandler, OAuth2Provider, OAuthGrantType, TokenEndpoint}


@Singleton
class OAuth2Controller @Inject() (
    override val tokenEndpoint: TokenEndpoint,
    config: Configuration,
    secureRandom: SecureRandom,
    accessTokenDAO: AccessTokenDAO,
    silhouette: Silhouette[DefaultEnv]) extends Controller with OAuth2Provider {

    def accessToken = silhouette.UserAwareAction.async { implicit request =>
        request.identity match {
            case Some(user) =>
                issueAccessToken(new OAuthDataHandlerImpl(config, secureRandom, accessTokenDAO, Some(user)))
            case _ => Future.successful(Redirect(routes.AuthController.getSignIn()))
        }
    }

    override def issueAccessToken[A, U](handler: AuthorizationHandler[U])(implicit request: Request[A], ctx: ExecutionContext): Future[Result] = {
        tokenEndpoint.handleRequest(request, handler).map {
            case Left(e) => new Status(e.statusCode)(responseOAuthErrorJson(e)).withHeaders(responseOAuthErrorHeader(e))
            case Right(r) =>
                r.authInfo.redirectUri match {
                    case Some(uri) if request.grantType == OAuthGrantType.IMPLICIT =>
                        Redirect(s"$uri#token=${r.accessToken}")
                    case _ =>
                        Ok(Json.toJson(responseAccessToken(r))).withHeaders("Cache-Control" -> "no-store", "Pragma" -> "no-cache")
                }
        }
    }

} 
开发者ID:coompany,项目名称:ideas,代码行数:48,代码来源:OAuth2Controller.scala


示例18: RandomTest

//设置package包名称以及导入依赖的类
package xyztr

import java.security.SecureRandom
import java.util.Random

import org.jboss.netty.util.CharsetUtil
import org.scalatest.{FlatSpec, Matchers}

class RandomTest extends FlatSpec with Matchers {
  "SecureRandom" should "generate completely random numbers by default" in {
    val rg = new SecureRandom()
    val randomLong = rg.nextLong
    randomLong should not be 606409227870597303L
  }

  "SecureRandom" should "generate completely random numbers even if the same seed is used" in {
    val seed = new String("seed").getBytes(CharsetUtil.UTF_8)
    val rg1 = new SecureRandom()
    val rg2 = new SecureRandom()
    rg1.setSeed(seed)
    rg2.setSeed(seed)

    val b1 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
    val b2 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
    rg1.nextBytes(b1)
    rg2.nextBytes(b2)
    b1 should not be b2
  }

  "Random" should "generate completely non-random numbers if the same seed is used" in {
    val seed = 77
    val rg1 = new Random(seed)
    val rg2 = new Random(seed)

    val b1 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
    val b2 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
    rg1.nextBytes(b1)
    rg2.nextBytes(b2)
    b1 should be(b2)
  }
} 
开发者ID:matshenricson,项目名称:xyztr,代码行数:42,代码来源:RandomTest.scala


示例19: createHTTPSContextWithPassword

//设置package包名称以及导入依赖的类
package org.nephtys.keepaseat

import java.io.InputStream
import java.security.{KeyStore, SecureRandom}
import javax.crypto.SecretKey
import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory}

import akka.http.scaladsl.server.Route
import org.nephtys.cmac.MacSource
import org.nephtys.keepaseat.internal.{GetRetreiveRoute, LinkJWTRoute, PostChangesRoute, StaticRoute}
import org.nephtys.keepaseat.internal.configs.{AnalogInterfaceConfig, PasswordConfig, ServerConfig}
import org.nephtys.keepaseat.internal.validators.{SuperuserPostValidator, UserPostValidator}
import akka.actor.{ActorRef, ActorSystem}
import akka.http.scaladsl.{ConnectionContext, HttpsConnectionContext}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller
import akka.stream.ActorMaterializer
import org.nephtys.keepaseat.filter.XSSCleaner


  def createHTTPSContextWithPassword(password: Array[Char], pkcs12file: InputStream, keystoreInstance: String =
  "PKCS12",
                         keymanagerInstance: String = "SunX509", trustmanagerInstance: String = "SunX509")
                        (implicit system: ActorSystem, mat: ActorMaterializer):
  HttpsConnectionContext = {
    implicit val dispatcher = system.dispatcher

    val ks: KeyStore = KeyStore.getInstance(keystoreInstance)

    require(pkcs12file != null, "Keystore required!")
    require(password != null, "Password required!")

    ks.load(pkcs12file, password)

    val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance(keymanagerInstance)
    keyManagerFactory.init(ks, password)

    val tmf: TrustManagerFactory = TrustManagerFactory.getInstance(trustmanagerInstance)
    tmf.init(ks)

    val sslContext: SSLContext = SSLContext.getInstance("TLS")

    sslContext.init(keyManagerFactory.getKeyManagers, tmf.getTrustManagers, new SecureRandom)

    ConnectionContext.https(sslContext)
  }


  def createHTTPSContext(pkcs12file: InputStream, keystoreInstance: String = "PKCS12",
                         keymanagerInstance: String = "SunX509", trustmanagerInstance: String = "SunX509")
                        (implicit system: ActorSystem, mat: ActorMaterializer, serverConfig: ServerConfig):
  HttpsConnectionContext = {
    require(serverConfig.httpsPassword.isDefined,
      """createHTTPSContext, but https password was none. If the password " +
      "is empty, use Some("") instead.""")
    createHTTPSContextWithPassword(serverConfig.httpsPassword.get.toCharArray, pkcs12file,
      keystoreInstance, keymanagerInstance,
      trustmanagerInstance)
  }
} 
开发者ID:n3phtys,项目名称:keep-a-seat,代码行数:62,代码来源:KeepASeat.scala


示例20: originHostWithProtocol

//设置package包名称以及导入依赖的类
package org.nephtys.keepaseat.internal.linkkeys

import java.security.SecureRandom

import org.nephtys.cmac.{HmacValue, MacSource}
import org.nephtys.keepaseat.internal.eventdata.{Event, EventElementBlock}

import scala.util.Random


sealed trait ReservationRequest {

  def originHostWithProtocol : String
  def elements : Seq[EventElementBlock]
  // values
  def name : String
  def email : String
  def telephone : String
  def commentary : String

  def randomNumber : Long //to salt the hmacs

  def toNewEventWithoutID : Event

  def toURLencodedJWT()(implicit macSource : MacSource) = ReservationRequest.makeUrlencodedJWT(this)
}

case class SimpleReservation(
                              originHostWithProtocol : String,
                              elements : Seq[EventElementBlock],
                             name : String,
                             email : String,
                             telephone : String,
                             commentary : String, randomNumber : Long) extends ReservationRequest{
  def toNewEventWithoutID : Event = Event(-1l, elements, name, email, telephone, commentary, confirmedBySupseruser = false)
}


object ReservationRequest {
  import org.nephtys.cmac.HmacHelper._
  import upickle.default._
  def makeUrlencodedJWT(request : ReservationRequest)(implicit macSource : MacSource) : String = {
      request.toHMAC().toURLEncodedString().encodedString
  }
  def fromJWTString(urlencodedjwt : String)(implicit macSource : MacSource) : HmacValue[ReservationRequest] = {
    urlencodedjwt.fromURLEncodedString.toHMAC[ReservationRequest]()
  }

  def randomNumber : Long = new SecureRandom().nextLong()

} 
开发者ID:n3phtys,项目名称:keep-a-seat,代码行数:52,代码来源:ReservationRequest.scala



注:本文中的java.security.SecureRandom类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Node类代码示例发布时间:2022-05-23
下一篇:
Scala TimeoutException类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap