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

Scala SecretKeySpec类代码示例

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

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



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

示例1: EncryptionUtility

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

import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.{IvParameterSpec, SecretKeySpec}

object EncryptionUtility {
  private val Algorithm = "AES/CBC/PKCS5Padding"
  private val Key = new SecretKeySpec(Base64.getDecoder.decode("DxVnlUlQSu3E5acRu7HPwg=="), "AES")
  private val IvSpec = new IvParameterSpec(new Array[Byte](16))

  val AdminKey = "Dx$V!nl%Ul^QS&u3*[email protected]=="

  def encrypt(text: String): String = {
    val cipher = Cipher.getInstance(Algorithm)
    cipher.init(Cipher.ENCRYPT_MODE, Key, IvSpec)

    new String(Base64.getEncoder.encode(cipher.doFinal(text.getBytes("utf-8"))), "utf-8")
  }

  def decrypt(text: String): String = {
    val cipher = Cipher.getInstance(Algorithm)
    cipher.init(Cipher.DECRYPT_MODE, Key, IvSpec)

    new String(cipher.doFinal(Base64.getDecoder.decode(text.getBytes("utf-8"))), "utf-8")
  }
} 
开发者ID:knoldus,项目名称:knolx-portal,代码行数:28,代码来源:EncryptionUtility.scala


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


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


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


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


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


示例7: update

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

import javax.crypto.spec.SecretKeySpec
import javax.crypto.Cipher
import java.nio.ByteBuffer
import spooky.util.ByteString
import akka.util.FakeBStrings

sealed trait WriteCipher {
  def update(bs: Array[Byte]): Array[Byte]
  def update(bb: ByteBuffer): ByteString
  def update(bb: ByteString): ByteString
  def updateToBytes(bb: ByteBuffer): Array[Byte]
}

class RC4WriteCipher(writeKey: SecretKeySpec) extends RC4Cipher(writeKey, true) with WriteCipher

object WritePlain extends WriteCipher {
  def update(bb: ByteBuffer): ByteString = FakeBStrings(bb.duplicate)

  def update(bs: Array[Byte]): Array[Byte] = bs

  def update(bb: ByteString): ByteString = bb

  def updateToBytes(bb: ByteBuffer): Array[Byte] = bb.array
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:27,代码来源:WriteCipher.scala


示例8: RC4Cipher

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

import javax.crypto.spec.SecretKeySpec
import java.nio.ByteBuffer
import org.bouncycastle.crypto.engines.RC4Engine
import org.bouncycastle.crypto.params.KeyParameter
import spooky.util.ByteString
import akka.util.FakeBStrings

private[cipher] abstract class RC4Cipher(key: SecretKeySpec, forEncryption: Boolean) {
  private val rc4Engine = new RC4Engine
  val params = new KeyParameter(key.getEncoded)
  rc4Engine.init(forEncryption, params)

  for (n <- 0 until 1024) {
    rc4Engine.returnByte(0)
  }

  def ignore(bb: ByteBuffer, length: Int): Unit = {
    for (n <- 0 until length) {
      rc4Engine.returnByte(bb.get)
    }
  }

  def update(bs: Array[Byte]): Array[Byte] = {
    if (bs.length > 0) {
      val result = Array.ofDim[Byte](bs.length)
      rc4Engine.processBytes(bs, 0, bs.length, result, 0)
      result
    } else Array.ofDim[Byte](0)
  }
  def update(bb: ByteBuffer): ByteString = {
    val result = Array.ofDim[Byte](bb.remaining)
    for (i <- 0 until result.length) {
      result(i) = rc4Engine.returnByte(bb.get)
    }
    FakeBStrings(result)
  }

  def update(bb: ByteString): ByteString = {
    FakeBStrings(update(bb.toArray))
  }

  def updateToBytes(bb: ByteBuffer): Array[Byte] = {
    val result = Array.ofDim[Byte](bb.remaining)
    for (i <- 0 until result.length) {
      result(i) = rc4Engine.returnByte(bb.get)
    }
    result
  }

  def updateBB(bs: ByteString): ByteBuffer = {
    val result = ByteBuffer.allocate(bs.length)
    for (i <- 0 until result.limit) {
      result.put(rc4Engine.returnByte(bs(i)))
    }
    result
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:60,代码来源:RC4Cipher.scala


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


示例10: Encryptor

//设置package包名称以及导入依赖的类
package eu.shiftforward.apso.encryption

import java.io.InputStream
import java.security.{ Key, MessageDigest }
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

import org.apache.commons.codec.binary.Base64

import eu.shiftforward.apso.Logging


object Encryptor extends EncryptionUtils with Logging {

  private def loadEncryptionCipher(transformation: String, key: Key): Option[Cipher] = handle(
    {
      log.debug(s"Building Encryptor using Transformation '$transformation' and Key Algorithm '${key.getAlgorithm}'")
      val cipher = Cipher.getInstance(transformation, provider)
      cipher.init(Cipher.ENCRYPT_MODE, key)
      cipher
    },
    {
      ex: Throwable =>
        log.warn(s"Cipher Transformation: $transformation")
        log.warn("Cipher Key: " + key)
        log.warn(s"Impossible to create Encryption Cipher!", ex)
    })

  def apply(transformation: String, secretKeySpec: SecretKeySpec): Option[Encryptor] =
    loadEncryptionCipher(transformation, secretKeySpec).map(new Encryptor(_))

  def apply(transformation: String, key: Array[Byte]): Option[Encryptor] =
    apply(transformation, new SecretKeySpec(key, transformation))

  def apply(transformation: String, key: String): Option[Encryptor] = {
    val md = MessageDigest.getInstance("SHA-256")

    apply(transformation, new SecretKeySpec(md.digest(key.getBytes("UTF-8")), transformation))
  }

  def apply(
    transformation: String,
    key: InputStream,
    keyStorePassword: String,
    keyAlias: String,
    keyPassword: String): Option[Encryptor] =
    for {
      keyStore <- loadKeyStore(key, keyStorePassword)
      key <- getKey(keyStore, keyAlias, keyPassword)
      cipher <- loadEncryptionCipher(transformation, key)
    } yield new Encryptor(cipher)
} 
开发者ID:ShiftForward,项目名称:apso,代码行数:53,代码来源:Encryptor.scala


示例11: Decryptor

//设置package包名称以及导入依赖的类
package eu.shiftforward.apso.encryption

import java.io.InputStream
import java.security.{ Key, MessageDigest }
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

import org.apache.commons.codec.binary.Base64

import eu.shiftforward.apso.Logging


object Decryptor extends EncryptionUtils with Logging {

  private def loadDecryptionCipher(transformation: String, key: Key): Option[Cipher] = handle(
    {
      log.debug(s"Building Decryptor using Transformation '$transformation' and Key Algorithm '${key.getAlgorithm}'")
      val cipher = Cipher.getInstance(transformation, provider)
      cipher.init(Cipher.DECRYPT_MODE, key)
      cipher
    },
    {
      ex: Throwable =>
        log.warn(s"Cipher Transformation: $transformation")
        log.warn("Cipher Key: " + key)
        log.warn(s"Impossible to create Decryption Cipher!", ex)
    })

  def apply(transformation: String, key: Array[Byte]): Option[Decryptor] =
    loadDecryptionCipher(transformation, new SecretKeySpec(key, transformation)).map(new Decryptor(_))

  def apply(transformation: String, key: String): Option[Decryptor] = {
    val md = MessageDigest.getInstance("SHA-256")

    loadDecryptionCipher(
      transformation,
      new SecretKeySpec(md.digest(key.getBytes("UTF-8")), transformation)).map(new Decryptor(_))
  }

  def apply(
    transformation: String,
    key: InputStream,
    keyStorePassword: String,
    keyAlias: String,
    keyPassword: String): Option[Decryptor] =
    for {
      keyStore <- loadKeyStore(key, keyStorePassword)
      key <- getKey(keyStore, keyAlias, keyPassword)
      cipher <- loadDecryptionCipher(transformation, key)
    } yield new Decryptor(cipher)
} 
开发者ID:ShiftForward,项目名称:apso,代码行数:52,代码来源:Decryptor.scala


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


示例13: CryptoOperations

//设置package包名称以及导入依赖的类
package io.clouderite.commons.scala.berries.crypto

import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.{IvParameterSpec, SecretKeySpec}

class CryptoOperations(text: String) {
  private val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")

  def encrypt(key: String, iv: String): String = {
    cipher.init(Cipher.ENCRYPT_MODE, keySpec(key), paramSpec(iv))
    Base64.getEncoder.encodeToString(cipher.doFinal(text.getBytes()))
  }

  def decrypt(key: String, iv: String): String = {
    cipher.init(Cipher.DECRYPT_MODE, keySpec(key), paramSpec(iv))
    new String(cipher.doFinal(Base64.getDecoder.decode(text)))
  }

  def keySpec(key: String) = new SecretKeySpec(key.getBytes(), "AES")
  def paramSpec(iv: String) = new IvParameterSpec(iv.getBytes())
}

object CryptoOperations {
  implicit def toCryptoOperations(text: String): CryptoOperations = new CryptoOperations(text)
} 
开发者ID:clouderite,项目名称:scala-berries,代码行数:27,代码来源:CryptoOperations.scala


示例14: BubbleHandle

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

import java.security.{PrivateKey, PublicKey}
import java.util.Date
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec

import xyztr.TierionClient.SaveBubbleRecordResponse


case class BubbleHandle(ipfsHash: String, encodedEncryptedEncryptionKey: Array[Byte], created: Long, blockchainHashId: Option[String]) extends Ordered[BubbleHandle] {
  def decryptSecretKey(privateKey: PrivateKey): SecretKey = new SecretKeySpec(Crypto.decryptWithPrivateKey(encodedEncryptedEncryptionKey, privateKey), "AES")

  def compare(that: BubbleHandle) = {
    val milliDiff = that.created - this.created
    if (milliDiff < 0) -1
    else if (milliDiff > 0) +1
    else 0
  }
}

object BubbleHandle {
  def apply(ipfsHash: String, secretKey: SecretKey, publicKey: PublicKey, response: Option[SaveBubbleRecordResponse] = None): BubbleHandle = response.isDefined match {
    case false => BubbleHandle(ipfsHash, Crypto.encryptWithPublicKey(secretKey.getEncoded, publicKey), new Date().getTime, None)
    case true  => BubbleHandle(ipfsHash, Crypto.encryptWithPublicKey(secretKey.getEncoded, publicKey), response.get.timestamp, Some(response.get.id))
  }
} 
开发者ID:matshenricson,项目名称:xyztr,代码行数:28,代码来源:BubbleHandle.scala


示例15: decrypt

//设置package包名称以及导入依赖的类
package io.policarp.scala.credstash

import javax.crypto.Cipher
import javax.crypto.spec.{ IvParameterSpec, SecretKeySpec }

trait AESEncryption {
  def decrypt(key: Array[Byte], encryptedValue: Array[Byte]): Array[Byte]
}


object DefaultAESEncryption extends AESEncryption {

  private def cipher(key: Array[Byte], encryptMode: Int) = {
    val cipher = Cipher.getInstance("AES/CTR/NoPadding")

    // based on Python's Crypto.Cipher.AES and Crypto.Util.Counter
    val blockSize = cipher.getBlockSize
    // ref: https://pythonhosted.org/pycrypto/Crypto.Util.Counter-module.html
    // Python default is Big Endian
    val counter = Array[Byte](1).padTo(blockSize, 0.toByte).reverse
    val ivParameterSpec = new IvParameterSpec(counter)

    cipher.init(encryptMode, keyToSpec(key), ivParameterSpec)
    cipher
  }

  def keyToSpec(key: Array[Byte]): SecretKeySpec = new SecretKeySpec(key, "AES")

  def encrypt(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
    cipher(key, Cipher.ENCRYPT_MODE).doFinal(value)
  }

  def decrypt(key: Array[Byte], encryptedValue: Array[Byte]): Array[Byte] = {
    cipher(key, Cipher.DECRYPT_MODE).doFinal(encryptedValue)
  }
} 
开发者ID:kdrakon,项目名称:scala-credstash,代码行数:37,代码来源:AESEncryption.scala


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


示例17: Hmac

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

import java.security.Security
import javax.crypto.spec.SecretKeySpec

import one.lockstep.util._


class Hmac private (serviceName: String) extends Mac with Cryptosystem {

  private lazy val provider = {
    val preferredProviders = Seq("GmsCore_OpenSSL", "AndroidOpenSSL", "SunJCE")
    val providers = Security.getProviders(s"Mac.$serviceName")
    val filteredProviders = providers.filter(p => preferredProviders.contains(p.getName)).distinct
    filteredProviders.head
  }

  private def newInstance() = javax.crypto.Mac.getInstance(serviceName, provider)
  override lazy val blockLength: Int = newInstance().getMacLength*8
  override lazy val bitStrength: Int = blockLength/2
  override lazy val keyLength: Int = blockLength/2

  override def apply(secretKey: SecretKey): Bytes ? MacTag = {
    bytes ?
      val hmac = newInstance()
      val key = new SecretKeySpec(secretKey.raw, serviceName)
      hmac.init(key)
      MacTag(hmac.doFinal(bytes))
  }

  override def keygen(): SecretKey =
    SecretKey(random.bits(keyLength).bytes)

  override def validate(secretKey: SecretKey): Boolean =
    secretKey.bitLength == keyLength
}

object Hmac {
  val md5 = new Hmac("HmacMD5") { override lazy val bitStrength = 64 }
  val sha1 = new Hmac("HmacSHA1") { override lazy val bitStrength = 80 }
  val sha256 = new Hmac("HmacSHA256") { override lazy val bitStrength = 128 }
  val sha386 = new Hmac("HmacSHA386") { override lazy val bitStrength = 192 }
  val sha512 = new Hmac("HmacSHA512") { override lazy val bitStrength = 256 }
  private val members: Seq[Hmac] = Seq(md5, sha1, sha256, sha386, sha512)
  def apply(l: Int): Hmac =
    members.filter(_.bitStrength >= l).minBy(_.bitStrength)
} 
开发者ID:lockstep-one,项目名称:vault,代码行数:48,代码来源:Hmac.scala


示例18: mac

//设置package包名称以及导入依赖的类
package com.redbubble.hawk.validate

import java.nio.charset.StandardCharsets._
import javax.crypto
import javax.crypto.spec.SecretKeySpec

import com.redbubble.hawk.validate.Base64Ops._

trait MacOps {
  final def mac(credentials: Credentials, data: Array[Byte]): MAC = MAC(base64Encode(createMac(credentials, data)))

  private def createMac(credentials: Credentials, data: Array[Byte]): Array[Byte] = {
    val mac = crypto.Mac.getInstance(credentials.algorithm.keyGeneratorAlgorithm)
    val key = new SecretKeySpec(credentials.key.getBytes(UTF_8), credentials.algorithm.keyGeneratorAlgorithm)
    mac.init(key)
    mac.doFinal(data)
  }
}

object MacOps extends MacOps 
开发者ID:redbubble,项目名称:finagle-hawk,代码行数:21,代码来源:MacOps.scala


示例19: AesUtil

//设置package包名称以及导入依赖的类
package com.evenfinancial.sbt.secrets.util

import java.util.Base64
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.spec.{IvParameterSpec, SecretKeySpec}

// Basically copied from the Play framework's Crypto library.
// @see https://github.com/playframework/playframework/blob/2.4.x/framework/src/play/src/main/scala/play/api/libs/Crypto.scala
object AesUtil {

  def encrypt(data: String, dataKey: String): String = {
    val secretKey = buildSecretKey(dataKey)
    val cipher = buildCipher()
    cipher.init(Cipher.ENCRYPT_MODE, secretKey)
    val encrypted = cipher.doFinal(data.getBytes("UTF-8"))
    val result = cipher.getIV() ++ encrypted
    Base64.getEncoder.encodeToString(result)
  }

  def decrypt(data: String, dataKey: String): String = {
    val secretKey = buildSecretKey(dataKey)
    val bytes = Base64.getDecoder.decode(data)
    val cipher = buildCipher()
    val iv = bytes.slice(0, cipher.getBlockSize)
    val payload = bytes.slice(cipher.getBlockSize, bytes.size)
    cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv))
    new String(cipher.doFinal(payload), "utf-8")
  }

  private def buildCipher() = Cipher.getInstance("AES/CTR/NoPadding")

  private def buildSecretKey(dataKey: String) = {
    val algorithm = "AES"
    val messageDigest = MessageDigest.getInstance("SHA-256")
    messageDigest.update(dataKey.getBytes("utf-8"))
    // max allowed length in bits / (8 bits to a byte)
    val maxAllowedKeyLength = Cipher.getMaxAllowedKeyLength(algorithm) / 8
    val raw = messageDigest.digest().slice(0, maxAllowedKeyLength)
    new SecretKeySpec(raw, algorithm)
  }

} 
开发者ID:EVENFinancial,项目名称:sbt-secrets,代码行数:44,代码来源:AesUtil.scala


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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