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


Scala SecretKeySpec类代码示例

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


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


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