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

Scala Mac类代码示例

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

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



在下文中一共展示了Mac类的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
} 
开发者ID:yunify,项目名称:qingstor-sdk-scala,代码行数:20,代码来源:SecurityUtil.scala


示例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)
    }
  }
} 
开发者ID:etaty,项目名称:jwtyped,代码行数:30,代码来源:AlgoSecretKey.scala


示例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) 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:61,代码来源:Player.scala


示例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)
  }

} 
开发者ID:wegtam,项目名称:amws-scala,代码行数:33,代码来源:SignRequest.scala


示例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")))
  }
} 
开发者ID:adamw,项目名称:testpr,代码行数:47,代码来源:Crypto.scala


示例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)
} 
开发者ID:daviddenton,项目名称:finagle-aws,代码行数:23,代码来源:AwsHmacSha256.scala


示例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)
    }
  }

} 
开发者ID:kdrakon,项目名称:scala-credstash,代码行数:30,代码来源:EncryptionUtils.scala


示例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 
开发者ID:dgouyette,项目名称:tepkin,代码行数:39,代码来源:Crypto.scala


示例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)
  }
} 
开发者ID:bluelabsio,项目名称:s3-stream,代码行数:53,代码来源:SigningKey.scala


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

} 
开发者ID:astrofed,项目名称:akka-slick-auth-token-microservices,代码行数:60,代码来源:JsonWebSignature.scala


示例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
    }
  }
} 
开发者ID:pbaun,项目名称:rere,代码行数:54,代码来源:ScramShaAuthMechanism.scala


示例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
  }

} 
开发者ID:aafa,项目名称:bitrader,代码行数:59,代码来源:AuthInterceptor.scala


示例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
} 
开发者ID:amarjanica,项目名称:discourse-scala-client,代码行数:38,代码来源:SSOProvider.scala


示例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)
  }
} 
开发者ID:jkugiya,项目名称:aws-v4-signer-scala,代码行数:23,代码来源:HmacSha256.scala


示例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
} 
开发者ID:hailg,项目名称:facebook-scala-ads-sdk,代码行数:58,代码来源:APIContext.scala


示例16: PoloniexAuth

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

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import org.apache.commons.codec.binary.Hex
import play.api.libs.ws.WSRequest


class PoloniexAuth(apiKey: String, secretKey: String) {

  protected def generateSignature(params: String): String = {
    val keyspec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA512")
    val shaMac = Mac.getInstance("HmacSHA512")
    shaMac.init(keyspec)

    val macData = shaMac.doFinal(params.getBytes())
    Hex.encodeHexString(macData)
  }

  def setAuthenticationHeaders(request: WSRequest,
                               params: String = ""): WSRequest = {

    val signature = generateSignature(params)

    request.withHeaders(
      "Key" -> apiKey,
      "Sign" -> signature)
  }

  def setNonAuthenticationHeaders(request: WSRequest) = {
    val gdaxRequest = request.withHeaders(
      "Accept" -> "application/json")
  }
} 
开发者ID:asciiu,项目名称:polo,代码行数:36,代码来源:PoloniexAuth.scala


示例17: PrivateKey

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

import javax.crypto.{ Cipher, Mac }
import javax.crypto.spec.{ IvParameterSpec, SecretKeySpec }
import org.apache.commons.codec.binary.Hex

case class PrivateKey(key: Array[Byte])

case class CryptoBits(key: PrivateKey) {

  def sign(message: String): String = {
    val mac = Mac.getInstance("HmacSHA1")
    mac.init(new SecretKeySpec(key.key, "HmacSHA1"))
    Hex.encodeHexString(mac.doFinal(message.getBytes("utf-8")))
  }

  def signToken(token: String, nonce: String): String = {
    val joined = nonce + "-" + token
    sign(joined) + "-" + joined
  }

  def validateSignedToken(token: String): Option[String] = {
    token.split("-", 3) match {
      case Array(signature, nonce, raw) => {
        val signed = sign(nonce + "-" + raw)
        if(constantTimeEquals(signature, signed)) Some(raw) else None
      }
      case _ => None
    }
  }

  def constantTimeEquals(a: String, b: String): Boolean = {
    var equal = 0
    for (i <- 0 until (a.length min b.length)) {
      equal |= a(i) ^ b(i)
    }
    if (a.length != b.length) {
      false
    } else {
      equal == 0
    }
  }
} 
开发者ID:reactormonk,项目名称:cryptobits,代码行数:44,代码来源:cryptobits.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala MediaTypes类代码示例发布时间:2022-05-23
下一篇:
Scala IMqttDeliveryToken类代码示例发布时间: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