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


Scala MessageDigest类代码示例

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


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

示例1: Message

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

import java.security.MessageDigest

import com.google.appengine.api.datastore.{Key, Entity, KeyFactory, DatastoreServiceFactory}
import com.google.gson.JsonObject

class Message(var title: String, var content: String) {

  def save: String = {
    DatastoreServiceFactory.getDatastoreService.put(toEntity)
    id
  }

  def toEntity: Entity = {
    val entity = new Entity(Message.key(id))
    entity.setProperty("title", title)
    entity.setProperty("content", content)
    entity
  }

  def toJson: JsonObject = {
    val json = new JsonObject
    json.addProperty("title", title)
    json.addProperty("content", content)
    json
  }

  def id : String = new String(MessageDigest.getInstance("MD5").digest((title + content).getBytes))
}

object Message {

  def key(id: String): Key = KeyFactory.createKey("MESSAGES", id)

  def fromEntity(entity: Entity) : Message = {
    val title = entity.getProperty("title").asInstanceOf[String]
    val content = entity.getProperty("content").asInstanceOf[String]
    new Message(title, content)
  }

  def fromJson(json: JsonObject): Message = {
    val title = json.get("title").getAsString
    val content = json.get("content").getAsString
    new Message(title, content)
  }

  def findById(id: String): Message = Message.fromEntity(DatastoreServiceFactory.getDatastoreService.get(Message.key(id)))
} 
开发者ID:erickzanardo,项目名称:spammer,代码行数:50,代码来源:Message.scala

示例2: 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

示例3: HomeController

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

import java.security.MessageDigest
import java.util.Date
import javax.inject._

import actors.MyWebSocketActor
import akka.actor.ActorSystem
import akka.stream.Materializer
import akka.stream.scaladsl.Flow
import play.api._
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc._

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class HomeController @Inject()(implicit system: ActorSystem, materializer: Materializer) extends Controller with ApiSecurity {
  def index = Action.async { implicit request =>
    Future.successful(
      Ok(views.html.index())
    )
  }

  def websocket = WebSocketRequest
}

trait ApiSecurity { this: Controller =>
  private[this] val tokenName = "sessionId"
  private[this] def hash(s: String) = MessageDigest.getInstance("SHA-256").digest(s.getBytes("UTF-8")).map("%02x".format(_)).mkString("")
  implicit class ResultWithToken(result: Result)(implicit request: RequestHeader) {
    def withToken: Result = {
      request.session.get(tokenName) match {
        case Some(sessionId) => result
        case None => result.withSession(tokenName -> hash(new Date().getTime + request.remoteAddress))
      }
    }
  }

  def WebSocketRequest(implicit system: ActorSystem, materializer: Materializer) =
    WebSocket.acceptOrResult[JsValue, JsValue] { request =>
      Future.successful(request.session.get(tokenName) match {
        case None => Left(Forbidden)
        case Some(_) => Right(ActorFlow.actorRef(MyWebSocketActor.props))
      })
  }
} 
开发者ID:kormoglaz,项目名称:scala-akka-arkanoid,代码行数:49,代码来源:HomeController.scala

示例4: Generator

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

import java.security.MessageDigest


object Generator {

  def generateToken(email: String) =
    {
      // The generated token will be :     userEmail#userId#itsRegistrationTimestamp
      val token = email + "#"
      val algorithm: MessageDigest = MessageDigest.getInstance("SHA-256")
      val defaultBytes: Array[Byte] = token.getBytes
      algorithm.reset
      algorithm.update(defaultBytes)
      val messageDigest: Array[Byte] = algorithm.digest
      getHexString(messageDigest)

    }

  def getHexString(messageDigest: Array[Byte]): String = {
    val hexString: StringBuffer = new StringBuffer
    messageDigest foreach { digest =>
      val hex = Integer.toHexString(0xFF & digest)
      if (hex.length == 1) hexString.append('0') else hexString.append(hex)
    }

    hexString.toString
  }

}
object Md5 {

  def hash(s: String): String = {
    val md5 = MessageDigest.getInstance("MD5").digest(s.getBytes)
    asString(md5)
  }

  val hexDigits = "0123456789abcdef".toCharArray

  def asString(bytes: Array[Byte]) = {
    bytes.foldLeft("") { case (agg, b) => agg + hexDigits((b >> 4) & 0xf) + hexDigits(b & 0xf) }
  }

} 
开发者ID:elarib,项目名称:cvManager,代码行数:46,代码来源:Generator.scala

示例5: SecurityUtil

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

import java.security.MessageDigest
import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

object SecurityUtil {
  def getMD5(string: String): Array[Byte] = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"))

  def getHmacSHA256(key: String, content: String): Array[Byte] = {
    val secret = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256")
    val mac = Mac.getInstance("HmacSHA256")
    mac.init(secret)
    mac.doFinal(content.getBytes("UTF-8"))
  }

  def encodeToBase64String(bytes: Array[Byte]): String = Base64.getEncoder.encodeToString(bytes)
} 
开发者ID:yunify,项目名称:qingstor-sdk-scala,代码行数:20,代码来源:SecurityUtil.scala

示例6: Transaction

//设置package包名称以及导入依赖的类
package net.shiroka.tools.ofx

import java.io._
import java.security.MessageDigest
import scala.xml.PrettyPrinter
import org.joda.time.DateTime
import org.joda.time.format._
import Transaction._

case class Transaction(
    dateTime: DateTime,
    `type`: Type,
    description: String,
    amount: BigDecimal,
    balance: BigDecimal
) {
  lazy val date: DateTime = dateBase(dateTime)
  lazy val moveToLastMinuteOfTheDay = copy(dateTime = dateTime.plusDays(1).minusMinutes(1))
  lazy val dateTimeOfx = dateTime.toString(ofxDateFormat)

  def uniquifyTime(previousOpt: Option[DateTime]) = previousOpt match {
    case None => moveToLastMinuteOfTheDay
    case Some(previous) if (date != dateBase(previous)) => moveToLastMinuteOfTheDay
    case Some(previous) => copy(dateTime = previous.minusMinutes(1))
  }

  def writeOfx(sink: PrintStream, ofxKeyPrefix: String = ""): Unit = {
    sink.print(ppXml.format(
      <STMTTRN>
        <TRNTYPE>{ `type`.name }</TRNTYPE>
        <DTPOSTED>{ dateTimeOfx }</DTPOSTED>
        <TRNAMT>{ amount }</TRNAMT>
        <FITID>{ ofxId(ofxKeyPrefix) }</FITID>
        <MEMO>{ description }</MEMO>
      </STMTTRN>
    ))
  }

  def ofxId(prefix: String) = {
    val text = List(prefix, dateTimeOfx, description, `type`.name, amount, balance).mkString(":")
    MessageDigest.getInstance("MD5").digest(text.getBytes).map("%02x".format(_)).mkString
  }
}

object Transaction {
  val ofxDateFormat = DateTimeFormat.forPattern("yyyyMMddHHmmss")
  val ppXml = new PrettyPrinter(120, 2)

  sealed abstract class Type(val name: String)
  case object Debit extends Type("DEBIT")
  case object Deposit extends Type("DEP")
  case object Interest extends Type("INT")
  case object Credit extends Type("CREDIT")

  def dateBase(dt: DateTime) = dt.dayOfMonth.roundFloorCopy
} 
开发者ID:ikuo,项目名称:ofx-tools,代码行数:57,代码来源:Transaction.scala

示例7: AlgoSecretKey

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

import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import jwtyped.{Message, Signature}


case class AlgoSecretKey(algorithm: String, secret: Secret) {
  val secretKeySpec: SecretKeySpec = new SecretKeySpec(secret.bytes, algorithm)
}

object AlgoSecretKey {
  implicit val hmacSHASign = new Sign[AlgoSecretKey] {
    override def sign(algorithm: AlgoSecretKey, message: Message): Signature = {
      val mac: Mac = Mac.getInstance(algorithm.algorithm)
      mac.init(algorithm.secretKeySpec)
      Signature(mac.doFinal(message.getBytes))
    }
  }

  implicit def hmacSHAVerify(implicit hmacSHASign: Sign[AlgoSecretKey]) = new Verify[AlgoSecretKey] {
    override def verify(algorithm: AlgoSecretKey, message: Message, signature: Signature): Boolean = {
      val s = hmacSHASign.sign(algorithm, message)
      MessageDigest.isEqual(s.value, signature.value)
    }
  }
} 
开发者ID:etaty,项目名称:jwtyped,代码行数:30,代码来源:AlgoSecretKey.scala

示例8: encodeHex

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

import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter

import akka.stream.scaladsl.{Flow, Keep, Sink}
import akka.util.ByteString

import scala.concurrent.Future

package object auth {
  def encodeHex(bytes: Array[Byte]): String = DatatypeConverter.printHexBinary(bytes).toLowerCase

  def encodeHex(bytes: ByteString): String = encodeHex(bytes.toArray)

  def digest(algorithm: String = "SHA-256"): Sink[ByteString, Future[ByteString]] =
    Flow[ByteString]
      .fold(MessageDigest.getInstance(algorithm)) {
        case (digest, bytes) =>
          digest.update(bytes.asByteBuffer)
          digest
      }
      .map(d => ByteString(d.digest()))
      .toMat(Sink.head[ByteString])(Keep.right)
} 
开发者ID:akka,项目名称:alpakka,代码行数:26,代码来源:package.scala

示例9: FileHasher

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

import java.io.InputStream
import java.nio.file.{Files, Path}
import java.security.MessageDigest
import kokellab.utils.core._

import kokellab.utils.core.{bytesToHex, hexToBytes}

class FileHasher(algorithm: String = "SHA-256") {

	val emptyHash: String = hash(Array.emptyByteArray)

	def validate(file: Path, hashHex: String): Unit = {
		val actual = hash(file)
		if (actual != hashHex) throw new ValidationFailedException(s"Validation failed: Required $hashHex but got $actual")
	}
	def validate(stream: InputStream, hashHex: String): Unit = {
		val actual = hash(stream)
		if (actual != hashHex) throw new ValidationFailedException(s"Validation failed: Required $hashHex but got $actual")
	}
	def validate(bytes: TraversableOnce[Byte], hashHex: String): Unit = {
		val actual = hash(bytes)
		if (actual != hashHex) throw new ValidationFailedException(s"Validation failed: Required $hashHex but got $actual")
	}

	def hash(file: Path): String = {
		val md = MessageDigest.getInstance(algorithm)
		readFileInChunks(file, md.update)
		bytesToHex(md.digest())
	}

	def hash(stream: InputStream): String = {
		val md = MessageDigest.getInstance(algorithm)
		readStreamInChunks(stream, md.update)
		bytesToHex(md.digest())
	}

	def hash(bytes: TraversableOnce[Byte]): String = {
		val md = MessageDigest.getInstance(algorithm)
		md.update(bytes.toArray)
		bytesToHex(md.digest())
	}

}

class ValidationFailedException(message: String = "The validation failed", cause: Throwable = null) extends Exception(message, cause) 
开发者ID:kokellab,项目名称:kl-common-scala,代码行数:48,代码来源:FileHasher.scala

示例10: encrypt

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

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64
import java.security.MessageDigest
import java.util.Arrays
import controllers.HasConfig

trait HasEncryption { self: HasConfig =>
  
  private val CIPHER = "AES/ECB/PKCS5Padding"
  
  private lazy val keySpec = self.config.getString("recogito.email.key").flatMap { key =>
    if (key.isEmpty) {
      None
    } else {
      val md = MessageDigest.getInstance("SHA-1")
      val keyDigest = md.digest(key.getBytes)
      Some(new SecretKeySpec(Arrays.copyOf(keyDigest, 16), "AES"))
    }
  }
  
  def encrypt(plaintext: String) = keySpec match {
    case Some(spec) => {
      val cipher = Cipher.getInstance(CIPHER)
      cipher.init(Cipher.ENCRYPT_MODE, spec)
      Base64.encodeBase64String(cipher.doFinal(plaintext.getBytes("UTF-8")))
    }
    
    case None => plaintext
  }
  
  def decrypt(encrypted: String) = keySpec match {
    case Some(spec) => {
      val cipher = Cipher.getInstance(CIPHER)
      cipher.init(Cipher.DECRYPT_MODE, spec)
      new String(cipher.doFinal(Base64.decodeBase64(encrypted)))      
    }
    
    case None => encrypted
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:45,代码来源:HasEncryption.scala

示例11: MessagesSpec

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

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._

final class MessagesSpec extends Specification with ScalaCheck { def is = s2"""

  PasswordMessage
    should MD5 encrypt a password with given salt           $pmEncrypt
                                                                            """

  val pmEncrypt = forAll { (user: String, pm: PasswordMessage, salt: Array[Byte]) =>
    val md = MessageDigest.getInstance("MD5")
    md.update((pm.password+ user).getBytes(StandardCharsets.UTF_8))
    val unsaltedHexStr = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("")(_ + _)
    val saltedBytes = unsaltedHexStr.getBytes ++ salt
    md.reset()
    md.update(saltedBytes)
    val passwd = md.digest().map(x => "%02x".format(x.byteValue)).foldLeft("md5")(_ + _)
    passwd must_== PasswordMessage.encryptMD5Passwd(user, pm.password, salt)
  }
  
  lazy val genByte: Gen[Byte] = arbitrary[Byte]
  lazy val genSalt: Gen[Array[Byte]] = Gen.containerOfN[Array, Byte](4, genByte)
  lazy val genPasswordMessage: Gen[PasswordMessage] = for {
    password    <-  arbitrary[String]
  } yield new PasswordMessage(password)
  implicit lazy val implicitPasswordMessage: Arbitrary[PasswordMessage] = 
    Arbitrary(genPasswordMessage)
} 
开发者ID:finagle,项目名称:roc,代码行数:36,代码来源:MessageSpec.scala

示例12: Account

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

import java.security.MessageDigest

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

case class Account(
  id: Long,
  email: String,
  password: String,
  createdAt: DateTime
)

object Account extends SkinnyCRUDMapper[Account] {

  override def defaultAlias = createAlias("a")
  val ownerAlias = createAlias("owner")

  override def extract(rs: WrappedResultSet, a: ResultName[Account]) = new Account(
    id = rs.get(a.id),
    email = rs.get(a.email),
    password = rs.get(a.password),
    createdAt = rs.get(a.createdAt)
  )

  private def digestString(s: String): String = {
    val md = MessageDigest.getInstance("SHA-1")
    md.update(s.getBytes)
    md.digest.foldLeft("") { (s, b) =>
      s + "%02x".format(if (b < 0) b + 256 else b)
    }
  }

  def authenticate(email: String, password: String)(implicit s: DBSession): Option[Account] = {
    val hashedPassword = digestString(password)
    val a = Account.defaultAlias
    Account.where(sqls.eq(a.email, email).and.eq(a.password, hashedPassword)).apply().headOption
  }
} 
开发者ID:trumanw,项目名称:cloud-oauth-play,代码行数:42,代码来源:Account.scala

示例13: TrackingController

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

import java.security.MessageDigest

import play.api._
import play.api.libs.Codecs
import play.api.mvc._
// Java8 lib
import java.util.Base64

class TrackingController extends Controller {

  val COOKIE_KEY = "Z_SYSTEM_3RD_PARTY_COOKIE_ID_SCALA"
  val COOKIE_MAX_AFTER_AGE = Some(31622400 + 31622400)

  //ref https://css-tricks.com/snippets/html/base64-encode-of-1x1px-transparent-gif/
  val onePixelGifBase64 = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
  val onePixelGifBytes = Base64.getDecoder().decode(onePixelGifBase64)

  def pixelTracking = Action {request =>
    val cookies = request.cookies
    val cookieValue = cookies.get(COOKIE_KEY).map { cookie =>
      Logger.debug(s"Cookie Exist! ${cookie.value}")
      cookie.value
    }.getOrElse {
      val newValue = uniqueIdGenerator()
      Logger.debug("Cookie Generate! $newValue")
      newValue
    }
    Ok(onePixelGifBytes).withCookies(Cookie(COOKIE_KEY, cookieValue, COOKIE_MAX_AFTER_AGE)).as("image/gif")
  }

  val uniqueIdGenerator = () => {
    val milliTime = System.currentTimeMillis()
    val nanoTime = System.nanoTime()
    val baseString = s"$milliTime $nanoTime"
    Logger.debug(baseString)

    val md = MessageDigest.getInstance("SHA-256")
    md.update(baseString.getBytes())

    val id = Codecs.toHexString(md.digest())
    Logger.debug(id)
    id
  }
} 
开发者ID:uryyyyyyy,项目名称:adReferenceImplementation,代码行数:47,代码来源:TrackingController.scala

示例14: ImmutableByteBuffer

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

import java.nio.ByteBuffer
import java.security.MessageDigest

class ImmutableByteBuffer private (private val buffer: ByteBuffer) {
  def toArray: Array[Byte] = buffer.array()
  def toByteBuffer: ByteBuffer = buffer.duplicate()
  def length: Int = buffer.remaining
  override def equals(o: Any): Boolean = o match {
    case other: ImmutableByteBuffer => buffer == other.buffer
    case other: ByteBuffer          => buffer == other
    case other: Array[Byte]         => MessageDigest.isEqual(buffer.array(), other)
  }
  override def toString:String = buffer.toString
}
object ImmutableByteBuffer {
  def apply(buffer: ByteBuffer): ImmutableByteBuffer = new ImmutableByteBuffer(buffer.slice())
  def apply(buffer: Array[Byte]): ImmutableByteBuffer = new ImmutableByteBuffer(ByteBuffer.wrap(buffer))
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:21,代码来源:ImmutableByteBuffer.scala

示例15: Checksum

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

import scala.annotation.tailrec
import java.security.MessageDigest
import java.util.Arrays
import org.apache.commons.codec.binary.Hex
import java.nio.ByteBuffer

sealed case class Checksum(sum: Array[Byte], algorithm: Algorithm) {
  def check(other: Array[Byte]): Boolean = {
    check(other.length, other)
  }
  def check(length: Int, other: Array[Byte]*): Boolean = {
      @tailrec
      def rec(length: Int, other: Seq[Array[Byte]], index: Int, digest: MessageDigest): Array[Byte] = {
        if (other.length - 1 == index) {
          digest.update(other(index), 0, length)
          digest.digest
        } else {
          digest.update(other(index))
          rec(length, other, index + 1, digest)
        }
      }
    val digester = MessageDigest.getInstance(algorithm.toString)
    MessageDigest.isEqual(sum, rec(length, other, 0, digester))
  }
  def compare(other: Array[Byte]): Boolean = MessageDigest.isEqual(sum, other)
  override def toString: String = Hex.encodeHexString(sum)
  override def hashCode: Int = Arrays.hashCode(sum)
  override def equals(o: Any): Boolean = o match {
    case Checksum(otherHash, Sha1) => MessageDigest.isEqual(otherHash, sum)
    case _                         => false
  }
}
object Checksum {
  def parse(raw: ByteBuffer, algorithm: Algorithm): Checksum = {
    val checksum = Array.ofDim[Byte](algorithm.bytes)
    for (n <- 0 until algorithm.bytes) {
      checksum(n) = raw.get
    }
    Checksum(checksum, algorithm)
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:44,代码来源:Checksum.scala


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