本文整理汇总了Scala中javax.crypto.Mac类的典型用法代码示例。如果您正苦于以下问题:Scala Mac类的具体用法?Scala Mac怎么用?Scala Mac使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Mac类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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)
}
示例2: 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)
}
}
}
示例3: Player
//设置package包名称以及导入依赖的类
package proton.game
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Clock, LocalDateTime}
import java.util.{Base64, UUID}
import javax.crypto.spec.SecretKeySpec
import javax.crypto.{KeyGenerator, Mac}
@SerialVersionUID(1L)
class Player(val id: UUID, val name: String, val secret: String) extends Serializable {
override def hashCode = id.hashCode()
override def equals(other: Any) = other match {
case that: Player => this.id == that.id
case _ => false
}
override def toString = s"$name ($id)"
def identity = PlayerIdentity(id, name)
def isAuthorized(time: LocalDateTime, signature: String): Boolean = {
val seconds = ChronoUnit.SECONDS.between(time, LocalDateTime.now(Clock.systemUTC()))
if (seconds < -300 || seconds > 300) {
false
} else {
val secretKeySpec = new SecretKeySpec(secret.getBytes, "HmacSHA256")
val mac = Mac.getInstance("HmacSHA256")
mac.init(secretKeySpec)
val message = id.toString.toLowerCase + "|" + time.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
val hmac = mac.doFinal(message.getBytes("UTF-8"))
val encoded = Base64.getEncoder.encodeToString(hmac)
encoded.equalsIgnoreCase(signature)
}
}
}
object Player {
def apply(name: String) = new Player(UUID.randomUUID(), name, generateKey)
def apply(id: UUID, name: String) = new Player(id, name, generateKey)
private def generateKey: String = {
val keyGenerator: KeyGenerator = KeyGenerator.getInstance("HmacSHA256")
Base64.getEncoder.encodeToString(keyGenerator.generateKey().getEncoded)
}
def apply(id: UUID, name: String, secret: String) = new Player(id, name, secret)
def apply(identity: PlayerIdentity) = new Player(identity.id, identity.name, generateKey)
def apply(identity: PlayerIdentity, secret: String) = new Player(identity.id, identity.name, secret)
}
case class PlayerIdentity(id: UUID, name: String)
示例4: SignRequest
//设置package包名称以及导入依赖的类
package com.wegtam.amws.common
import java.nio.charset.StandardCharsets
import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import com.wegtam.amws.common.Request.{ ParameterName, RequestParameters }
import scala.util.Try
object SignRequest {
// The field name for the query parameter that will hold the signature.
final val SignatureRequestFieldName: ParameterName = "Signature"
// These fields are needed for signed requests and must be added accordingly.
final val SignatureRequestFields: RequestParameters = Map(
"SignatureMethod" -> "HmacSHA256",
"SignatureVersion" -> "2"
)
def sign(key: Array[Byte], data: Array[Byte]): Try[String] = Try {
val algo = "HmacSHA256"
val base = Base64.getEncoder
val hmac = Mac.getInstance(algo)
val skey = new SecretKeySpec(key, algo)
hmac.init(skey)
val sig = hmac.doFinal(data)
new String(base.encode(sig), StandardCharsets.UTF_8)
}
}
示例5: Crypto
//设置package包名称以及导入依赖的类
package com.softwaremill.session
import java.security.MessageDigest
import java.util
import javax.crypto.{Cipher, Mac}
import javax.crypto.spec.SecretKeySpec
import javax.xml.bind.DatatypeConverter
import com.softwaremill.session.SessionUtil._
object Crypto {
def sign_HmacSHA1_hex(message: String, secret: String): String = {
val key = secret.getBytes("UTF-8")
val mac = Mac.getInstance("HmacSHA1")
mac.init(new SecretKeySpec(key, "HmacSHA1"))
toHexString(mac.doFinal(message.getBytes("utf-8")))
}
def sign_HmacSHA256_base64(message: String, secret: String): String = {
val key = secret.getBytes("UTF-8")
val mac = Mac.getInstance("HmacSHA256")
mac.init(new SecretKeySpec(key, "HmacSHA256"))
DatatypeConverter.printBase64Binary(mac.doFinal(message.getBytes("utf-8")))
}
def encrypt_AES(value: String, secret: String): String = {
val raw = util.Arrays.copyOf(secret.getBytes("utf-8"), 16)
val skeySpec = new SecretKeySpec(raw, "AES")
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
toHexString(cipher.doFinal(value.getBytes("utf-8")))
}
def decrypt_AES(value: String, secret: String): String = {
val raw = util.Arrays.copyOf(secret.getBytes("utf-8"), 16)
val skeySpec = new SecretKeySpec(raw, "AES")
val cipher = Cipher.getInstance("AES")
cipher.init(Cipher.DECRYPT_MODE, skeySpec)
new String(cipher.doFinal(hexStringToByte(value)))
}
def hash_SHA256(value: String): String = {
val digest = MessageDigest.getInstance("SHA-256")
toHexString(digest.digest(value.getBytes("UTF-8")))
}
}
示例6: AwsHmacSha256
//设置package包名称以及导入依赖的类
package io.github.daviddenton.finagle.aws
import java.nio.charset.StandardCharsets
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import aws.Hex
object AwsHmacSha256 {
def hash(payload: String): String = hash(payload.getBytes(StandardCharsets.UTF_8))
def hash(payload: Array[Byte]): String = Digest.sha256(payload).toHex
def hmacSHA256(key: Array[Byte], data: String): Array[Byte] = {
val algorithm = "HmacSHA256"
val mac = Mac.getInstance(algorithm)
mac.init(new SecretKeySpec(key, algorithm))
mac.doFinal(data.getBytes(StandardCharsets.UTF_8))
}
def hex(data: Array[Byte]): String = Hex.encode(data)
}
示例7: EncryptionUtils
//设置package包名称以及导入依赖的类
package io.policarp.scala.credstash
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Hex
object EncryptionUtils {
implicit class ToHexDigest(bytes: Array[Byte]) {
def toHexDigest = new String(Hex.encodeHex(bytes))
}
implicit class FromHexDigest(chars: Array[Char]) {
def fromHexDigest = Hex.decodeHex(chars)
}
object HmacSHA256 {
@throws[Exception]
def apply(data: Array[Byte], key: Array[Byte]) = {
val algorithm = "HmacSHA256"
val mac = Mac.getInstance(algorithm)
mac.init(new SecretKeySpec(key, algorithm))
mac.doFinal(data)
}
}
}
示例8: sha1
//设置package包名称以及导入依赖的类
package com.github.jeroenr.tepkin.util
import java.security.MessageDigest
import javax.crypto.spec.{PBEKeySpec, SecretKeySpec}
import javax.crypto.{Mac, SecretKeyFactory}
import com.github.jeroenr.bson.util.Codec
trait Crypto extends Codec {
def sha1(value: String): String = {
val digest = sha1(value.getBytes("UTF-8"))
encodeBase64(digest)
}
def sha1(value: Array[Byte]): Array[Byte] = {
MessageDigest.getInstance("SHA-1").digest(value)
}
def hmac(value: Array[Byte], key: String): Array[Byte] = {
val signingKey = new SecretKeySpec(value, "HmacSHA1")
val mac = Mac.getInstance("HmacSHA1")
mac.init(signingKey)
mac.doFinal(decodeUtf8(key))
}
def keyDerive(password: String, salt: Array[Byte], iterations: Int): Array[Byte] = {
val spec = new PBEKeySpec(password.toCharArray, salt, iterations, 20 * 8 )
val keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
keyFactory.generateSecret(spec).getEncoded
}
def xor(as: Array[Byte], bs: Array[Byte]): Array[Byte] = {
as.zip(bs).map { case (a, b) => (a ^ b).toByte }
}
}
object Crypto extends Crypto
示例9: CredentialScope
//设置package包名称以及导入依赖的类
package com.bluelabs.akkaaws
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import javax.xml.bind.DatatypeConverter
case class CredentialScope(date: LocalDate, awsRegion: String, awsService: String){
val dateFormat = new SimpleDateFormat("yyyy-MM-dd")
lazy val formattedDate: String = date.format(DateTimeFormatter.BASIC_ISO_DATE)
def scopeString = s"$formattedDate/$awsRegion/$awsService/aws4_request"
}
case class SigningKey(credentials: AWSCredentials, scope: CredentialScope, algorithm: String = "HmacSHA256") {
val rawKey = new SecretKeySpec(s"AWS4${credentials.secretAccessKey}".getBytes, algorithm)
def signature(message: Array[Byte]): Array[Byte] = {
signWithKey(key, message)
}
def hexEncodedSignature(message: Array[Byte]): String = {
Utils.encodeHex(signature(message))
}
def credentialString: String = s"${credentials.accessKeyId}/${scope.scopeString}"
lazy val key: SecretKeySpec =
wrapSignature(dateRegionServiceKey, "aws4_request".getBytes)
lazy val dateRegionServiceKey: SecretKeySpec =
wrapSignature(dateRegionKey, scope.awsService.getBytes)
lazy val dateRegionKey: SecretKeySpec =
wrapSignature(dateKey, scope.awsRegion.getBytes)
lazy val dateKey: SecretKeySpec =
wrapSignature(rawKey, scope.formattedDate.getBytes)
private def wrapSignature(signature: SecretKeySpec, message: Array[Byte]): SecretKeySpec = {
new SecretKeySpec(signWithKey(signature, message), algorithm)
}
private def signWithKey(key: SecretKeySpec, message: Array[Byte]): Array[Byte] = {
val mac = Mac.getInstance(algorithm)
mac.init(key)
mac.doFinal(message)
}
}
示例10: JsonWebSignature
//设置package包名称以及导入依赖的类
package authentikat.jwt
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Hex
object JsonWebSignature {
object HexToString{
implicit def converter (bytes: Array[Byte]): String = {
Hex.encodeHexString(bytes)
}
}
def apply(algorithm: String, data: String, key: String): Array[Byte] = {
algorithm match {
case "HS256" => apply(HS256, data, key)
case "HS384" => apply(HS384, data, key)
case "HS512" => apply(HS512, data, key)
case "none" => apply(none, data, key)
case x => throw new UnsupportedOperationException(x + " is an unknown or unimplemented JWT algo key")
}
}
def apply(algorithm: Algorithm, data: String, key: String = null): Array[Byte] = {
algorithm match {
case HS256 => HmacSha("HmacSHA256", data, key)
case HS384 => HmacSha("HmacSHA384", data, key)
case HS512 => HmacSha("HmacSHA512", data, key)
case none => Array.empty[Byte]
case x => throw new UnsupportedOperationException(x + " is an unknown or unimplemented JWT algo key")
}
}
private case object HmacSha {
def apply(algorithm: String, data: String, key: String): Array[Byte] = {
val _key = Option(key).getOrElse(throw new IllegalArgumentException("Missing key for JWT encryption via " + algorithm))
val mac: Mac = Mac.getInstance(algorithm)
val secretKey: SecretKeySpec = new SecretKeySpec(_key.getBytes, algorithm)
mac.init(secretKey)
mac.doFinal(data.getBytes)
}
}
abstract class Algorithm
case object none extends Algorithm
case object HS256 extends Algorithm
case object HS384 extends Algorithm
case object HS512 extends Algorithm
}
示例11: MAC_ALGORITHM
//设置package包名称以及导入依赖的类
package rere.sasl.scram.crypto
import java.security.MessageDigest
import javax.crypto.spec.{PBEKeySpec, SecretKeySpec}
import javax.crypto.{Mac, SecretKeyFactory}
import rere.sasl.util.{BinaryString, UTF8}
import scala.util.control.NonFatal
trait ScramShaAuthMechanism extends ScramAuthMechanism {
def MAC_ALGORITHM: String
def PBKDF2_KEY_LENGTH: Int
def PBKDF2_ALGORITHM: String
def HASH_FUNCTION_NAME: String
def factory: SecretKeyFactory
def log(throwable: Throwable): Unit
final def hi(password: String, salt: BinaryString, iterations: Int): BinaryString = {
try {
val keySpec = new PBEKeySpec(password.toCharArray, salt, iterations, PBKDF2_KEY_LENGTH)
factory.generateSecret(keySpec).getEncoded
} catch {
case NonFatal(ex) =>
log(ex)
throw ex
}
}
final def hmac(key: BinaryString, data: String): BinaryString = {
try {
val mac = Mac.getInstance(MAC_ALGORITHM)
val secretKey = new SecretKeySpec(key, MAC_ALGORITHM)
mac.init(secretKey)
mac.doFinal(UTF8.to(data))
} catch {
case NonFatal(ex) =>
log(ex)
throw ex
}
}
final def h(data: BinaryString): BinaryString = {
try {
MessageDigest.getInstance(HASH_FUNCTION_NAME).digest(data)
} catch {
case NonFatal(ex) =>
log(ex)
throw ex
}
}
}
示例12: AuthInterceptor
//设置package包名称以及导入依赖的类
package app.bitrader.api.network
import java.nio.charset.Charset
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import app.bitrader.activity.Circuitable
import app.bitrader.api.common.AuthData
import okhttp3.Interceptor.Chain
import okhttp3.{Interceptor, Request, Response}
import okio.Buffer
class AuthInterceptor extends Interceptor with Circuitable{
def credentials: Option[AuthData] = appCircuit.zoom(_.selectedAccount).value.context.auth.authData
override def intercept(chain: Chain): Response = {
credentials.map {cc =>
val request: Request = chain.request()
val newRequest = request.newBuilder
val query: String = { // ugly, ugly function
val buffer: Buffer = new okio.Buffer()
request.body().writeTo(buffer)
val postString: String = buffer.readString(Charset.forName("UTF-8"))
postString
}
println(s"post query $query")
// todo put nonce here
// val formEncodingBuilder: FormEncodingBuilder = new FormEncodingBuilder
// formEncodingBuilder.add()
// newRequest.post(formEncodingBuilder)
newRequest.addHeader("Key", cc.apiKey)
newRequest.addHeader("Sign", hmacSHA512(query, cc.apiSecret))
val build: Request = newRequest.build()
chain.proceed(build)
}.getOrElse(
chain.proceed(chain.request())
)
}
def hmacSHA512(value: String, secret: String): String = {
val hmacsha512: String = "HmacSHA512"
val encoding: String = "UTF-8"
val secretKeySpec: SecretKeySpec = new SecretKeySpec(secret.getBytes(encoding), hmacsha512)
val mac: Mac = Mac.getInstance(hmacsha512)
mac.init(secretKeySpec)
val bytes: Array[Byte] = mac.doFinal(value.getBytes(encoding))
bytes.map("%02x" format _).mkString
}
}
示例13: SSOProvider
//设置package包名称以及导入依赖的类
package com.amarjanica.discourse.util
import java.nio.charset.StandardCharsets
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import com.amarjanica.discourse.models.{SSOContext, SSOUserRequest, SSOUserResult, SignatureNotMatchedException}
import javax.xml.bind.DatatypeConverter;
class SSOProvider(ctx: SSOContext) {
def provide(req: SSOUserRequest): SSOUserResult = {
val signedPayload = signPayload(ctx.payload)
if (signedPayload.equalsIgnoreCase(ctx.signature)) {
val oldPayload = new String(DatatypeConverter.parseBase64Binary(ctx.payload))
val newPayload = s"$oldPayload&${req.queryParameters}"
val base64String = DatatypeConverter.printBase64Binary(newPayload.getBytes(StandardCharsets.UTF_8))
SSOUserResult(base64String, signPayload(base64String))
} else {
throw SignatureNotMatchedException(
s"SSO ${ctx.payload}, signature $signedPayload did not match signature ${ctx.signature}!")
}
}
private[this] def calculateRFC2104HMAC(data: String, key: String): String = {
val HMAC_SHA1_ALGORITHM = "HmacSHA256"
val mac = Mac.getInstance(HMAC_SHA1_ALGORITHM)
val signingKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), HMAC_SHA1_ALGORITHM)
mac.init(signingKey)
mac.doFinal(data.getBytes)
bytesToHex(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)))
}
private[this] def signPayload(payload: String): String = calculateRFC2104HMAC(payload, ctx.secret)
private[this] def bytesToHex(bytes: Array[Byte]) = bytes.map("%02X" format _).mkString.toLowerCase
}
示例14: HmacSha256
//设置package包名称以及导入依赖的类
package jkugiya.awstools.signer.v4.hash
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import jkugiya.awstools.signer.v4.SigningException
import scala.util.{ Failure, Success, Try }
private[v4] object HmacSha256 {
def encode(key: Array[Byte], value: String): Array[Byte] = Try {
val algorithm = "HmacSHA256"
val mac = Mac.getInstance(algorithm)
val signingKey = new SecretKeySpec(key, algorithm)
mac.init(signingKey)
mac.doFinal(value.getBytes("UTF-8"))
} match {
case Success(hash) => hash
case Failure(t) => throw new SigningException(t)
}
}
示例15: APIContext
//设置package包名称以及导入依赖的类
package com.fourseasapp.facebookads
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import javax.inject.Inject
import org.slf4j.{LoggerFactory, Logger}
case class APIContext (accessToken: String,
appSecret: String = null,
endpointBase: String = "https://graph.facebook.com",
version: String = "v2.5",
isDebug: Boolean = false,
timeOut: Int = 30) {
def hasAppSecret = appSecret != null
def getAppSecretProof(): String = {
sha256(appSecret, accessToken)
}
def log(s: String): Unit = {
if (isDebug) {
APIContext.logger.debug(s)
}
}
def error(s: String, t: Throwable): Unit = {
APIContext.logger.error(s, t)
}
private def sha256(secret: String, message: String): String = {
val sha256HMAC = Mac.getInstance("HmacSHA256")
val secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256")
sha256HMAC.init(secretKey)
val bytes = sha256HMAC.doFinal(message.getBytes())
toHex(bytes)
}
private def toHex(bytes: Array[Byte]): String = {
val sb = new StringBuilder()
for (b <- bytes) {
sb.append("%1$02x".format(b))
}
sb.toString()
}
}
object APIContext {
val USER_AGENT = "fourseasapp-scala-ads-api-sdk-v2.5"
val logger = LoggerFactory.getLogger(classOf[APIContext])
implicit val apiEC = scala.concurrent.ExecutionContext.global
}