当前位置: 首页>>代码示例>>Scala>>正文


Scala SecureRandom类代码示例

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


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


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