本文整理汇总了Scala中org.apache.commons.codec.binary.Base64类的典型用法代码示例。如果您正苦于以下问题:Scala Base64类的具体用法?Scala Base64怎么用?Scala Base64使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Base64类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: RSAUtils
//设置package包名称以及导入依赖的类
package com.wix.pay.twocheckout.tokenization
import java.security.KeyFactory
import java.security.spec.RSAPublicKeySpec
import javax.crypto.Cipher
import org.apache.commons.codec.binary.Base64
object RSAUtils {
def rsaEncrypt(key: RSAPublicKey, text: String) = {
val modulus = BigInt(1, Base64.decodeBase64(key.base64Modulus))
val exp = BigInt(1, Base64.decodeBase64(key.base64Exp))
val publicKeySpec = new RSAPublicKeySpec(modulus.bigInteger, exp.bigInteger)
val publicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec)
val cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
val res = cipher.doFinal(text.getBytes("UTF-8"))
Base64.encodeBase64String(res)
}
}
case class RSAPublicKey(base64Modulus: String, base64Exp: String)
示例2: RSAUtilsTest
//设置package包名称以及导入依赖的类
package com.wix.pay.twocheckout.tokenization
import java.security.spec.RSAPublicKeySpec
import java.security.{KeyFactory, KeyPairGenerator}
import javax.crypto.Cipher
import org.apache.commons.codec.binary.Base64
import org.specs2.mutable.SpecWithJUnit
import org.specs2.specification.Scope
class RSAUtilsTest extends SpecWithJUnit {
"RSAUtils" should {
"encrypt data with provided key in base64 format" in new Ctx {
val encrypted = RSAUtils.rsaEncrypt(publicKey, someMessage)
decryptBase64(encrypted) mustEqual someMessage
}
"encrypt empty string with provided key in base64 format" in new Ctx {
val encrypted = RSAUtils.rsaEncrypt(publicKey, emptyMessage)
decryptBase64(encrypted) mustEqual emptyMessage
}
}
trait Ctx extends Scope {
val factory = KeyPairGenerator.getInstance("RSA")
factory.initialize(2048)
val keys = factory.genKeyPair()
val publicKeySpec = KeyFactory.getInstance("RSA").getKeySpec(keys.getPublic, classOf[RSAPublicKeySpec])
val publicKey = RSAPublicKey(
Base64.encodeBase64String(publicKeySpec.getModulus.toByteArray),
Base64.encodeBase64String(publicKeySpec.getPublicExponent.toByteArray)
)
println(publicKey)
val someMessage = "some message hello"
val emptyMessage = ""
def decryptBase64(encrypted: String): String = {
val bytes = Base64.decodeBase64(encrypted)
val cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate)
new String(cipher.doFinal(bytes), "utf-8")
}
}
}
示例3: TokenizerRequestBuilder
//设置package包名称以及导入依赖的类
package com.wix.pay.twocheckout.tokenizer
import com.wix.pay.creditcard.CreditCard
import org.apache.commons.codec.binary.Base64
class TokenizerRequestBuilder {
def pretokenRequest(sellerId: String, publishableKey: String) = {
val base64Key = Base64.encodeBase64String(publishableKey.getBytes("utf-8"))
s"""{"sellerId":"$sellerId","publicKey":"$base64Key","userPref":""}"""
}
def tokenRequest(sellerId: String, paymentMethod: String) = {
val base64Method = Base64.encodeBase64String(paymentMethod.getBytes("utf-8"))
s"""{"sellerId":"$sellerId","paymentMethod":"$base64Method"}"""
}
def innerTokenRequest(card: CreditCard, publishableKey: String, preToken: String) = {
val month = card.expiration.month formatted "%02d"
val year = card.expiration.year
val number = card.number
val cvv = card.csc.get
s"""{"paymentMethod":{"cardNum":"$number", "expMonth":"$month", "expYear":"$year", "cvv":"$cvv", "cardType":"CC"},
|"pubAccessKey":"$publishableKey",
|"preToken":"$preToken"}""".stripMargin
}
}
示例4: 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
}
}
示例5: AuthService
//设置package包名称以及导入依赖的类
package services
import java.security.MessageDigest
import java.util.UUID
import java.util.concurrent.TimeUnit
import model.User
import org.apache.commons.codec.binary.Base64
import org.mindrot.jbcrypt.BCrypt
import play.api.cache.SyncCacheApi
import play.api.mvc.{Cookie, RequestHeader}
import scalikejdbc._
import scala.concurrent.duration.Duration
class AuthService(cacheApi: SyncCacheApi) {
def login(userCode: String, password: String): Option[Cookie] = {
for {
user <- checkUser(userCode, password)
cookie <- Some(createCookie(user))
} yield {
cookie
}
}
def checkCookie(header: RequestHeader): Option[User] = {
for {
cookie <- header.cookies.get(cookieHeader)
user <- cacheApi.get[User](cookie.value)
} yield {
user
}
}
private def checkUser(userCode: String, password: String): Option[User] =
DB.readOnly { implicit session =>
val maybeUser = sql"select * from users where user_code = $userCode".
map(User.fromRS).single().apply()
maybeUser.flatMap { user =>
if (BCrypt.checkpw(password, user.password)) {
Some(user)
} else None
}
}
val mda = MessageDigest.getInstance("SHA-512")
val cookieHeader = "X-Auth-Token"
private def createCookie(user: User): Cookie = {
val randomPart = UUID.randomUUID().toString.toUpperCase
val userPart = user.userId.toString.toUpperCase
val key = s"$randomPart|$userPart"
val token = Base64.encodeBase64String(mda.digest(key.getBytes))
val duration = Duration.create(10, TimeUnit.HOURS)
cacheApi.set(token, user, duration)
Cookie(cookieHeader, token, maxAge = Some(duration.toSeconds.toInt))
}
}
示例6: login
//设置package包名称以及导入依赖的类
package controllers
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.libs.json._
import org.apache.commons.codec.binary.Base64
import java.util.UUID
import scala.concurrent.Future
trait SessionController extends Controller with Session {
def login = Action.async { req =>
req.headers.get("Authorization").map { auth =>
val userpass = decodeBase64(auth.split(" ").tail.head).split(":")
val (user, pass) = (userpass.headOption, userpass.drop(1).headOption.getOrElse(""))
user.map { us =>
if (us == "login" && pass == "password") {
val uuid = UUID.randomUUID.toString
saveAccessTokenForUser(uuid, us)
Future.successful(Ok(uuid))
}
else {
futureUnauthorized
}
} getOrElse futureUnauthorized
} getOrElse futureUnauthorized
}
private val futureUnauthorized = Future.successful(Unauthorized)
private def decodeBase64(str: String) = new String(Base64.decodeBase64(str), "UTF-8")
}
trait Session {
private var sessionMap = new java.util.concurrent.ConcurrentHashMap[String, String]
def saveAccessTokenForUser(token: String, user: String) = sessionMap.put(token, user)
def getUserForAccessToken(token: String) = {
val r = sessionMap.get(token)
if ( r == null)
None
else
Some(r)
}
}
object SessionController extends SessionController
示例7: StringUtils
//设置package包名称以及导入依赖的类
package utils
import org.apache.commons.codec.binary.Base64
object StringUtils {
implicit class StringUtilsExtensions(val self: String) extends AnyVal {
def stripMargins(margin: String): String = self.stripPrefix(margin).stripSuffix(margin)
}
implicit class ByteArrayToBase64StringExtensions(val array: Array[Byte]) extends AnyVal {
def asBase64(): String = Base64.encodeBase64String(array)
}
implicit class ByteArrayFromBase64StringExtensions(val string: String) extends AnyVal {
def fromBase64(): Array[Byte] = Base64.decodeBase64(string)
}
}
示例8: SignatureAlgorithm
//设置package包名称以及导入依赖的类
package me.laiseca.oauth1.client.core.model
import me.laiseca.oauth1.client.core.Defaults
import me.laiseca.oauth1.client.core.util.UrlEncode
import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.HmacUtils
abstract class SignatureAlgorithm(val name: String) {
def digest(text: String, consumerSecret: Option[String], tokenSecret: Option[String]): String = {
assert(consumerSecret.isDefined || tokenSecret.isDefined)
val d = digest(
key(consumerSecret, tokenSecret).getBytes(Defaults.Charset),
text.getBytes(Defaults.Charset))
val digest64 = new Base64(0).encode(d)
new String(digest64, Defaults.Charset)
}
private[this] def key(consumerSecret: Option[String], tokenSecret: Option[String]): String = concat {
UrlEncode.encode(List(consumerSecret.getOrElse(""), tokenSecret.getOrElse("")))
}
private[this] def concat(items: Iterable[String]): String = items.mkString("&")
protected def digest(key: Array[Byte], text: Array[Byte]): Array[Byte]
}
case object HmacSHA1 extends SignatureAlgorithm("HMAC-SHA1") {
override protected def digest(key: Array[Byte], text: Array[Byte]): Array[Byte] =
HmacUtils.hmacSha1(key, text)
}
case object HmacSHA256 extends SignatureAlgorithm("HMAC-SHA256") {
override protected def digest(key: Array[Byte], text: Array[Byte]): Array[Byte] =
HmacUtils.hmacSha256(key, text)
}
示例9: Key
//设置package包名称以及导入依赖的类
package models
import java.nio.ByteBuffer
import java.security.SecureRandom
import net.glxn.qrgen._
import org.apache.commons.codec.binary.{Base32, Base64}
import play.api.Play
object Key {
val sr = new SecureRandom
val config = Play.current.configuration
val size = config.getInt("qrCode.size").getOrElse(160)
def next: String = {
var bb = ByteBuffer.allocate(8)
sr.nextBytes(bb.array)
val token = bb.getLong
token.abs.toHexString
}
def urlImage(key: String) : String = {
// data uris require base64 encoding of data
// ie: <img src="data:image/png;base64,data">
val url = s"http://www.onceness.com/msg/$key"
val data = new String(Base64.encodeBase64(QRCode.from(url).withSize(size,size).stream().toByteArray))
data
}
def msgImage(msg: String) : String = {
// data uris require base64 encoding of data
// ie: <img src="data:image/png;base64,data">
val data = new String(Base64.encodeBase64(QRCode.from(msg).withSize(size,size).stream().toByteArray))
data
}
}
示例10: BasicAuthorization
//设置package包名称以及导入依赖的类
package util
import org.apache.commons.codec.binary.Base64
object BasicAuthorization {
trait Authorization
case class Token(token: String) extends Authorization
def get(value: Option[String]): Option[Authorization] = {
value.flatMap { get(_) }
}
def get(value: String): Option[Authorization] = {
value.split(" ").toList match {
case "Basic" :: value :: Nil => {
new String(Base64.decodeBase64(value.getBytes)).split(":").toList match {
case Nil => None
case token :: rest => Some(Token(token))
}
}
case _ => None
}
}
}
示例11: NormalizationHandler
//设置package包名称以及导入依赖的类
package com.fustigatedcat.heystk.engine.normalization
import java.io.ByteArrayInputStream
import java.util.zip.GZIPInputStream
import com.fustigatedcat.heystk.common.normalization.Normalization
import com.fustigatedcat.heystk.engine.queue.RabbitQueue
import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.io.IOUtils
import org.json4s.native.JsonMethods.parse
import org.slf4j.LoggerFactory
object NormalizationHandler {
val logger = LoggerFactory.getLogger(this.getClass)
implicit val formats = org.json4s.DefaultFormats
def checksum(string : String) : String = {
DigestUtils.sha256Hex(string)
}
def unzip(string : String) : String = {
val arr = Base64.decodeBase64(string)
val gis = new GZIPInputStream(new ByteArrayInputStream(arr))
IOUtils.toString(gis, "UTF-8")
}
def handle(string : String, chksm : String) = {
val body = unzip(string)
if(checksum(body) == chksm) {
// write normalization to temp DB and post to Queue for needs processing
parse(unzip(string)).extract[List[Normalization]].par.foreach(RabbitQueue.postToProcess)
} else {
logger.error(s"Invalid checksum ${checksum(body)} != $chksm")
}
}
}
示例12: BasicAuthTokenAccessor
//设置package包名称以及导入依赖的类
package controllers.basic
import jp.t2v.lab.play2.auth.{AuthenticityToken, TokenAccessor}
import play.api.mvc.{Result, RequestHeader}
import org.apache.commons.codec.binary.Base64
import java.nio.charset.Charset
class BasicAuthTokenAccessor extends TokenAccessor {
override def delete(result: Result)(implicit request: RequestHeader): Result = result
override def put(token: AuthenticityToken)(result: Result)(implicit request: RequestHeader): Result = result
override def extract(request: RequestHeader): Option[AuthenticityToken] = {
val encoded = for {
h <- request.headers.get("Authorization")
if h.startsWith("Basic ")
} yield h.substring(6)
encoded.map(s => new String(Base64.decodeBase64(s), Charset.forName("UTF-8")))
}
}
示例13: JavaUUIDs
//设置package包名称以及导入依赖的类
package effectful.examples.pure.uuid.impl
import java.nio.ByteBuffer
import java.util.{UUID => JavaUUID}
import cats.Id
import effectful.examples.pure.uuid.UUIDs
import org.apache.commons.codec.binary.Base64
import scala.util.Try
class JavaUUIDs extends UUIDs[Id] {
import UUIDs._
implicit val print : UUID => String = toString(_)
def toUUID(uuid: JavaUUID) = UUID(toBytes(uuid))
def toBytes(uuid: JavaUUID) : Array[Byte] = {
val bb = ByteBuffer.allocate(16)
bb.putLong(uuid.getMostSignificantBits)
bb.putLong(uuid.getLeastSignificantBits)
bb.array()
}
def toJavaUUID(uuid: UUID) : JavaUUID = {
val bb = ByteBuffer.wrap(uuid.bytes.toArray)
val msb = bb.getLong
val lsb = bb.getLong
new JavaUUID(msb,lsb)
}
override def gen(): Id[UUID] =
toUUID(JavaUUID.randomUUID())
override def toString(uuid: UUID): String =
toJavaUUID(uuid).toString
override def fromBase64(s: String): Option[UUID] = {
val uuid = UUID(Base64.decodeBase64(s))
Try(toJavaUUID(uuid)).toOption.map(_ => uuid)
}
override def toBase64(uuid: UUID): String =
Base64.encodeBase64URLSafeString(uuid.bytes.toArray)
override def fromString(s: String): Id[Option[UUID]] =
Try(JavaUUID.fromString(s)).toOption.map(toUUID)
}
示例14: Bytes
//设置package包名称以及导入依赖的类
package com.avsystem.scex.util
import java.io.UnsupportedEncodingException
import java.nio.charset.StandardCharsets
import com.avsystem.commons.jiop.JavaInterop._
import com.avsystem.scex.presentation.annotation.Documentation
import org.apache.commons.codec.binary.{Base64, Hex}
import scala.collection.mutable
import scala.util.hashing.MurmurHash3
final class Bytes(val bytes: Array[Byte]) extends Comparable[Bytes] {
override def hashCode(): Int = MurmurHash3.bytesHash(bytes)
override def equals(other: Any): Boolean = other match {
case b: Bytes => java.util.Arrays.equals(bytes, b.bytes)
case _ => false
}
override def toString: String = s"Bytes($escaped)"
override def compareTo(o: Bytes): Int = {
def loop(i: Int): Int =
if (i == bytes.length && i == o.bytes.length) 0
else if (i == bytes.length) -1
else if (i == o.bytes.length) 1
else {
val b1 = bytes(i)
val b2 = o.bytes(i)
if (b1 == b2) loop(i + 1) else b1 - b2
}
loop(0)
}
@Documentation("Encodes this sequence of bytes as string with non-ASCII bytes and backslash escaped, e.g. 'hsg\\x7c\\x0dfoo\\\\bar'")
def escaped: String = EscapedBytes.render(bytes)
@Documentation("Encodes this sequence of bytes as hexadecimal string")
def hex: String = Hex.encodeHexString(bytes)
@Documentation("Encodes this sequence of bytes as BASE64 string")
def base64: String = Base64.encodeBase64String(bytes)
@Documentation("Decodes this sequence of bytes as UTF-8 string")
def decodeUTF8: String = new String(bytes, StandardCharsets.UTF_8)
@Documentation("Decodes this sequence of bytes as string using given charset")
def decode(charset: String): String =
try new String(bytes, charset) catch {
case e: UnsupportedEncodingException => throw new IllegalArgumentException(e)
}
def asList: JList[Byte] = new mutable.WrappedArray.ofByte(bytes).asJava
}
示例15: Encryption
//设置package包名称以及导入依赖的类
package me.flygare.utils
import java.security.MessageDigest
import java.util
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64
object Encryption {
def encrypt(key: String, value: String): String = {
val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, keyToSpec(key))
Base64.encodeBase64String(cipher.doFinal(value.getBytes("UTF-8")))
}
def decrypt(key: String, encryptedValue: String): String = {
val cipher: Cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING")
cipher.init(Cipher.DECRYPT_MODE, keyToSpec(key))
new String(cipher.doFinal(Base64.decodeBase64(encryptedValue)))
}
def keyToSpec(key: String): SecretKeySpec = {
var keyBytes: Array[Byte] = (SALT + key).getBytes("UTF-8")
val sha: MessageDigest = MessageDigest.getInstance("SHA-256")
keyBytes = sha.digest(keyBytes)
keyBytes = util.Arrays.copyOf(keyBytes, 16)
new SecretKeySpec(keyBytes, "AES")
}
private val SALT: String =
"1b9d370a82ba55843b71030c6b22bd88f8ae12d328c3154314272c995c2ce7b7"
}