本文整理汇总了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")
}
}
示例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)
}
示例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)
}
}
}
示例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)
示例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)
}
}
示例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
}
}
示例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
}
示例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
}
}
示例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")))
}
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
示例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))
}
}
示例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)
}
}