本文整理汇总了Scala中java.util.Base64类的典型用法代码示例。如果您正苦于以下问题:Scala Base64类的具体用法?Scala Base64怎么用?Scala Base64使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Base64类的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: ConsulStoreActorMapper
//设置package包名称以及导入依赖的类
package io.vamp.persistence.consul
import java.util.Base64
import akka.http.scaladsl.model.ContentTypes
import io.vamp.common.{ ClassMapper, Config }
import io.vamp.persistence.KeyValueStoreActor
import scala.concurrent.Future
class ConsulStoreActorMapper extends ClassMapper {
val name = "consul"
val clazz = classOf[ConsulStoreActor]
}
class ConsulStoreActor extends KeyValueStoreActor {
private lazy val url = Config.string("vamp.persistence.key-value-store.consul.url")()
override protected def info(): Future[Any] = httpClient.get[Any](s"$url/v1/agent/self") map { consul ?
Map("type" ? "consul", "consul" ? consul)
}
override protected def all(path: List[String]): Future[List[String]] = {
val key = pathToString(path)
checked[List[String]](httpClient.get[List[String]](urlOf(path, keys = true), logError = false) recover { case _ ? Nil }) map { list ?
list.map(_.substring(key.length))
}
}
override protected def get(path: List[String]): Future[Option[String]] = {
httpClient.get[List[_]](urlOf(path), logError = false) recover { case _ ? None } map {
case head :: Nil ? Option(result(head.asInstanceOf[Map[_, _]]))
case _ ? None
}
}
override protected def set(path: List[String], data: Option[String]): Future[Any] = data match {
case None ? httpClient.delete(urlOf(path), logError = false)
case Some(value) ? httpClient.put[Any](urlOf(path), value, contentType = ContentTypes.`text/plain(UTF-8)`)
}
private def urlOf(path: List[String], keys: Boolean = false) = {
s"$url/v1/kv${pathToString(path)}${if (keys) "?keys" else ""}"
}
private def result(map: Map[_, _]): String = map.asInstanceOf[Map[String, _]].get("Value") match {
case Some(value) if value != null ? new String(Base64.getDecoder.decode(value.asInstanceOf[String]))
case _ ? ""
}
}
示例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: TrackingController
//设置package包名称以及导入依赖的类
package controllers
import java.security.MessageDigest
import play.api._
import play.api.libs.Codecs
import play.api.mvc._
// Java8 lib
import java.util.Base64
class TrackingController extends Controller {
val COOKIE_KEY = "Z_SYSTEM_3RD_PARTY_COOKIE_ID_SCALA"
val COOKIE_MAX_AFTER_AGE = Some(31622400 + 31622400)
//ref https://css-tricks.com/snippets/html/base64-encode-of-1x1px-transparent-gif/
val onePixelGifBase64 = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
val onePixelGifBytes = Base64.getDecoder().decode(onePixelGifBase64)
def pixelTracking = Action {request =>
val cookies = request.cookies
val cookieValue = cookies.get(COOKIE_KEY).map { cookie =>
Logger.debug(s"Cookie Exist! ${cookie.value}")
cookie.value
}.getOrElse {
val newValue = uniqueIdGenerator()
Logger.debug("Cookie Generate! $newValue")
newValue
}
Ok(onePixelGifBytes).withCookies(Cookie(COOKIE_KEY, cookieValue, COOKIE_MAX_AFTER_AGE)).as("image/gif")
}
val uniqueIdGenerator = () => {
val milliTime = System.currentTimeMillis()
val nanoTime = System.nanoTime()
val baseString = s"$milliTime $nanoTime"
Logger.debug(baseString)
val md = MessageDigest.getInstance("SHA-256")
md.update(baseString.getBytes())
val id = Codecs.toHexString(md.digest())
Logger.debug(id)
id
}
}
示例7: SauceLabsClient
//设置package包名称以及导入依赖的类
package tools
import java.nio.ByteBuffer
import java.util.Base64
import javax.net.ssl.SSLContext
import org.http4s.blaze.channel.nio2.ClientChannelFactory
import org.http4s.blaze.http.{HttpClient, HttpResponse}
import org.http4s.blaze.util.{Execution, GenericSSLContext}
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
class SauceLabsClient(userName: String, accessKey: String, jobId: String) extends HttpClient {
import scala.concurrent.ExecutionContext.Implicits.global
override lazy val connectionManager = new ClientChannelFactory()
override protected val sslContext: SSLContext = GenericSSLContext.clientSSLContext()
def setName(name: String): Unit = {
putToJob(s"""{"name": "$name"}""")
}
def setPassed(passed: Boolean): Unit = {
putToJob(s"""{"passed": $passed}""")
}
def putToJob(data: String): Unit = {
val authorization = {
val s = s"$userName:$accessKey"
Base64.getEncoder.encodeToString(s.getBytes)
}
val headers = Seq(
"content-type" -> "application/json",
"authorization" -> s"Basic $authorization"
)
val response = PUT(
url = s"https://saucelabs.com/rest/v1/$userName/jobs/$jobId", headers,
body = ByteBuffer.wrap(data.getBytes),
5 seconds
)
Await.result(response, 10 seconds)
}
// Cause blaze client doesn't support anything else GET!
def PUT(url: String, headers: Seq[(String, String)], body: ByteBuffer,timeout: Duration): Future[HttpResponse] = {
val r = runReq("PUT", url, headers, body, timeout)
r.flatMap {
case r: HttpResponse => Future.successful(r)
case r => Future.failed(new Exception(s"Received invalid response type: ${r.getClass}"))
}(Execution.directec)
}
}
示例8: UuidUtil
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.util
import java.nio.ByteBuffer
import java.util.Base64
import java.util.UUID
object UuidUtil {
private val encoder: Base64.Encoder = Base64.getUrlEncoder
private val decoder: Base64.Decoder = Base64.getUrlDecoder
private val lastRedundantCharacters: String = "=="
def toBase64(uuid: UUID): String = {
val uuidBytes = ByteBuffer.wrap(new Array[Byte](16))
uuidBytes.putLong(uuid.getMostSignificantBits)
uuidBytes.putLong(uuid.getLeastSignificantBits)
val result = encoder.encodeToString(uuidBytes.array())
if (result.endsWith(lastRedundantCharacters)) {
result.substring(0, result.length - lastRedundantCharacters.length)
} else {
result
}
}
def toUuid(str: String): UUID = try {
UUID.fromString(str)
} catch {
case e: IllegalArgumentException =>
val uuidBytes = ByteBuffer.wrap(decoder.decode(str))
val result = new UUID(uuidBytes.getLong, uuidBytes.getLong)
if (uuidBytes.hasRemaining) {
throw new IllegalArgumentException("Invalid UUID string: " + str)
}
result
}
}
示例9: MsgPack
//设置package包名称以及导入依赖的类
package com.taxis99.amazon.serializers
import java.util.Base64
import com.typesafe.scalalogging.Logger
import msgpack4z.{MsgOutBuffer, _}
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsValue, Json}
object MsgPack extends ISerializer {
protected val logger: Logger =
Logger(LoggerFactory.getLogger(getClass.getName))
protected val jsonVal = Play2Msgpack.jsValueCodec(PlayUnpackOptions.default)
protected val b64encoder = Base64.getEncoder
protected val b64decoder = Base64.getDecoder
override def decode(value: String): JsValue = {
val bytes: Array[Byte] = b64decoder.decode(value)
val unpacker = MsgInBuffer.apply(bytes)
val unpacked = jsonVal.unpack(unpacker)
unpacked.valueOr { e =>
logger.error("Could not decode message", e)
new ClassCastException("Could not decode message")
Json.obj()
}
}
}
示例10: SauceLabsClient
//设置package包名称以及导入依赖的类
package tools
import java.nio.ByteBuffer
import java.util.Base64
import javax.net.ssl.SSLContext
import org.http4s.blaze.channel.nio2.ClientChannelFactory
import org.http4s.blaze.http.{HttpClient, HttpResponse}
import org.http4s.blaze.util.{Execution, GenericSSLContext}
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
class SauceLabsClient(userName: String, accessKey: String, jobId: String) extends HttpClient {
import scala.concurrent.ExecutionContext.Implicits.global
override lazy val connectionManager = new ClientChannelFactory()
override protected val sslContext: SSLContext = GenericSSLContext.clientSSLContext()
def setName(name: String): Unit = {
putToJob(s"""{"name": "$name"}""")
}
def setPassed(passed: Boolean): Unit = {
putToJob(s"""{"passed": $passed}""")
}
def putToJob(data: String): Unit = {
val authorization = {
val s = s"$userName:$accessKey"
Base64.getEncoder.encodeToString(s.getBytes)
}
val headers = Seq(
"content-type" -> "application/json",
"authorization" -> s"Basic $authorization"
)
val response = PUT(
url = s"https://saucelabs.com/rest/v1/$userName/jobs/$jobId", headers,
body = ByteBuffer.wrap(data.getBytes),
5 seconds
)
Await.result(response, 10 seconds)
()
}
// Cause blaze client doesn't support anything else GET!
def PUT(url: String, headers: Seq[(String, String)], body: ByteBuffer,timeout: Duration): Future[HttpResponse] = {
val r = runReq("PUT", url, headers, body, timeout)
r.flatMap {
case r: HttpResponse => Future.successful(r)
case _ => Future.failed(new Exception(s"Received invalid response type: ${r.getClass}"))
}(Execution.directec)
}
}
示例11: Ecr
//设置package包名称以及导入依赖的类
package sbtecr
import java.util.Base64
import com.amazonaws.regions.Region
import com.amazonaws.services.ecr.AmazonECRClient
import com.amazonaws.services.ecr.model._
import sbt.Logger
import scala.collection.JavaConverters._
private[sbtecr] object Ecr extends Aws {
def domain(region: Region, accountId: String) = s"${accountId}.dkr.ecr.${region}.amazonaws.com"
def createRepository(region: Region, repositoryName: String)(implicit logger: Logger): Unit = {
val request = new CreateRepositoryRequest()
request.setRepositoryName(repositoryName)
try {
val result = ecr(region).createRepository(request)
logger.info(s"Repository created in ${region}: arn=${result.getRepository.getRepositoryArn}")
} catch {
case e: RepositoryAlreadyExistsException =>
logger.info(s"Repository exists: ${region}/${repositoryName}")
}
}
def dockerCredentials(region: Region)(implicit logger: Logger): (String, String) = {
val request = new GetAuthorizationTokenRequest()
val response = ecr(region).getAuthorizationToken(request)
response
.getAuthorizationData
.asScala
.map(_.getAuthorizationToken)
.map(Base64.getDecoder.decode(_))
.map(new String(_, "UTF-8"))
.map(_.split(":"))
.headOption match {
case Some(creds) if creds.size == 2 =>
(creds(0), creds(1))
case _ =>
throw new IllegalStateException("Authorization token not found.")
}
}
private def ecr(region: Region) = client(classOf[AmazonECRClient], region)
}
示例12: Keys
//设置package包名称以及导入依赖的类
package com.malliina.aws.cognito
import java.math.BigInteger
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.RSAPublicKeySpec
import java.util.Base64
object Keys {
val keyFactory = KeyFactory.getInstance("RSA")
def publicKey(key: JWTKey): RSAPublicKey =
publicKey(toBigInt(key.n), toBigInt(key.e))
private def publicKey(modulus: BigInteger, exponent: BigInteger): RSAPublicKey = {
val keySpec = new RSAPublicKeySpec(modulus, exponent)
keyFactory.generatePublic(keySpec).asInstanceOf[RSAPublicKey]
}
private def toBigInt(enc: String): BigInteger =
new BigInteger(1, Base64.getUrlDecoder.decode(enc))
}
示例13: Plist
//设置package包名称以及导入依赖的类
package jp.pigumer
import java.security.{PrivateKey, Signature}
import java.util.Base64
import org.bouncycastle.pkcs.PKCS10CertificationRequest
case class Plist(csr: PKCS10CertificationRequest, chain: String, privateKey: PrivateKey) {
def toXml = {
val csrString = Base64.getEncoder.encodeToString(csr.getEncoded)
val signature = Signature.getInstance("SHA1WithRSA")
signature.initSign(privateKey)
signature.update(csr.getEncoded)
val signatureString = Base64.getEncoder.encodeToString(signature.sign)
s"""<?xml version="1.0" encoding="UTF-8"?>
|<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|<plist version="1.0">
|<dict>
|<key>PushCertRequestCSR</key>
|<string>
|$csrString
|</string>
|<key>PushCertCertificateChain</key>
|<string>
|$chain
|</string>
|<key>PushCertSignature</key>
|<string>
|$signatureString
|</string>
|</dict>
|</plist>
""".stripMargin
}
}
示例14: PlistFactory
//设置package包名称以及导入依赖的类
package jp.pigumer
import java.security.PrivateKey
import java.util.Base64
import org.bouncycastle.pkcs.PKCS10CertificationRequest
object PlistFactory {
def generate(csr: PKCS10CertificationRequest,
vendorCertificate: String,
appleCertificate: String,
appleRootCertificate: String,
vendorPrivateKey: PrivateKey) = {
val plist = generatePlist(csr, vendorCertificate + "\n" + appleCertificate + "\n" + appleRootCertificate, vendorPrivateKey)
Base64.getEncoder.encodeToString(plist.getBytes())
}
def generatePlist(csr: PKCS10CertificationRequest,
chain: String,
vendorPrivateKey: PrivateKey) = {
val plist = Plist(csr, chain, vendorPrivateKey)
plist.toXml
}
}
示例15: 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)
}