java.util.Base64 Scala Examples

The following examples show how to use java.util.Base64. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SslContexts.scala    From kubernetes-client   with Apache License 2.0 5 votes vote down vote up
package com.goyeau.kubernetes.client.util
import java.io.{ByteArrayInputStream, File, FileInputStream, InputStreamReader}
import java.security.cert.{CertificateFactory, X509Certificate}
import java.security.{KeyStore, SecureRandom, Security}
import java.util.Base64

import com.goyeau.kubernetes.client.KubeConfig
import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory}
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
import org.bouncycastle.openssl.{PEMKeyPair, PEMParser}

object SslContexts {
  private val TrustStoreSystemProperty         = "javax.net.ssl.trustStore"
  private val TrustStorePasswordSystemProperty = "javax.net.ssl.trustStorePassword"
  private val KeyStoreSystemProperty           = "javax.net.ssl.keyStore"
  private val KeyStorePasswordSystemProperty   = "javax.net.ssl.keyStorePassword"

  def fromConfig(config: KubeConfig): SSLContext = {
    val sslContext = SSLContext.getInstance("TLS")
    sslContext.init(keyManagers(config), trustManagers(config), new SecureRandom)
    sslContext
  }

  private def keyManagers(config: KubeConfig) = {
    // Client certificate
    val certDataStream = config.clientCertData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data)))
    val certFileStream = config.clientCertFile.map(new FileInputStream(_))

    // Client key
    val keyDataStream = config.clientKeyData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data)))
    val keyFileStream = config.clientKeyFile.map(new FileInputStream(_))

    for {
      keyStream  <- keyDataStream.orElse(keyFileStream)
      certStream <- certDataStream.orElse(certFileStream)
    } yield {
      Security.addProvider(new BouncyCastleProvider())
      val pemKeyPair =
        new PEMParser(new InputStreamReader(keyStream)).readObject().asInstanceOf[PEMKeyPair] // scalafix:ok
      val privateKey = new JcaPEMKeyConverter().setProvider("BC").getPrivateKey(pemKeyPair.getPrivateKeyInfo)

      val certificateFactory = CertificateFactory.getInstance("X509")
      val certificate        = certificateFactory.generateCertificate(certStream).asInstanceOf[X509Certificate] // scalafix:ok

      defaultKeyStore.setKeyEntry(
        certificate.getSubjectX500Principal.getName,
        privateKey,
        config.clientKeyPass.fold(Array.empty[Char])(_.toCharArray),
        Array(certificate)
      )
    }

    val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
    keyManagerFactory.init(defaultKeyStore, Array.empty)
    keyManagerFactory.getKeyManagers
  }

  private lazy val defaultKeyStore = {
    val propertyKeyStoreFile =
      Option(System.getProperty(KeyStoreSystemProperty, "")).filter(_.nonEmpty).map(new File(_))

    val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)
    keyStore.load(
      propertyKeyStoreFile.map(new FileInputStream(_)).orNull,
      System.getProperty(KeyStorePasswordSystemProperty, "").toCharArray
    )
    keyStore
  }

  private def trustManagers(config: KubeConfig) = {
    val certDataStream = config.caCertData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data)))
    val certFileStream = config.caCertFile.map(new FileInputStream(_))

    certDataStream.orElse(certFileStream).foreach { certStream =>
      val certificateFactory = CertificateFactory.getInstance("X509")
      val certificate        = certificateFactory.generateCertificate(certStream).asInstanceOf[X509Certificate] // scalafix:ok
      defaultTrustStore.setCertificateEntry(certificate.getSubjectX500Principal.getName, certificate)
    }

    val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
    trustManagerFactory.init(defaultTrustStore)
    trustManagerFactory.getTrustManagers
  }

  private lazy val defaultTrustStore = {
    val securityDirectory = s"${System.getProperty("java.home")}/lib/security"

    val propertyTrustStoreFile =
      Option(System.getProperty(TrustStoreSystemProperty, "")).filter(_.nonEmpty).map(new File(_))
    val jssecacertsFile = Option(new File(s"$securityDirectory/jssecacerts")).filter(f => f.exists && f.isFile)
    val cacertsFile     = new File(s"$securityDirectory/cacerts")

    val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)
    keyStore.load(
      new FileInputStream(propertyTrustStoreFile.orElse(jssecacertsFile).getOrElse(cacertsFile)),
      System.getProperty(TrustStorePasswordSystemProperty, "changeit").toCharArray
    )
    keyStore
  }
} 
Example 2
Source File: Btoa.scala    From asura   with MIT License 5 votes vote down vote up
package asura.core.script.function

import java.nio.charset.StandardCharsets
import java.util.Base64

import scala.concurrent.Future

object Btoa extends TransformFunction {

  override val name: String = "btoa"
  override val description: String = "Creates a base-64 encoded ASCII string from a string"

  override def apply(arg: Object): Future[String] = {
    Future.successful {
      if (null != arg) {
        Base64.getEncoder().encodeToString(arg.asInstanceOf[String].getBytes(StandardCharsets.UTF_8))
      } else {
        "null"
      }
    }
  }
} 
Example 3
Source File: BasicAuth.scala    From asura   with MIT License 5 votes vote down vote up
package asura.app.api.auth

import java.nio.charset.StandardCharsets
import java.util.Base64

import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.headers.RawHeader
import asura.core.auth.AuthorizeAndValidate
import asura.core.es.model.Authorization

import scala.concurrent.Future

object BasicAuth extends AuthorizeAndValidate {

  override val `type`: String = "Basic Auth"
  override val description: String =
    """## Basic Auth
      |> Add a header with the key `Authorization` and the value a string encoded by base64.
      |
      |### Example
      |
      |If the data is as below:
      |
      |```json
      |{
      |    "username" : "a",
      |    "password": "b"
      |}
      |```
      |
      |A header `Authorization: Basic YTpi` will be added. `YTpi` is generated by call `Base64.encode("a:b")`.
      |
    """.stripMargin


  override val template: String =
    """{
      |    "username" : "",
      |    "password": ""
      |}
    """.stripMargin

  override def authorize(request: HttpRequest, auth: Authorization): Future[HttpRequest] = {
    val username = auth.data.get("username")
    val password = auth.data.get("password")
    val bytes = Base64.getEncoder.encode(s"${username.get}:${password.get}".getBytes(StandardCharsets.UTF_8))
    val value = new String(bytes, StandardCharsets.UTF_8)
    Future.successful(request.withHeaders(request.headers :+ RawHeader("Authorization", s"Basic ${value}")))
  }

  override def validate(auth: Authorization): (Boolean, String) = {
    val username = auth.data.get("username")
    val password = auth.data.get("password")
    if (username.isEmpty || password.isEmpty) {
      (false, "username and password can't be empty")
    } else {
      (true, null)
    }
  }
} 
Example 4
Source File: Crypto.scala    From gospeak   with Apache License 2.0 5 votes vote down vote up
package gospeak.libs.scala

import java.nio.ByteBuffer
import java.security.{Key, MessageDigest, SecureRandom}
import java.util.Base64

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

import scala.util.Try

object Crypto {
  private val charEnc = "UTF-8"
  private val aesKeyLength = 128
  private val aesTransformationString = "AES/CFB/NoPadding"

  def base64Encode(message: String): String =
    base64Encode(message.getBytes)

  def base64Encode(message: Array[Byte]): String =
    new String(Base64.getEncoder.encode(message), charEnc)

  def base64Decode(base64: String): Try[String] =
    base64DecodeBytes(base64).map(new String(_, charEnc))

  def base64DecodeBytes(base64: String): Try[Array[Byte]] =
    Try(Base64.getDecoder.decode(base64.getBytes(charEnc)))

  def md5(message: String): String =
    MessageDigest.getInstance("MD5").digest(message.getBytes).map("%02x".format(_)).mkString

  def sha1(message: String): String =
    MessageDigest.getInstance("SHA1").digest(message.getBytes).map("%02x".format(_)).mkString

  def secureRandom(): Try[Double] = {
    Try(SecureRandom.getInstance("SHA1PRNG")).map { sr =>
      val seedByteCount = 10
      val seed = sr.generateSeed(seedByteCount)
      sr.setSeed(seed)
      sr.nextDouble()
    }
  }

  final case class AesSecretKey(value: String) extends Key {
    override def getAlgorithm: String = "AES"

    override def getFormat: String = "RAW"

    override def getEncoded: Array[Byte] = base64DecodeBytes(value).get

    override def toString: String = "AesSecretKey(*****)"
  }

  final case class AesEncrypted(cipher: String)

  def aesGenerateKey(): Try[AesSecretKey] = for {
    // Generate an AES key of the desired length (in bits) using an AES KeyGenerator.
    keyGen <- Try(KeyGenerator.getInstance("AES"))
    _ <- Try(keyGen.init(aesKeyLength))
    secretKey <- Try(keyGen.generateKey)
  } yield AesSecretKey(base64Encode(secretKey.getEncoded))

  // adapted from https://www.owasp.org/index.php/Using_the_Java_Cryptographic_Extensions
  def aesEncrypt(message: String, secretKey: AesSecretKey): Try[AesEncrypted] = {
    for {
      // Get a Cipher instance of the desired algorithm, mode, and padding.
      aesCipherForEncryption <- Try(Cipher.getInstance(aesTransformationString))
      // Generate an initialization vector for our message of the same size as the Cipher's blocksize.
      iv <- Try(aesCipherForEncryption.getBlockSize).map(new Array[Byte](_))
      prng <- Try(new SecureRandom())
      _ = prng.nextBytes(iv)
      // Initialize the Cipher instance for encryption using the key and initialization vector.
      p <- Try(new IvParameterSpec(iv))
      _ <- Try(aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey, p))
      // Use the Cipher to encrypt the message (after encoding it to a byte[] using the named Charset), and then append the encrypted data to the IV and Base64-encode the result.
      m <- Try(message.getBytes(charEnc))
      encrypted <- Try(aesCipherForEncryption.doFinal(m))
      cipherData = ByteBuffer.allocate(iv.length + encrypted.length)
      _ = cipherData.put(iv)
      _ = cipherData.put(encrypted)
    } yield AesEncrypted(base64Encode(cipherData.array))
  }

  def aesDecrypt(message: AesEncrypted, secretKey: AesSecretKey): Try[String] = {
    for {
      // Get a new Cipher instance of the same algorithm, mode, and padding used for encryption.
      aesCipherForDecryption <- Try(Cipher.getInstance(aesTransformationString))
      // Base64-decode and split the data into the IV and the encrypted data, and then initialize the cipher for decryption with the same key used for encryption (symmetric), the IV, and the encrypted data.
      cipherData <- base64DecodeBytes(message.cipher).map(ByteBuffer.wrap)
      iv = new Array[Byte](aesCipherForDecryption.getBlockSize)
      _ <- Try(cipherData.get(iv))
      encrypted = new Array[Byte](cipherData.remaining)
      _ <- Try(cipherData.get(encrypted))
      _ <- Try(aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)))
      // Use the Cipher to decrypt the data, convert it to a String using the named Charset, and display the message.
      decrypted <- Try(aesCipherForDecryption.doFinal(encrypted))
    } yield new String(decrypted, charEnc)
  }
} 
Example 5
Source File: GitHubSourceAcl.scala    From kafka-security-manager   with MIT License 5 votes vote down vote up
package com.github.simplesteph.ksm.source

import java.io.{Reader, StringReader}
import java.nio.charset.Charset
import java.util.Base64

import com.fasterxml.jackson.databind.ObjectMapper
import com.typesafe.config.Config
import org.slf4j.LoggerFactory
import skinny.http.{HTTP, HTTPException, Request, Response}

import scala.util.Try

class GitHubSourceAcl extends SourceAcl {

  private val log = LoggerFactory.getLogger(classOf[GitHubSourceAcl])

  override val CONFIG_PREFIX: String = "github"
  final val USER_CONFIG = "user"
  final val REPO_CONFIG = "repo"
  final val FILEPATH_CONFIG = "filepath"
  final val BRANCH_CONFIG = "branch"
  final val HOSTNAME_CONFIG = "hostname"
  final val AUTH_BASIC_CONFIG = "auth.basic"
  final val AUTH_TOKEN_CONFIG = "auth.token"

  var lastModified: Option[String] = None
  val objectMapper = new ObjectMapper()
  var user: String = _
  var repo: String = _
  var filepath: String = _
  var branch: String = _
  var hostname: String = _
  var basicOpt: Option[String] = _
  var tokenOpt: Option[String] = _

  
  override def close(): Unit = {
    // HTTP
  }
} 
Example 6
Source File: BitbucketCloudSourceAcl.scala    From kafka-security-manager   with MIT License 5 votes vote down vote up
package com.github.simplesteph.ksm.source

import java.io._
import java.nio.charset.Charset
import java.util.Base64

import com.typesafe.config.Config
import org.slf4j.LoggerFactory
import skinny.http.{HTTP, HTTPException, Request, Response}

class BitbucketCloudSourceAcl extends SourceAcl {

  private val log = LoggerFactory.getLogger(classOf[BitbucketCloudSourceAcl])

  override val CONFIG_PREFIX: String = "bitbucket-cloud"

  final val API_URL_CONFIG = "api.url"
  final val ORGANIZATION_CONFIG = "organization"
  final val REPO_CONFIG = "repo"
  final val FILEPATH_CONFIG = "filepath"
  final val AUTH_USERNAME_CONFIG = "auth.username"
  final val AUTH_PASSWORD_CONFIG = "auth.password"

  var lastCommit: Option[String] = None

  var apiurl: String = _
  var organization: String = _
  var repo: String = _
  var filePath: String = _
  var username: String = _
  var password: String = _

  
  override def close(): Unit = {
    // HTTP
  }
} 
Example 7
Source File: BitbucketServerSourceAcl.scala    From kafka-security-manager   with MIT License 5 votes vote down vote up
package com.github.simplesteph.ksm.source

import java.io.{Reader, StringReader}
import java.nio.charset.Charset
import java.util.Base64

import com.fasterxml.jackson.databind.ObjectMapper
import com.typesafe.config.Config
import org.slf4j.LoggerFactory
import skinny.http.{HTTP, HTTPException, Request, Response}

class BitbucketServerSourceAcl extends SourceAcl {

  private val log = LoggerFactory.getLogger(classOf[BitbucketServerSourceAcl])

  override val CONFIG_PREFIX: String = "bitbucket-server"

  final val HOSTNAME_CONFIG = "hostname"
  final val PORT_CONFIG = "port"
  final val PROTOCOL_CONFIG = "protocol"
  final val PROJECT_CONFIG = "project"
  final val REPO_CONFIG = "repo"
  final val FILEPATH_CONFIG = "filepath"
  final val AUTH_USERNAME_CONFIG = "auth.username"
  final val AUTH_PASSWORD_CONFIG = "auth.password"
  final val BRANCH_CONFIG = "branch"

  var lastCommit: Option[String] = None
  val objectMapper = new ObjectMapper()
  var http: HTTP = HTTP

  var hostname: String = _
  var port: String = _
  var protocol: String = _
  var project: String = _
  var repo: String = _
  var filePath: String = _
  var username: String = _
  var password: String = _
  var branch: Option[String] = _

  
  override def close(): Unit = {
    // HTTP
  }
} 
Example 8
Source File: GitLabSourceAcl.scala    From kafka-security-manager   with MIT License 5 votes vote down vote up
package com.github.simplesteph.ksm.source

import java.io.{Reader, StringReader}
import java.nio.charset.Charset
import java.util.Base64

import com.fasterxml.jackson.databind.ObjectMapper
import com.typesafe.config.Config
import org.slf4j.LoggerFactory
import skinny.http.{HTTP, HTTPException, Request, Response}

class GitLabSourceAcl extends SourceAcl {

  private val log = LoggerFactory.getLogger(classOf[GitLabSourceAcl])

  override val CONFIG_PREFIX: String = "gitlab"
  final val REPOID_CONFIG = "repoid"
  final val FILEPATH_CONFIG = "filepath"
  final val BRANCH_CONFIG = "branch"
  final val HOSTNAME_CONFIG = "hostname"
  final val ACCESSTOKEN_CONFIG = "accesstoken"

  var lastModified: Option[String] = None
  val objectMapper = new ObjectMapper()
  var repoid: String = _
  var filepath: String = _
  var branch: String = _
  var hostname: String = _
  var accessToken: String = _

  
  override def close(): Unit = {
    // HTTP
  }
} 
Example 9
Source File: IdGenUtilImpl.scala    From c4proto   with Apache License 2.0 5 votes vote down vote up
package ee.cone.c4actor

import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets.UTF_8
import java.security.MessageDigest
import java.util.Base64

import ee.cone.c4actor.Types.SrcId
import ee.cone.c4di.c4
import okio.ByteString

import scala.collection.immutable.TreeMap

@c4("RichDataCompApp") final case class IdGenUtilImpl()(
  proto: MessageDigest = MessageDigest.getInstance("MD5")
) extends IdGenUtil {
  private def md5(data: Array[Byte]*): String = {
    val d = proto.clone().asInstanceOf[MessageDigest] // much faster than getInstance("MD5")
    data.foreach{ bytes =>
      val l = bytes.length
      d.update((l>>24).toByte)
      d.update((l>>16).toByte)
      d.update((l>> 8).toByte)
      d.update((l>> 0).toByte)
      d.update(bytes)
    }
    Base64.getUrlEncoder.encodeToString(d.digest)
  }
  private def toBytes(value: String): Array[Byte] = value.getBytes(UTF_8)
  private def toBytes(value: Long): Array[Byte] =
    ByteBuffer.allocate(java.lang.Long.BYTES).putLong(value).array()

  def srcIdFromSrcIds(srcIdList: SrcId*): SrcId = md5(srcIdList.map(toBytes):_*)
  def srcIdFromStrings(stringList: String*): SrcId = md5(stringList.map(toBytes):_*)
  def srcIdFromSerialized(adapterId: Long, bytes: ByteString): SrcId =
    md5(toBytes(adapterId),bytes.toByteArray)
} 
Example 10
Source File: Atob.scala    From asura   with MIT License 5 votes vote down vote up
package asura.core.script.function

import java.util.Base64

import scala.concurrent.Future

object Atob extends TransformFunction {

  override val name: String = "atob"
  override val description: String = "Decodes a string of data which has been encoded using base-64 encoding"

  override def apply(arg: Object): Future[String] = {
    Future.successful {
      if (null != arg) {
        new String(Base64.getDecoder().decode(arg.toString))
      } else {
        "null"
      }
    }
  }
} 
Example 11
Source File: SecretsApi.scala    From kubernetes-client   with Apache License 2.0 5 votes vote down vote up
package com.goyeau.kubernetes.client.api

import java.util.Base64
import cats.effect.Sync
import com.goyeau.kubernetes.client.KubeConfig
import com.goyeau.kubernetes.client.operation._
import io.circe._
import io.k8s.api.core.v1.{Secret, SecretList}
import org.http4s.{Status, Uri}
import org.http4s.client.Client
import org.http4s.implicits._
import scala.collection.compat._

private[client] case class SecretsApi[F[_]](httpClient: Client[F], config: KubeConfig)(implicit
    val F: Sync[F],
    val listDecoder: Decoder[SecretList],
    encoder: Encoder[Secret],
    decoder: Decoder[Secret]
) extends Listable[F, SecretList] {
  val resourceUri = uri"/api" / "v1" / "secrets"

  def namespace(namespace: String) = NamespacedSecretsApi(httpClient, config, namespace)
}

private[client] case class NamespacedSecretsApi[F[_]](
    httpClient: Client[F],
    config: KubeConfig,
    namespace: String
)(implicit
    val F: Sync[F],
    val resourceEncoder: Encoder[Secret],
    val resourceDecoder: Decoder[Secret],
    val listDecoder: Decoder[SecretList]
) extends Creatable[F, Secret]
    with Replaceable[F, Secret]
    with Gettable[F, Secret]
    with Listable[F, SecretList]
    with Deletable[F]
    with GroupDeletable[F]
    with Watchable[F, Secret] {
  val resourceUri: Uri = uri"/api" / "v1" / "namespaces" / namespace / "secrets"

  def createEncode(resource: Secret): F[Status] = create(encode(resource))

  def createOrUpdateEncode(resource: Secret): F[Status] =
    createOrUpdate(encode(resource))

  private def encode(resource: Secret) =
    resource.copy(data = resource.data.map(_.view.mapValues(v => Base64.getEncoder.encodeToString(v.getBytes)).toMap))
} 
Example 12
Source File: SqsMessageSpec.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.sqs.queue
import java.util.Base64

import com.amazonaws.services.sqs.model.{Message, MessageAttributeValue}
import org.scalatest.EitherValues
import vinyldns.core.TestRecordSetData.pendingCreateAAAA
import vinyldns.core.TestZoneData.zoneChangePending
import vinyldns.core.domain.batch.BatchChangeCommand
import vinyldns.core.protobuf.ProtobufConversions
import vinyldns.sqs.queue.SqsMessageType.{
  SqsBatchChangeMessage,
  SqsRecordSetChangeMessage,
  SqsZoneChangeMessage
}

import scala.collection.JavaConverters._
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

class SqsMessageSpec extends AnyWordSpec with Matchers with EitherValues with ProtobufConversions {
  import SqsMessage._

  "parseSqsMessage" should {
    "build the command for zone change correctly" in {
      val bytes = toPB(zoneChangePending).toByteArray
      val messageBody = Base64.getEncoder.encodeToString(bytes)
      val msg = new Message()
        .withBody(messageBody)
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsZoneChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(msg).right.value.command shouldBe zoneChangePending
    }

    "build the command for record set change correctly" in {
      val bytes = toPB(pendingCreateAAAA).toByteArray
      val messageBody = Base64.getEncoder.encodeToString(bytes)
      val msg = new Message()
        .withBody(messageBody)
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsRecordSetChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(msg).right.value.command shouldBe pendingCreateAAAA
    }

    "build the command for batch change command correctly" in {
      val batchChangeCommand = BatchChangeCommand("some-id")
      val bytes = batchChangeCommand.id.getBytes
      val messageBody = Base64.getEncoder.encodeToString(bytes)
      val msg = new Message()
        .withBody(messageBody)
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsBatchChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(msg).right.value.command shouldBe batchChangeCommand
    }

    "return EmptySqsMessageContents when processing an empty message" in {
      val message = new Message()
        .withMessageId("test-id")
        .withMessageAttributes(
          Map(
            "message-type" -> new MessageAttributeValue()
              .withStringValue(SqsZoneChangeMessage.name)
              .withDataType("String")
          ).asJava
        )

      parseSqsMessage(message) shouldBe Left(EmptySqsMessageContents(message.getMessageId))
    }
  }
} 
Example 13
Source File: SqsMessage.scala    From vinyldns   with Apache License 2.0 5 votes vote down vote up
package vinyldns.sqs.queue
import java.util.Base64

import cats.implicits._
import com.amazonaws.services.sqs.model.Message
import vinyldns.core.domain.batch.BatchChangeCommand
import vinyldns.core.domain.zone.ZoneCommand
import vinyldns.core.protobuf.ProtobufConversions
import vinyldns.core.queue.{CommandMessage, MessageId}
import vinyldns.proto.VinylDNSProto
import vinyldns.sqs.queue.SqsMessageType.{
  SqsBatchChangeMessage,
  SqsRecordSetChangeMessage,
  SqsZoneChangeMessage
}

final case class SqsMessage(id: MessageId, command: ZoneCommand) extends CommandMessage
object SqsMessage extends ProtobufConversions {
  sealed abstract class SqsMessageError(message: String) extends Throwable(message)
  final case class InvalidSqsMessageContents(messageId: String)
      extends SqsMessageError(s"Unable to parse SQS Message with ID '$messageId'")
  final case class EmptySqsMessageContents(messageId: String)
      extends SqsMessageError(s"No message body found for SQS message with ID '$messageId'")
  final case class InvalidMessageType(className: String)
      extends SqsMessageError(s"Invalid command message type '$className'")

  def parseSqsMessage(message: Message): Either[Throwable, SqsMessage] =
    for {
      messageType <- SqsMessageType.fromMessage(message)
      messageBytes <- Either.fromOption(
        Option(message.getBody),
        EmptySqsMessageContents(message.getMessageId)
      )
      contents <- Either.catchNonFatal(Base64.getDecoder.decode(messageBytes))
      cmd <- Either
        .catchNonFatal {
          messageType match {
            case SqsRecordSetChangeMessage =>
              fromPB(VinylDNSProto.RecordSetChange.parseFrom(contents))
            case SqsZoneChangeMessage => fromPB(VinylDNSProto.ZoneChange.parseFrom(contents))
            case SqsBatchChangeMessage =>
              BatchChangeCommand(new String(contents))
          }
        }
    } yield SqsMessage(MessageId(message.getReceiptHandle), cmd)
} 
Example 14
Source File: package.scala    From hail   with MIT License 5 votes vote down vote up
package is.hail

import java.io._
import java.security.KeyStore
import java.util.Base64

import is.hail.annotations._
import is.hail.asm4s._
import is.hail.types.physical._
import is.hail.io._
import is.hail.utils._
import javax.net.ssl._;

package object shuffler {
  val shuffleBufferSpec = BufferSpec.unblockedUncompressed

  
  def sslContext(
    keyStorePath: String,
    keyStorePassPhrase: String,
    trustStorePath: String,
    trustStorePassPhrase: String
  ): SSLContext = sslContext(
    new FileInputStream(keyStorePath), keyStorePassPhrase,
    new FileInputStream(trustStorePath), trustStorePassPhrase)

  def sslContext(
    keyStoreInputStream: InputStream,
    keyStorePassPhrase: String,
    trustStoreInputStream: InputStream,
    trustStorePassPhrase: String
  ): SSLContext = {
    val ctx = SSLContext.getInstance("TLS")
    val kmf = KeyManagerFactory.getInstance("SunX509")
    val ks = KeyStore.getInstance("PKCS12")
    ks.load(keyStoreInputStream, keyStorePassPhrase.toCharArray())
    kmf.init(ks, keyStorePassPhrase.toCharArray())
    val tmf = TrustManagerFactory.getInstance("SunX509")
    val ts = KeyStore.getInstance("JKS")
    ts.load(trustStoreInputStream, trustStorePassPhrase.toCharArray())
    tmf.init(ts)
    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null)
    ctx
  }

  def rvstr(pt: PType, off: Long): String =
    UnsafeRow.read(pt, null, off).toString

  def writeRegionValueArray(
    encoder: Encoder,
    values: Array[Long]
  ): Unit = {
    var i = 0
    while (i < values.length) {
      encoder.writeByte(1)
      encoder.writeRegionValue(values(i))
      i += 1
    }
    encoder.writeByte(0)
  }

  def readRegionValueArray(
    region: Region,
    decoder: Decoder,
    sizeHint: Int = ArrayBuilder.defaultInitialCapacity
  ): Array[Long] = {
    val ab = new ArrayBuilder[Long](sizeHint)

    var hasNext = decoder.readByte()
    while (hasNext == 1) {
      ab += decoder.readRegionValue(region)
      hasNext = decoder.readByte()
    }
    assert(hasNext == 0, hasNext)

    ab.result()
  }

  private[this] val b64encoder = Base64.getEncoder()

  def uuidToString(uuid: Array[Byte]): String =
    b64encoder.encodeToString(uuid)

  def uuidToString(uuid: Code[Array[Byte]]): Code[String] =
    Code.invokeScalaObject1[Array[Byte], String](getClass, "uuidToString", uuid)
} 
Example 15
Source File: Secrets.scala    From mmlspark   with MIT License 5 votes vote down vote up
import java.io.IOException
import java.util.Base64

import sys.process._
import spray.json._
import DefaultJsonProtocol._
import org.apache.commons.io.IOUtils
import sbt.{SettingKey, TaskKey}

object Secrets {
  private val kvName = "mmlspark-keys"
  private val subscriptionID = "ce1dee05-8cf6-4ad6-990a-9c80868800ba"

  protected def exec(command: String): String = {
    val os = sys.props("os.name").toLowerCase
    os match {
      case x if x contains "windows" => Seq("cmd", "/C") ++ Seq(command) !!
      case _ => command !!
    }
  }

  private def getSecret(secretName: String): String = {
    println(s"fetching secret: $secretName")
    try {
      exec(s"az account set -s $subscriptionID")
      val secretJson = exec(s"az keyvault secret show --vault-name $kvName --name $secretName")
      secretJson.parseJson.asJsObject().fields("value").convertTo[String]
    } catch {
      case _: IOException =>
        println("WARNING: Could not load secret from keyvault, defaulting to the empty string." +
          " Please install az command line to perform authorized build steps like publishing")
        ""
      case _: java.lang.RuntimeException =>
        println("WARNING: Could not load secret from keyvault, defaulting to the empty string." +
          " Please install az command line to perform authorized build steps like publishing")
        ""
    }
  }

  lazy val nexusUsername: String = sys.env.getOrElse("NEXUS-UN", getSecret("nexus-un"))
  lazy val nexusPassword: String = sys.env.getOrElse("NEXUS-PW", getSecret("nexus-pw"))
  lazy val pgpPublic: String = new String(Base64.getDecoder.decode(
    sys.env.getOrElse("PGP-PUBLIC", getSecret("pgp-public")).getBytes("UTF-8")))
  lazy val pgpPrivate: String = new String(Base64.getDecoder.decode(
    sys.env.getOrElse("PGP-PRIVATE", getSecret("pgp-private")).getBytes("UTF-8")))
  lazy val pgpPassword: String = sys.env.getOrElse("PGP-PW", getSecret("pgp-pw"))
  lazy val storageKey: String = sys.env.getOrElse("STORAGE_KEY", getSecret("storage-key"))

} 
Example 16
Source File: Authentication.scala    From coursier   with Apache License 2.0 5 votes vote down vote up
package coursier.core

import java.nio.charset.StandardCharsets
import java.util.Base64

import dataclass.data

@data class Authentication(
  user: String,
  passwordOpt: Option[String],
  httpHeaders: Seq[(String, String)],
  optional: Boolean,
  realmOpt: Option[String],
  httpsOnly: Boolean,
  passOnRedirect: Boolean
) {

  override def toString: String =
    s"Authentication($user, ****, ${httpHeaders.map { case (k, v) => (k, "****") }}, $optional, $realmOpt, $httpsOnly, $passOnRedirect)"


  def withPassword(password: String): Authentication =
    withPasswordOpt(Some(password))
  def withRealm(realm: String): Authentication =
    withRealmOpt(Some(realm))

  def userOnly: Boolean =
    this == Authentication(user)

  def allHttpHeaders: Seq[(String, String)] = {
    val basicAuthHeader = passwordOpt.toSeq.map { p =>
      ("Authorization", "Basic " + Authentication.basicAuthenticationEncode(user, p))
    }
    basicAuthHeader ++ httpHeaders
  }

}

object Authentication {

  def apply(user: String): Authentication =
    Authentication(user, None, Nil, optional = false, None, httpsOnly = true, passOnRedirect = false)
  def apply(user: String, password: String): Authentication =
    Authentication(user, Some(password), Nil, optional = false, None, httpsOnly = true, passOnRedirect = false)

  def apply(
    user: String,
    passwordOpt: Option[String],
    optional: Boolean,
    realmOpt: Option[String],
    httpsOnly: Boolean,
    passOnRedirect: Boolean
  ): Authentication =
    new Authentication(user, passwordOpt, Nil, optional, realmOpt, httpsOnly, passOnRedirect)

  def apply(
    user: String,
    password: String,
    optional: Boolean,
    realmOpt: Option[String],
    httpsOnly: Boolean,
    passOnRedirect: Boolean
  ): Authentication =
    Authentication(user, Some(password), Nil, optional, realmOpt, httpsOnly, passOnRedirect)

  def apply(httpHeaders: Seq[(String, String)]): Authentication =
    Authentication("", None, httpHeaders, optional = false, None, httpsOnly = true, passOnRedirect = false)

  def apply(
    httpHeaders: Seq[(String, String)],
    optional: Boolean,
    realmOpt: Option[String],
    httpsOnly: Boolean,
    passOnRedirect: Boolean
  ): Authentication =
    Authentication("", None, httpHeaders, optional, realmOpt, httpsOnly, passOnRedirect)


  private[coursier] def basicAuthenticationEncode(user: String, password: String): String =
    Base64.getEncoder.encodeToString(
      s"$user:$password".getBytes(StandardCharsets.UTF_8)
    )

} 
Example 17
Source File: PowershellRunner.scala    From coursier   with Apache License 2.0 5 votes vote down vote up
package coursier.env

import java.nio.charset.StandardCharsets
import java.util.Base64
import dataclass.data
import java.io.InputStream
import java.io.ByteArrayOutputStream

@data class PowershellRunner(
  powershellExePath: String = "powershell.exe",
  options: Seq[String] = PowershellRunner.defaultOptions,
  encodeProgram: Boolean = true
) {

  def runScript(script: String): String = {

    // inspired by https://github.com/soc/directories-jvm/blob/1f344ef0087e8422f6c7334317e73b8763d9e483/src/main/java/io/github/soc/directories/Util.java#L147
    val fullScript = "& {\n" +
      "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n" +
      script +
      "\n}"

    val scriptArgs =
      if (encodeProgram) {
        val base64 = Base64.getEncoder()
        val encodedScript = base64.encodeToString(fullScript.getBytes(StandardCharsets.UTF_16LE))
        Seq("-EncodedCommand", encodedScript)
      } else
        Seq("-Command", fullScript)

    val command = Seq(powershellExePath) ++ options ++ scriptArgs

    val b = new ProcessBuilder(command: _*)
      .redirectInput(ProcessBuilder.Redirect.PIPE)
      .redirectOutput(ProcessBuilder.Redirect.PIPE)
      .redirectError(ProcessBuilder.Redirect.INHERIT)
    val p: Process = b.start()
    p.getOutputStream.close()
    val outputBytes = PowershellRunner.readFully(p.getInputStream)
    val retCode = p.waitFor()
    if (retCode == 0)
      new String(outputBytes, StandardCharsets.UTF_8)
    else
      throw new Exception(s"Error running powershell script (exit code: $retCode)")
  }

}

object PowershellRunner {

  def defaultOptions: Seq[String] =
    Seq("-NoProfile", "-NonInteractive")

  private def readFully(is: InputStream): Array[Byte] = {
    val buffer = new ByteArrayOutputStream
    val data = Array.ofDim[Byte](16384)

    var nRead = 0
    while ({
      nRead = is.read(data, 0, data.length)
      nRead != -1
    })
      buffer.write(data, 0, nRead)

    buffer.flush()
    buffer.toByteArray
  }


} 
Example 18
Source File: CryptoSpec.scala    From nexus   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.storage

import java.util.Base64

import ch.epfl.bluebrain.nexus.commons.test.Randomness
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class CryptoSpec extends AnyWordSpecLike with Matchers with Randomness {

  private val accessKey = "AKIAIOSFODNN7EXAMPLE"
  private val secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

  "The Crypto object" should {

    "always generate the same key for a given password" in {
      val key = Crypto.deriveKey("changeme", "salt")
      Base64.getEncoder.encodeToString(key.getEncoded) shouldEqual "FB4G2MHn/q6PXqpNkE1F5wBG7Ndsd9FtyeLcNQL0G40="
      key.getAlgorithm shouldEqual "AES"
      key.getFormat shouldEqual "RAW"
    }

    "encode and decode secrets" in {
      val key = Crypto.deriveKey(genString(32), genString(16))
      Crypto.decrypt(key, Crypto.encrypt(key, accessKey)) shouldEqual accessKey
      Crypto.decrypt(key, Crypto.encrypt(key, secretKey)) shouldEqual secretKey
    }
  }
} 
Example 19
Source File: ZkSnarkBenchmark.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.common

import java.util.Base64
import java.util.concurrent.TimeUnit

import com.wavesplatform.common.ZkSnarkBenchmark.{CurveSt, Groth16St}
import com.wavesplatform.lang.v1.EnvironmentFunctionsBenchmark.{curve25519, randomBytes}
import com.wavesplatform.zwaves.bls12.Groth16
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole
import scorex.crypto.signatures.{Curve25519, Signature}

@OutputTimeUnit(TimeUnit.MICROSECONDS)
@BenchmarkMode(Array(Mode.AverageTime))
@Threads(1)
@Fork(1)
@Warmup(iterations = 10)
@Measurement(iterations = 20)
class ZkSnarkBenchmark {
  @Benchmark
  def groth16(st: Groth16St, bh: Blackhole): Unit =
    bh.consume(Groth16.verify(st.vk, st.proof, st.inputs))

  // for comparison
  @Benchmark
  def sigVerify(st: CurveSt, bh: Blackhole): Unit =
    bh.consume(Curve25519.verify(Signature @@ st.signature, st.message, st.publicKey))
}

object ZkSnarkBenchmark {

  @State(Scope.Benchmark)
  class Groth16St {
    val vk: Array[Byte] = Base64.getDecoder.decode("s6Fw3I8k6rDlE1BJcs833aBONDLHtvx2AWD92/r2qWWc05SGxm+beILW+G2KrB4QpmeojJCTEDqiFAZ4tCkLGppmaiBNRunPepzNtXY+1TPiqRsDdpHP86U7lgng2OAEADUDAFAVbNLRMNzYHbDf7LRppGh2xiQILqHz0OqLU9dcS9vuNQVuVYIQqcUGoObYkPiXh4gEjeojZ/ZHYzBgRMzlqI2cyNPR1uFYHYBgrUtOcOoIueQqyvgii9NynelqEJHSYXFkhefEbegIXinjA9lHKkFuhkHRPW1lqIU7uMofmLTOEON7XyjTZf7HvJ0IoNU368JBygoz97xgjmTGe2R+F2M+tQjnA0qSNV4ve9/RyOmUZLIbvHPnC+HUCFnwGFuJF0LLkNL+LizhD+nRa6uBFgOGNKJo88XwRIjAC+KZOCP3nrxgegS4m/bRxmG6o6a03AlETTySuenJqp79DS7pTiBLmmKi0qCnOMyeiC5N25n4wKkCPDqUxeDfYBlDlRiGpRh8Lt/jHyJAAMdaUQK/bbla1wfBBSkq+WIqgzQRpFAOlP20GgbLlYitIeEpigMdNI7yna6gF/H/yj5AyoyctmX0JaRGs0JMbJXH5LSQjrnds41/8O/EoJzIVvGJt8MBfhtjM8XqRymtkjvo0c7N5PHw3mcVcJqQ5+GMytQ/IhIi7SrIqlesrpbWkG0koDcKMhIZM/EqXWQQApIp2B0w0LyJOjeRe3vg6R08QOJmc/2OiquIX2+3wo9wgmwzk6XX2gc8LF8qWr4m7Kk6qt2OIk2tLZK+2FR7l1+AkGEJ9rAh3KZ01rmTRRQk7BdXkNtxldeVfqs5CH7Tik8jGPEzpq06Aqh56GeG8+JZ+0MQpnidx2WwcNP/RwNQ2K0eiWrcvf2b8Zwq7fan2EmPIckcsQ4TDtcUYlZ/jtv8oQ8AbYVbjxCsb2+ANMbsiGfKojIKcDUqtiWCKA0A15oYvJ1+ypYRFgVFV4W9J0hTDNOAULv4Ir5pjtESEnbipEYilmSIuVIxoxBAQfGdYLfn7ktLcwpTBglFWQD40MGpY52ZWhOuQdGAhb2hiYHY8LLaqEpQKPlE6XjDbMkF32NoyNWLaJaankwoP0dKhxPec1cUp8DmzBDEzA/r7ct6e1TkkjFUNVdbmrPjaH4oywuOYrBjJl4LqS6sn0YtDMfXnDMxbj9hHjyiCvvJzCZoQF4Usz+nxwys9J/ltRjeGofKgQoYD8c6vyib5Zep3swXIP96yRJ4EY9VLx4ZHrKiXmbBkoOsZdZuOScTRqxr2eWXlRZsydm//A7HROZx0LYll/UbASK4RIz5biDG2Z1AIg2bjfCCXX069KgUsnTsrwVlx3XhF/FFje42YP447PvcnEx8vWaXYMIo9nABOOKdZlOipw8mq+/bn1H53vUUYxmGghiJ+cCSNMPLrX8DLKYOL9x5dDcpt2MJWZ7mjQ+lTtUFoNvV8lzQXncyobLubjPaKeGlLA2vPRnmqQSYNZqp+/J6Z7dtIt1btoW30jt0OM8D")
    val proof: Array[Byte] = Base64.getDecoder.decode("tKrzmvZK5lnOj3xbe/3x1Yu8aqPxMnPOawFPM0JWDBH+WDFKBUwlToXaefpY7gkxg14eUONY5rJI3dj6abI7b6gZtgyVP7Xr1HXtMpDX9i5xs4kgXxCcCZ+1ZNox311LEJLQoctW/Qi042T0t1FQ9ZSWUlyZkSEb/l8fC8akq2oEDIFICs+PmuzGdgDuuHndlV09I+bY5hgNhRV1UvteD3W8m7Q0vGO/W/milDXu6u65gch97W2Wwwjj0Ags+j5l")
    val inputs: Array[Byte] = Base64.getDecoder.decode("GCddXmFUIRlXriGVQ1A3t6cwg0w4lmWXGqI+X3mMbmNiO51k5CvrWHd5GOwVb5eb5Imcjj55Q6oKQptRSZqe9TY//vzQ+VNG5bkLiCpTgphYwzXH/GFowK7AjCvy8YhQbFQ1V8sPbpjH8rYlxveMdHW41maMYoW6sJuHpoz1RnNkAyGKRQ0sRUD1n/ohaE/LVLnB4F3cN3cea3MdTmPgPGIWCE5a6oeQRGI/RpKH6kY2BMeuta4jrizVRrcIeFvtYu+j4v31CSmSxiCTHx2SqF/QcSJGnkkdSj9eIZkiO+VjqFi39hRbsfsMYCDUZ8P8QhrYWb+6cFErJ/1PLPjOKFkgBG5pxLo5ifZGjTL5kbtBD6kKritHOHRuANqarO40IiS1yffpaJVrXyJDy0rn2K79XQhyO85tWfK6oT1Q4GwYgxGI9rYyfuKaqrYUbIWPoDCwc9lmSYF9klmjn7LyNDymCC9mmzCiTz4ggzlrR/6DhmJGoDon3wZ5N0jhuCvBPog54HohNv84S1zZLtzEbmlRawFa/q1sl/h5Fl+9KQYyN3SWGN0YIOd3eqtu80UBL8YkOZs8BL6Fgb6KXGULo1VkAHR9q+RSurwCvMqpk/nPzFyZ4MviHxSAmSOUNN2cXzYONrxHZYXGRid1/YxUSukQ57OtwTXsUVIeYG/HTUI=")
  }

  @State(Scope.Benchmark)
  class MerkleSt {
    val root0: Array[Byte] = Base64.getDecoder.decode("YK6g9RXHtw3vE3zmjCGCdLqrij2BwvPCO0E8Bm977ks=")
    val proof0: Array[Byte] = Base64.getDecoder.decode("UU2z52vRH3FTCVwi/C7IIOFz40tZih3P1EarEoM2vsJXWjwtRvpdGjsQl5p/vr1IivKe7cYSdXYs3FcV2R3C2EdPc0IguQwK6bUbVXN1n12KfHPSNfp/V7v9nOWkNiTeA6kMim4Mlj3goV1XuHK9ubsawXZSuDi0HzYaWi5VmxZa4bAzJ4EbgH0sjapX75LRvwCJulQBTpfNKDwi0wG9tybgUmLm53jkOE0DwQaSXJhhY3VsvV1mWW+wQWS1hWjjcS4wHwHwhSb4iFsdV2IQKAD5D8jcBhYj1+yJPITGvKId5FHNHJjkkWFtOMS5BSwz1g5H4Eq1Io/0WVrFBQUk4wQIHxgOMwWRLy6J2RS4vJ5QahhUQZ/OdH3j5z4cMvYqLRaCf+usdX2aZFadMqCDG9FsoLrTwVyW06rB9ToYzhwSrg2XKBzdwwzCE7TXHXnD2Y9bkBty9ZvfSd4htJYFoRa3WJEM8VaOA05xwc0E4GLqTdv8ZC8iDuTQOybnvcRWOD9sWXPdTRunh5XPFwnFSEKCxsWP+D8z44ExsqHH8/IlHHxqhsXgvjP2vI8vJXc5NJHP9mx5Gx6g7xkx5of+bQpa8JJ8ad60KyR88UlAMtn0bZdt5Sdtu5WIb+dCYmYGNNiow56PBg+c6Vs6Oo8sCCsSoK8nXGplshzdBnOmL1YZy5jC13EDORWuYk1PRe1aDLzKzDs1VstRjDp2DWe43SXT+B4DIm4qzc/wElMkfG2QNwel3G75HuxHSxPCa0aLAdPlfFtiAp2Z+Obh5CRXoxZvFUkifIaZ9v/o3H2i6udcJ3y2E05NFCYkjmRHuYYG8/Ktry89FE+S5hKnRuopCgMsbtdafxKW/5qKMnqVNQlcIO4lxqOBW0n2wFm+hhaWXS4+xEl6TxrDyonRz8l3hA3OPrfNVwXSNGqFsBrM9dUpj1l7CcMQ1F2E0XrQoRpPepBvVK22iAjWznSS8HDwSwKtw82edGHgqSGZ2cIS5ebjT6K+RIIJheFH2Sc9zq2MPuhuh+kceQZtCuo0yB8MOlw9ILLfv4BUN+Cf0HXziMQFcMAMd0DDySspFqir0DAzXTz1rIYxQmkVGFOgRDn23ksNt8WxJZV+LorP/vPlSuwtG6XACWsJhWHwNkbgpp0cWdts/QnavsdFhzUwgZq9DLjqHAhz/y/fApNkky4Z51JonZ/lqemNehkT0CygII4iTrkVHZJ7ROUjUguhevoz8wqprf514DNsdYp85PS1j7NSnjoiMl/vdW9PETXxpg95cu7CprJcHE1cfxy/fxFG9jfY6KCw89Nq+mkGwNtwn0YVxyAKDRKimJJ62dK96S3JuVX7Ko9sbYF/VQcHN+VQ+lgWjSUadtDMrVNToNjSbopb0HJ5t6rIdWoX2fQVyLRBCpNpSX5sE0ITadD22N3A3Qyo0hTnjZQldD8ZFVHLlywFCg0K+hiI6ndBXwMcmidciV2Q/DKuOGPjDj9R5GwPllIMafePMeY0GK+yhqcAs3cxezhMIfV1W47DBAkbJr1wUtfxmcH7SaWk1coJam8Gd5m9P5a14khPVn3L+X7eZQMfbUzoVUx9RB4Qc1SGQug5Cyw38iinB6okVp8ZYgkm1R5wGMEbl3+26vRzWhbJkTxN3LLRfu2Bn5JVowFQLj0PbqGSZTJ1E7TIFpDfVd7HOwiDxAD2VsE8Segu5WVLdx9bxPT8r+KhkuuWtq2Mt6ii4R40z30oQ6tEB6IA5DLnelAmFImgKSa7IHAy0cog9A5Wowyd/6s4Pvifi1sjk/8UX4zX15cRdKIwIfdLzWA1viVAiQG/meoNFWr/npHWvg8nEiFLeD86vjQbHK9YEtKRZXTV+4NpnlrsZNpj9Odt8mcx9MuUSrgggRXDWz+xHAdVR28XoyBC0u5Xgm9KQ9ZVXSh9wW3flHA+BZgwJhgILEJKt27L+tJ2z0eFiy1I7Tcosf8CyGonXzg8Nu1cn5iB0YpqIGAGWdsyhIYS5OSWyxpCEGRj/t31sg02jNo8nvsi8c+gpKQmeRVar463OZil")
    val index = 23
    val elements1: Array[Byte] = Base64.getDecoder.decode("GrfbyxFPhfTsam3aY8yqeY072ZrT3DTO8SrSRg4nJZ9nF1OpFPuvXQlcbsqFrGUkgUlokbCealGEw0J8G/H2oWFOY3CHDDhqBQGzUzk+/R3uYljv0YS/Wnb41IKeDSzfDcrJ41FdxBXgptFlh+TM3OKlgJ2jSAF9mqE3v7dUD/1n6conMUMPB+yeP5fapHBGu2OtlDmiHjzuGG6xrrW7tW45mNToh8yTb+POgZP+IvCmf7b8Tzzs0Z9fv998Q5HdXwrH6ts1cC9GBn9GwlWiDxfbKHKE+XS86tNoGPje5MFE7fWtv5XKzkGirbKRuKsBrLDrwl4UwaruqMwk1jJ4jTnsYzLpaGW7nZ46g+Mx5THu8481Kl7zWTFyRXVLIlvCc3eI3oqsjglbnCZ/7xgG4mnlDWqKYBuWzkmm6pCXB0JV7p+/1G7KcT7SIYoWUdf/XPedxh3N3Qgp3xhyh2VpcAMiK9JrMi8j4EQEsxE9Qm58z8aZ+fGBDkEJPaX0TJ1mDQvC4jQH6Sw96KjRLwezomn2Y5rtXcsxqX5UEhuYk39cxPBUX1tC5ap9qn0IPJaQ1Aj7tZvKhm4H1z3zAdwILTzjXYFOE2NyGZub0DY0g16XZKzhOCrtyeSauxm2pRzjNOFKLyEnk8/8a4bAXfODxGA4tCoBlv8ixFGa1agonvVPMc9FP6/S/26YEL491LGZsnqQ5AvvPt1oe/TmcfK/P1AxgsO2chZPqwddisQNRinb8x5NE8ptEWh9He7uutE/LeAGQVN5BYNpEMijP1RDj1FQkDFgglvvh6rgqm7sZr4lh/8wInwzJMMVTN9Dw1uvRHI5Igir1gcvs0vbuqhAf1NRcY5tnD6PxSTl79M1SkTpg1MSmpYJcISdoFNmfq0LVRUyp47f6gjWt+qVkyJAe3xp0GaEmaMKvvj2xVxLdxRRlRRTYABMFjU63LBttYjn0e1qkAvv1JveIrreATBq5Q==")
  }

  @State(Scope.Benchmark)
  class CurveSt {
    val (privateKey, publicKey) = curve25519.generateKeypair
    val message                 = randomBytes(150 * 1024)
    val signature               = curve25519.sign(privateKey, message)
  }
} 
Example 20
Source File: ExampleAuthenticator.scala    From marathon-example-plugins   with Apache License 2.0 5 votes vote down vote up
package mesosphere.marathon.example.plugin.auth

import java.util.Base64

import mesosphere.marathon.plugin.auth.{ Authenticator, Identity }
import mesosphere.marathon.plugin.http.{ HttpRequest, HttpResponse }
import mesosphere.marathon.plugin.plugin.PluginConfiguration
import play.api.libs.json.JsObject

import scala.concurrent.Future

class ExampleAuthenticator extends Authenticator with PluginConfiguration {

  import scala.concurrent.ExecutionContext.Implicits.global

  override def handleNotAuthenticated(request: HttpRequest, response: HttpResponse): Unit = {
    response.status(401)
    response.header("WWW-Authenticate", """Basic realm="Marathon Example Authentication"""")
    response.body("application/json", """{"message": "Not Authenticated!"}""".getBytes("UTF-8"))
  }

  override def authenticate(request: HttpRequest): Future[Option[Identity]] = Future {

    def basicAuth(header: String): Option[(String, String)] = {
      val BasicAuthRegex = "Basic (.+)".r
      val UserPassRegex = "([^:]+):(.+)".r
      header match {
        case BasicAuthRegex(encoded) =>
          val decoded = new String(Base64.getDecoder.decode(encoded))
          val UserPassRegex(username, password) = decoded
          Some(username->password)
        case _ => None
      }
    }

    for {
      auth <- request.header("Authorization").headOption
      (username, password) <- basicAuth(auth)
      identity <- identities.get(username) if identity.password == password
    } yield identity

  }

  private var identities = Map.empty[String, ExampleIdentity]

  override def initialize(marathonInfo: Map[String, Any], configuration: JsObject): Unit = {
    //read all identities from the configuration
    identities = (configuration \ "users").as[Seq[ExampleIdentity]].map(id => id.username -> id).toMap
  }
} 
Example 21
Source File: Encoder.scala    From twitter4s   with Apache License 2.0 5 votes vote down vote up
package com.danielasfregola.twitter4s.util

import java.security.MessageDigest
import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

private[twitter4s] trait Encoder {

  def toHmacSha1(base: String, secret: String): String = {
    val HMAC_SHA1 = "HmacSHA1"
    val UTF8 = "UTF-8"
    val secretKeySpec = new SecretKeySpec(secret.getBytes(UTF8), HMAC_SHA1)
    val mac = Mac.getInstance(HMAC_SHA1)
    mac.init(secretKeySpec)
    val bytesToSign = base.getBytes(UTF8)
    val digest = mac.doFinal(bytesToSign)
    Base64.getEncoder.encodeToString(digest)
  }

  def toBase64(data: Array[Byte]): String =
    Base64.getEncoder.encodeToString(data)

  def toSha1(base: String): String = {
    val SHA1 = "SHA-1"
    val messageDigest = MessageDigest.getInstance(SHA1)
    val bytes = messageDigest.digest(base.getBytes)

    val stringBuffer = new StringBuffer
    bytes.foreach { byte =>
      stringBuffer.append(Integer.toString((byte & 0xff) + 0x100, 16).substring(1))
    }
    stringBuffer.toString
  }

} 
Example 22
Source File: package.scala    From squid   with Apache License 2.0 5 votes vote down vote up
package squid.utils

package object serial {
  // adapted from https://gist.github.com/laughedelic/634f1a1e5333d58085603fcff317f6b4
  
  import java.io._
  import java.util.Base64
  import java.nio.charset.StandardCharsets.UTF_8
  
  def serialize(value: Any): String = {
    val stream: ByteArrayOutputStream = new ByteArrayOutputStream()
    val oos = new ObjectOutputStream(stream)
    oos.writeObject(value)
    oos.close
    new String(
      Base64.getEncoder().encode(stream.toByteArray),
      UTF_8
    )
  }
  
  def deserialize(str: String): Any = {
    val bytes = Base64.getDecoder().decode(str.getBytes(UTF_8))
    val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))
    val value = ois.readObject
    ois.close
    value
  }
  
} 
Example 23
Source File: CodeGeneratorTest.scala    From MoVE   with Mozilla Public License 2.0 5 votes vote down vote up
package de.thm.move.models

import java.io.PrintWriter
import java.net.URI
import java.nio.charset.Charset
import java.nio.file.{Paths, Files}
import java.util.Base64
import javafx.scene.Node
import javafx.scene.paint.{Paint, Color}
import javafx.scene.shape.{LineTo, MoveTo}
import javafx.scene.text.TextAlignment

import de.thm.move.MoveSpec

import de.thm.move.models.ModelicaCodeGenerator.FormatSrc
import de.thm.move.models.ModelicaCodeGenerator.FormatSrc.FormatSrc
import de.thm.move.types._
import de.thm.move.util.ResourceUtils
import de.thm.move.util.GeometryUtils
import de.thm.move.views.shapes._

class CodeGeneratorTest extends MoveSpec {
  val dummyURL = Paths.get(System.getProperty("user.home")).toUri

  private def eqTest(toTest:String,expected:String): Unit = {
    if(!toTest.contains(expected)) {
      println(toTest)
      println("Expected: "+expected)
    }

    assert(toTest.contains(expected), s"Expected [$toTest] containing [$expected]")
  }

  "ModelicaCodeGenerator" should "generate Rectangles" in {
    val generator = new ModelicaCodeGenerator(FormatSrc.Pretty, 1, 500,500)
    val rect = new ResizableRectangle((0,0), 100,100)
    rect.colorizeShape(Color.BLACK, Color.BLACK)
    rect.setRotate(90.0)
    val str = generator.generateShape(rect, "test",  dummyURL)(1)
    eqTest(str, "origin = {50,450}")
    eqTest(str, "extent = {{-50,50}, {50,-50}}")

    val generator2 = new ModelicaCodeGenerator(FormatSrc.Pretty, 4, 500,500)
    val str2 = generator2.generateShape(rect, "test",  dummyURL)(1)
    eqTest(str2, "origin = {12,112}")
    eqTest(str2, "extent = {{-12,12}, {12,-12}}")
  }

  it should "generate Circles" in {
    val generator = new ModelicaCodeGenerator(FormatSrc.Pretty, 1, 500,500)
    val circle = new ResizableCircle((100,100), 50,50)
    circle.colorizeShape(Color.BLACK, Color.BLACK)
    circle.setRotate(90.0)
    val str = generator.generateShape(circle, "test",  dummyURL)(1)
    eqTest(str, "origin = {100,400}")
    eqTest(str, "extent = {{-50,50}, {50,-50}}")
  }
} 
Example 24
Source File: ResourceUtils.scala    From MoVE   with Mozilla Public License 2.0 5 votes vote down vote up
package de.thm.move.util

import java.net.URI
import java.nio.file.{Files, Path, Paths}
import java.util.Base64
import javafx.scene.paint.Color

import de.thm.move.Global._

object ResourceUtils {

  def getFilename(uri:URI):String = {
    val uriStr = uri.toString
    uriStr.substring(uriStr.lastIndexOf("/")+1, uriStr.length)
  }

  def getFilename(p:Path):String = {
    p.getFileName.toString
  }

  def asColor(key:String): Option[Color] =
    config.getString(key).map(Color.web)

  
  def copy(src:URI, target:URI): Unit = {
    val targetPath = Paths.get(target).getParent
    val srcPath = Paths.get(src)
    val filename = srcPath.getFileName
    Files.copy(srcPath, targetPath.resolve(filename))
  }
} 
Example 25
Source File: MultiNodeEtcdConstructrSpec.scala    From constructr   with Apache License 2.0 5 votes vote down vote up
package de.heikoseeberger.constructr

import akka.actor.{ Address, AddressFromURIString }
import io.circe.Json
import io.circe.parser.parse
import java.util.Base64

class MultiNodeEtcdConstructrSpecMultiJvmNode1 extends MultiNodeEtcdConstructrSpec
class MultiNodeEtcdConstructrSpecMultiJvmNode2 extends MultiNodeEtcdConstructrSpec
class MultiNodeEtcdConstructrSpecMultiJvmNode3 extends MultiNodeEtcdConstructrSpec
class MultiNodeEtcdConstructrSpecMultiJvmNode4 extends MultiNodeEtcdConstructrSpec
class MultiNodeEtcdConstructrSpecMultiJvmNode5 extends MultiNodeEtcdConstructrSpec

object MultiNodeEtcdConstructrSpec {
  def toNodes(s: String): Set[Address] = {
    def jsonToNode(json: Json) = {
      val key =
        json.hcursor
          .get[String]("key")
          .fold(throw _, identity)
          .stripPrefix("/constructr/MultiNodeConstructrSpec/nodes/")
      AddressFromURIString(new String(Base64.getUrlDecoder.decode(key)))
    }
    import cats.syntax.either._ // for Scala 2.11
    parse(s)
      .fold(throw _, identity)
      .hcursor
      .downField("node")
      .get[Set[Json]]("nodes")
      .getOrElse(Set.empty)
      .map(jsonToNode)
  }
}

abstract class MultiNodeEtcdConstructrSpec
    extends MultiNodeConstructrSpec(
      2379,
      "/v2/keys/constructr?recursive=true",
      "/v2/keys/constructr/MultiNodeConstructrSpec/nodes",
      MultiNodeEtcdConstructrSpec.toNodes
    ) 
Example 26
Source File: DisplayData.scala    From almond   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package almond.interpreter.api

import java.util.Base64


final case class DisplayData(
  data: Map[String, String],
  metadata: Map[String, String] = Map.empty,
  idOpt: Option[String] = None
) {
  def isEmpty: Boolean =
    data.isEmpty && metadata.isEmpty && idOpt.isEmpty
  def withId(id: String): DisplayData =
    copy(idOpt = Some(id))

  def show()(implicit outputHandler: OutputHandler): Unit =
    outputHandler.display(this)
  def update()(implicit outputHandler: OutputHandler): Unit =
    outputHandler.updateDisplay(this)
}

object DisplayData {

  object ContentType {
    def text = "text/plain"
    def markdown = "text/markdown"
    def html = "text/html"
    def latex = "text/latex"
    def js = "application/javascript"
    def jpg = "image/jpeg"
    def png = "image/png"
    def gif = "image/gif"
    def svg = "image/svg+xml"
  }

  def text(text: String): DisplayData =
    DisplayData(Map(ContentType.text -> text))
  def markdown(content: String): DisplayData =
    DisplayData(Map(ContentType.markdown -> content))
  def html(content: String): DisplayData =
    DisplayData(Map(ContentType.html -> content))
  def latex(content: String): DisplayData =
    DisplayData(Map(ContentType.latex -> content))
  def js(content: String): DisplayData =
    DisplayData(Map(ContentType.js -> content))
  def jpg(content: Array[Byte]): DisplayData =
    DisplayData(Map(ContentType.jpg -> Base64.getEncoder.encodeToString(content)))
  def png(content: Array[Byte]): DisplayData =
    DisplayData(Map(ContentType.png -> Base64.getEncoder.encodeToString(content)))
  def svg(content: String): DisplayData =
    DisplayData(Map(ContentType.svg -> content))

  val empty: DisplayData =
    DisplayData(Map.empty)

  implicit class DisplayDataSyntax(private val s: String) extends AnyVal {
    def asText: DisplayData =
      DisplayData(Map(ContentType.text -> s))
    def as(mimeType: String): DisplayData =
      DisplayData(Map(mimeType -> s))
    def asMarkdown: DisplayData =
      DisplayData(Map(ContentType.markdown -> s))
    def asHtml: DisplayData =
      DisplayData(Map(ContentType.html -> s))
    def asLatex: DisplayData =
      DisplayData(Map(ContentType.latex -> s))
    def asJs: DisplayData =
      DisplayData(Map(ContentType.js -> s))
  }

} 
Example 27
Source File: JsonFileStorage.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.utils

import java.io.{File, PrintWriter}

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import play.api.libs.json.{Json, Reads, Writes}
import java.util.Base64

import scala.io.Source
import scala.util.control.NonFatal

object JsonFileStorage {
  private[this] val KeySalt           = "0495c728-1614-41f6-8ac3-966c22b4a62d"
  private[this] val AES               = "AES"
  private[this] val Algorithm         = AES + "/ECB/PKCS5Padding"
  private[this] val HashingAlgorithm  = "PBKDF2WithHmacSHA512"
  private[this] val HashingIterations = 999999
  private[this] val KeySizeBits       = 128

  def prepareKey(key: String): SecretKeySpec = {
    import java.security.NoSuchAlgorithmException
    import java.security.spec.InvalidKeySpecException

    import javax.crypto.SecretKeyFactory
    import javax.crypto.spec.PBEKeySpec

    def hashPassword(password: Array[Char], salt: Array[Byte], iterations: Int, keyLength: Int): Array[Byte] =
      try {
        val keyFactory = SecretKeyFactory.getInstance(HashingAlgorithm)
        val keySpec    = new PBEKeySpec(password, salt, iterations, keyLength)
        val key        = keyFactory.generateSecret(keySpec)
        key.getEncoded
      } catch {
        case e @ (_: NoSuchAlgorithmException | _: InvalidKeySpecException) =>
          throw new RuntimeException("Password hashing error", e)
      }

    new SecretKeySpec(hashPassword(key.toCharArray, KeySalt.utf8Bytes, HashingIterations, KeySizeBits), AES)
  }

  def save[T](value: T, path: String, key: Option[SecretKeySpec])(implicit w: Writes[T]): Unit = {
    val folder = new File(path).getParentFile
    if (!folder.exists()) folder.mkdirs()

    val file = new PrintWriter(path)
    try {
      val json = Json.toJson(value).toString()
      val data = key.fold(json)(k => encrypt(k, json))
      file.write(data)
    } finally file.close()
  }

  def save[T](value: T, path: String)(implicit w: Writes[T]): Unit =
    save(value, path, None)

  def load[T](path: String, key: Option[SecretKeySpec] = None)(implicit r: Reads[T]): T = {
    val file = Source.fromFile(path)
    try {
      val dataStr = file.mkString
      Json.parse(key.fold(dataStr)(k => decrypt(k, dataStr))).as[T]
    } finally file.close()
  }

  def load[T](path: String)(implicit r: Reads[T]): T =
    load(path, Option.empty[SecretKeySpec])(r)

  private[this] def encrypt(key: SecretKeySpec, value: String): String = {
    try {
      val cipher: Cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.ENCRYPT_MODE, key)
      new String(Base64.getEncoder.encode(cipher.doFinal(value.utf8Bytes)))
    } catch {
      case NonFatal(e) =>
        throw new RuntimeException("File storage encrypt error", e)
    }
  }

  private[this] def decrypt(key: SecretKeySpec, encryptedValue: String): String = {
    try {
      val cipher: Cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.DECRYPT_MODE, key)
      new String(cipher.doFinal(Base64.getDecoder.decode(encryptedValue)))
    } catch {
      case NonFatal(e) =>
        throw new RuntimeException("File storage decrypt error", e)
    }
  }
} 
Example 28
Source File: Base64UUID.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.util

import java.nio.ByteBuffer
import java.util.{Base64, UUID}

object Base64UUID {
  // example output: GGdknrcEQVu3elXyboKcYQ
  def create(): String = {
    def toBase64(uuid: UUID): String = {
      val (high, low) =
        (uuid.getMostSignificantBits, uuid.getLeastSignificantBits)
      val buffer = ByteBuffer.allocate(java.lang.Long.BYTES * 2)
      buffer.putLong(high)
      buffer.putLong(low)
      val encoded = Base64.getMimeEncoder.encodeToString(buffer.array())
      encoded.take(encoded.length - 2)
    }

    var res: String = null
    val allowed = ('a' to 'z').toSet ++ ('A' to 'Z').toSet ++ ('0' to '9').toSet

    while (res == null || res.exists(c => !allowed.contains(c))) {
      val uuid = java.util.UUID.randomUUID()
      res = toBase64(uuid)
    }

    res
  }
} 
Example 29
Source File: CryptoSpec.scala    From nexus-kg   with Apache License 2.0 5 votes vote down vote up
package ch.epfl.bluebrain.nexus.kg.storage

import java.util.Base64

import ch.epfl.bluebrain.nexus.commons.test.Randomness
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class CryptoSpec extends AnyWordSpecLike with Matchers with Randomness {

  private val accessKey = "AKIAIOSFODNN7EXAMPLE"
  private val secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

  "The Crypto object" should {

    "always generate the same key for a given password" in {
      val key = Crypto.deriveKey("changeme", "salt")
      Base64.getEncoder.encodeToString(key.getEncoded) shouldEqual "FB4G2MHn/q6PXqpNkE1F5wBG7Ndsd9FtyeLcNQL0G40="
      key.getAlgorithm shouldEqual "AES"
      key.getFormat shouldEqual "RAW"
    }

    "encode and decode secrets" in {
      val key = Crypto.deriveKey(genString(32), genString(16))
      Crypto.decrypt(key, Crypto.encrypt(key, accessKey)) shouldEqual accessKey
      Crypto.decrypt(key, Crypto.encrypt(key, secretKey)) shouldEqual secretKey
    }
  }
} 
Example 30
Source File: SauceLabsClient.scala    From korolev   with Apache License 2.0 5 votes vote down vote up
package tools

import java.util.Base64

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers._

import scala.concurrent.Await
import scala.concurrent.duration._

class SauceLabsClient(userName: String, accessKey: String, jobId: String)(implicit actorSystem: ActorSystem) {

  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 request = HttpRequest(
      uri = s"https://saucelabs.com/rest/v1/$userName/jobs/$jobId",
      method = HttpMethods.PUT,
      headers = List(Authorization(BasicHttpCredentials(authorization))),
      entity = HttpEntity(ContentTypes.`application/json`, data.getBytes)
    )

    val response = Http()
      .singleRequest(request)

    Await.result(response, 10 seconds)
    ()
  }
} 
Example 31
Source File: ConsulStoreActor.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
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: Class[_] = 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 children(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.flatMap(_.substring(key.length).split('/').headOption)
    }
  }

  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 _                            ⇒ ""
  }
} 
Example 32
Source File: TextUtil.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.common.util

import java.nio.charset.StandardCharsets
import java.util.Base64

object TextUtil {

  
  def toSnakeCase(s: String, dash: Boolean = true): String = {
    var lower = false
    val snake = new StringBuilder

    for (c ← s.toCharArray) {
      val previous = lower
      lower = !Character.isUpperCase(c)
      if (previous && !lower)
        if (dash) snake.append("-") else snake.append("_")
      snake.append(c)
    }

    snake.toString().toLowerCase
  }

  def encodeBase64(data: String): String = Base64.getEncoder.encodeToString(data.getBytes(StandardCharsets.UTF_8))
} 
Example 33
Source File: ProtoUtil.scala    From cloudflow   with Apache License 2.0 5 votes vote down vote up
package cloudflow.streamlets.proto

import java.security.MessageDigest
import java.util.Base64
import scalapb.descriptors.Descriptor
import cloudflow.streamlets.SchemaDefinition

object ProtoUtil {
  val Format = "proto"

  def createSchemaDefinition(descriptor: Descriptor) = SchemaDefinition(
    name = descriptor.fullName,
    schema = descriptor.asProto.toProtoString,
    fingerprint = fingerprintSha256(descriptor),
    format = Format
  )

  private def fingerprintSha256(descriptor: Descriptor): String =
    Base64
      .getEncoder()
      .encodeToString(MessageDigest.getInstance("SHA-256").digest(descriptor.asProto.toProtoString.getBytes("UTF-8")))
} 
Example 34
Source File: AvroUtil.scala    From cloudflow   with Apache License 2.0 5 votes vote down vote up
package cloudflow.streamlets.avro

import scala.util.{ Failure, Success, Try }

import scala.reflect.ClassTag
import scala.reflect._
import org.apache.avro.specific.SpecificRecordBase
import org.apache.avro.Schema
import cloudflow.streamlets._

object AvroUtil {
  val Format = "avro"

  def makeSchema[T <: SpecificRecordBase: ClassTag]: Schema =
    Try(classTag[T].runtimeClass.getDeclaredMethod("SCHEMA$")) match {
      case Success(schema) ⇒ schema.invoke(null).asInstanceOf[Schema]
      case Failure(_) ⇒ {
        Try(classTag[T].runtimeClass.getDeclaredField("SCHEMA$")) match {
          case Success(schema) ⇒ schema.get(null).asInstanceOf[Schema]
          case Failure(ex)     ⇒ throw new RuntimeException(s"Error fetching avro schema for class ${classTag[T].runtimeClass}", ex)
        }
      }
    }
  def fingerprintSha256(schema: Schema): String = {
    import java.util.Base64

    import org.apache.avro.SchemaNormalization._

    Base64
      .getEncoder()
      .encodeToString(parsingFingerprint("SHA-256", schema))
  }

  def createSchemaDefinition(schema: Schema) = SchemaDefinition(
    name = schema.getFullName,
    schema = schema.toString(false),
    fingerprint = fingerprintSha256(schema),
    format = Format
  )
} 
Example 35
Source File: Decoders.scala    From cosmos   with Apache License 2.0 5 votes vote down vote up
package com.mesosphere.cosmos.circe

import cats.syntax.either._
import com.mesosphere.cosmos.error.JsonDecodingError
import com.mesosphere.cosmos.error.JsonParsingError
import com.mesosphere.cosmos.finch.MediaTypedDecoder
import com.mesosphere.error.Result
import com.mesosphere.error.ResultOps
import com.mesosphere.http.MediaType
import io.lemonlabs.uri.Uri
import io.circe.Decoder
import io.circe.DecodingFailure
import io.circe.Error
import io.circe.Json
import io.circe.ParsingFailure
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.Base64
import scala.reflect.ClassTag
import scala.reflect.classTag

object Decoders {

  implicit val decodeUri: Decoder[Uri] = Decoder.decodeString.map(Uri.parse)

  implicit val decodeString: Decoder[String] = {
    Decoder.decodeString.withErrorMessage("String value expected")
  }

  implicit val decodeByteBuffer: Decoder[ByteBuffer] = Decoder.instance { c =>
    c.as[String].bimap(
      { _ => DecodingFailure("Base64 string value expected", c.history) },
      { s => ByteBuffer.wrap(Base64.getDecoder.decode(s)) }
    )
  }

  def decode[T: Decoder: ClassTag](value: String): Result[T] = {
    convertToCosmosError(io.circe.jawn.decode[T](value), value)
  }

  def mediaTypedDecode[T: ClassTag](
    value: String,
    mediaType: MediaType
  )(
    implicit decoder: MediaTypedDecoder[T]
  ): Result[T] = {
    for {
      json <- parse(value)
      result <- decoder(
        json.hcursor,
        mediaType
      )
    } yield result
  }

  def parse(value: String): Result[Json] = {
    convertToCosmosError(io.circe.jawn.parse(value), value)
  }

  def decode64[T: Decoder: ClassTag](value: String): T = {
    decode[T](base64DecodeString(value)).getOrThrow
  }

  def parse64(value: String): Json = {
    parse(base64DecodeString(value)).getOrThrow
  }

  def convertToCosmosError[T: ClassTag](
    result: Either[Error, T],
    inputValue: String
  ): Result[T] = result match {
    case Right(value) => Right(value)
    case Left(ParsingFailure(message, underlying)) =>
      Left(
        JsonParsingError(
          underlying.getClass.getName,
          message,
          inputValue
        )
      )
    case Left(DecodingFailure(message, _)) =>
      Left(
        JsonDecodingError(
          classTag[T].runtimeClass.getName,
          message,
          inputValue
        )
      )
  }

  private[this] def base64DecodeString(value: String): String = {
    new String(Base64.getDecoder.decode(value), StandardCharsets.UTF_8)
  }
} 
Example 36
Source File: MySqlConnector.scala    From asura   with MIT License 5 votes vote down vote up
package asura.core.sql

import java.sql._
import java.util
import java.util.Base64

import asura.common.util.{LogUtils, RSAUtils, StringUtils}
import asura.core.CoreConfig
import asura.core.es.model.SqlRequest.SqlRequestBody
import com.typesafe.scalalogging.Logger

object MySqlConnector {

  val logger = Logger("MySqlConnectors")

  @throws[Throwable]
  def connect(sql: SqlRequestBody): Connection = {
    val url = s"jdbc:mysql://${sql.host}:${sql.port}/${sql.database}?autoReconnect=true&useCursorFetch=true&useUnicode=true&characterEncoding=utf-8"
    try {
      val password = if (StringUtils.isNotEmpty(sql.encryptedPass)) {
        val bytes = Base64.getDecoder.decode(sql.encryptedPass)
        new String(RSAUtils.decryptByPublicKey(bytes, CoreConfig.securityConfig.pubKeyBytes))
      } else {
        sql.password
      }
      DriverManager.getConnection(url, sql.username, password)
    } catch {
      case t: Throwable =>
        logger.error(LogUtils.stackTraceToString(t))
        throw t
    }
  }

  @throws[Throwable]
  def executeUpdate(conn: Connection, sql: String): Integer = {
    val statement = conn.createStatement()
    try {
      statement.executeUpdate(sql)
    } catch {
      case t: Throwable =>
        logger.error(LogUtils.stackTraceToString(t))
        throw t
    } finally {
      statement.close()
    }
  }

  @throws[Throwable]
  def executeQuery(conn: Connection, sql: String): java.util.List[java.util.HashMap[String, Object]] = {
    var statement: Statement = null
    try {
      // https://stackoverflow.com/questions/26046234/is-there-a-mysql-jdbc-that-will-respect-fetchsize
      statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
      statement.setFetchSize(SqlConfig.MAX_ROWS_SIZE)
      val rs = statement.executeQuery(sql)
      val list = new util.ArrayList[util.HashMap[String, Object]]()
      val metaData = rs.getMetaData
      val count = metaData.getColumnCount
      while (rs.next() && list.size() < SqlConfig.MAX_ROWS_SIZE) {
        val row = new util.HashMap[String, Object]()
        for (i <- 1 to count) {
          val value = preserve(metaData, rs, i)
          if (null != value) row.put(metaData.getColumnName(i), value)
        }
        list.add(row)
      }
      list
    } finally {
      if (null != statement) statement.close()
    }
  }

  private def preserve(meta: ResultSetMetaData, rs: ResultSet, col: Int): Object = {
    val className = meta.getColumnClassName(col)
    className match {
      case "java.lang.Long" | "java.lang.Integer" | "java.lang.Short" | "java.lang.Byte"
           | "java.lang.Boolean"
      =>
        rs.getObject(col)
      case _ =>
        rs.getObject(col).toString
    }
  }
} 
Example 37
Source File: NodeIdVectorClockBase64.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.db.versioning

import java.nio.charset.{Charset, StandardCharsets}
import java.util.Base64

import justin.db.consistenthashing.NodeId
import justin.db.vectorclocks.{Counter, VectorClock}
import spray.json.DefaultJsonProtocol._
import spray.json._

import scala.util.Try

object NodeIdVectorClockBase64 {
  val charset: Charset = StandardCharsets.UTF_8
}

class NodeIdVectorClockBase64 {
  import NodeIdVectorClockBase64._

  def encode(vclock: VectorClock[NodeId]): Try[String] = Try {
    val vcClockBytes = vclock.toList
      .map { case (nodeId, counter) => (nodeId.id.toString, counter.value) }
      .toJson
      .compactPrint
      .getBytes(charset)

    Base64.getEncoder.encodeToString(vcClockBytes)
  }

  def decode(base64: String): Try[VectorClock[NodeId]] = Try {
    val decodedMap = new String(Base64.getDecoder.decode(base64), charset)
      .parseJson.convertTo[List[(String, Int)]]
      .map { case (k, v) => (NodeId(k.toInt), Counter(v))}
      .toMap

    VectorClock.apply(decodedMap)
  }
} 
Example 38
Source File: EncryptorActor.scala    From changestream   with MIT License 5 votes vote down vote up
package changestream.actors

import java.nio.charset.Charset
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

import akka.actor.Actor
import com.typesafe.config.{Config, ConfigFactory}
import kamon.Kamon
import org.slf4j.LoggerFactory
import spray.json._

object EncryptorActor {
  case class Plaintext(message: JsObject)
  case class Ciphertext(message: JsObject)
}

class EncryptorActor (
                        config: Config = ConfigFactory.load().getConfig("changestream.encryptor")
                      ) extends Actor {
  import EncryptorActor._

  protected val log = LoggerFactory.getLogger(getClass)
  protected val timingMetric = Kamon.timer("changestream.crypto_time")


  private val charset = Charset.forName("UTF-8")
  private val decoder = Base64.getDecoder
  private val encoder = Base64.getEncoder

  private val cipher = config.getString("cipher")
  private val decodedKey = decoder.decode(config.getString("key"))
  private val originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, cipher)
  private val encryptEngine = Cipher.getInstance(cipher)
  private val decryptEngine = Cipher.getInstance(cipher)

  private val encryptFields = config.getString("encrypt-fields").toLowerCase().split(',').map(_.trim)

  override def preStart() = {
    encryptEngine.init(Cipher.ENCRYPT_MODE, originalKey)
    decryptEngine.init(Cipher.DECRYPT_MODE, originalKey)
  }

  def receive = {
    case Plaintext(message) =>
      val timer = timingMetric.refine("mode" -> "encrypt").start()
      val result = encryptFields(message)
      timer.stop()

      sender() ! result

    case Ciphertext(message) =>
      val timer = timingMetric.refine("mode" -> "decrypt").start()
      val result = decryptFields(message)
      timer.stop()

      sender() ! result
  }

  private def encryptFields(message: JsObject, jsonPath: String = ""): JsObject = {
    JsObject(
      message.fields.map({
        case (k:String, plaintextValue:JsValue) if encryptFields.contains(getNextJsonPath(jsonPath, k)) =>
          val plaintextBytes = plaintextValue.compactPrint.getBytes(charset)
          val cipherText = encryptEngine.doFinal(plaintextBytes)
          val v = encoder.encodeToString(cipherText)
          k -> JsString(v)
        case (k:String, jsObj: JsObject) =>
          k -> encryptFields(jsObj, getNextJsonPath(jsonPath, k))
        case (k:String, v: JsValue) =>
          k -> v
      })
    )
  }

  private def decryptFields(message: JsObject, jsonPath: String = ""): JsObject = {
    JsObject(
      message.fields.map({
        case (k:String, JsString(ciphertextValue)) if encryptFields.contains(getNextJsonPath(jsonPath, k)) =>
          val ciphertextBytes = decoder.decode(ciphertextValue)
          val plaintextBytes = decryptEngine.doFinal(ciphertextBytes)
          val v = new String(plaintextBytes, charset).parseJson
          k -> v
        case (k:String, jsObj: JsObject) =>
          k -> decryptFields(jsObj, getNextJsonPath(jsonPath, k))
        case (k:String, v: JsValue) =>
          k -> v
      })
    )
  }

  private def getNextJsonPath(jsonPath: String, nextPath: String): String = {
    Seq(jsonPath, nextPath).filter(_.nonEmpty).mkString(".")
  }
} 
Example 39
Source File: KeyAuthSrv.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex.services

import java.util.Base64
import javax.inject.{Inject, Singleton}

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random

import play.api.libs.json.JsArray
import play.api.mvc.RequestHeader

import akka.stream.Materializer
import akka.stream.scaladsl.Sink

import org.elastic4play.controllers.Fields
import org.elastic4play.services.{AuthCapability, AuthContext, AuthSrv}
import org.elastic4play.{AuthenticationError, BadRequestError}

@Singleton
class KeyAuthSrv @Inject()(userSrv: UserSrv, implicit val ec: ExecutionContext, implicit val mat: Materializer) extends AuthSrv {
  override val name = "key"

  final protected def generateKey(): String = {
    val bytes = Array.ofDim[Byte](24)
    Random.nextBytes(bytes)
    Base64.getEncoder.encodeToString(bytes)
  }

  override val capabilities = Set(AuthCapability.authByKey)

  override def authenticate(key: String)(implicit request: RequestHeader): Future[AuthContext] = {
    import org.elastic4play.services.QueryDSL._
    // key attribute is sensitive so it is not possible to search on that field
    userSrv
      .find("status" ~= "Ok", Some("all"), Nil)
      ._1
      .filter(_.key().contains(key))
      .runWith(Sink.headOption)
      .flatMap {
        case Some(user) ⇒ userSrv.getFromUser(request, user, name)
        case None       ⇒ Future.failed(AuthenticationError("Authentication failure"))
      }
  }

  override def renewKey(username: String)(implicit authContext: AuthContext): Future[String] = {
    val newKey = generateKey()
    userSrv.update(username, Fields.empty.set("key", newKey)).map(_ ⇒ newKey)
  }

  override def getKey(username: String)(implicit authContext: AuthContext): Future[String] =
    userSrv.get(username).map(_.key().getOrElse(throw BadRequestError(s"User $username hasn't key")))

  override def removeKey(username: String)(implicit authContext: AuthContext): Future[Unit] =
    userSrv.update(username, Fields.empty.set("key", JsArray())).map(_ ⇒ ())
} 
Example 40
Source File: ValueCodecTest.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.codec

import java.nio.charset.StandardCharsets
import java.util.Base64

import wvlet.airframe.codec.PrimitiveCodec.ValueCodec
import wvlet.airframe.msgpack.spi.Value.StringValue
import wvlet.airframe.msgpack.spi.{MessagePack, MsgPack, Value, ValueFactory}

object ValueCodecTest {
  case class ValueTest(v: Value)
  case class RawByteArrayTest(rawByteArray: Array[Byte])
  case class RawMsgpackTest2(msgpack: MsgPack)
}

import wvlet.airframe.codec.ValueCodecTest._


class ValueCodecTest extends CodecSpec {
  scalaJsSupport

  def `support MessagePack values`: Unit = {
    roundtrip(ValueCodec, ValueFactory.newInteger(1), DataType.ANY)
    roundtrip(ValueCodec, ValueFactory.newString("hello msgpack"), DataType.ANY)
    roundtrip(ValueCodec, ValueFactory.newBoolean(true), DataType.ANY)
    roundtrip(ValueCodec, ValueFactory.newFloat(0.1234d), DataType.ANY)
  }

  def `accept value`: Unit = {
    val codec = MessageCodec.of[ValueTest]
    codec.unpackJson("""{"v":"hello msgpack"}""") shouldBe Some(ValueTest(StringValue("hello msgpack")))
  }

  def `support string to Array[Byte] conversion`: Unit = {
    val codec = MessageCodec.of[RawByteArrayTest]
    codec.unpackJson("""{"rawByteArray":"hello msgpack"}""") match {
      case Some(x) =>
        x.rawByteArray shouldBe "hello msgpack".getBytes(StandardCharsets.UTF_8)
      case _ =>
        fail("failed to parse msgpack")
    }
  }

  def `support BASE64-encoded string to Array[Byte] conversion`: Unit = {
    val base64 = Base64.getEncoder.encodeToString("hello msgpack".getBytes(StandardCharsets.UTF_8))
    val codec  = MessageCodec.of[RawByteArrayTest]
    codec.unpackJson(s"""{"rawByteArray":"${base64}"}""") match {
      case Some(x) =>
        x.rawByteArray shouldBe "hello msgpack".getBytes(StandardCharsets.UTF_8)
      case _ =>
        fail("failed to parse msgpack")
    }
  }

  def `accept MsgPack type`: Unit = {
    val codec = MessageCodec.of[RawMsgpackTest2]
    codec.unpackJson("""{"msgpack":"hello msgpack"}""") match {
      case Some(x) =>
        MessagePack.newUnpacker(x.msgpack).unpackValue shouldBe StringValue("hello msgpack")
      case _ =>
        fail("failed to parse msgpack")
    }
  }
} 
Example 41
Source File: Crypto.scala    From dr-cla   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package utils

import java.util.Base64

import javax.crypto.{Cipher, KeyGenerator}
import javax.inject.Inject
import play.api.Configuration

class Crypto @Inject() (configuration: Configuration) {

  private val secretKey = {
    val cryptoSecret = configuration.get[String]("play.http.secret.key")
    val keyGenerator = KeyGenerator.getInstance("AES")
    keyGenerator.init(128)
    keyGenerator.generateKey()
  }

  def encryptAES(plainText: String): String = {
    val plainTextBytes = plainText.getBytes
    val cipher = Cipher.getInstance("AES")
    cipher.init(Cipher.ENCRYPT_MODE, secretKey)
    val encryptedButes = cipher.doFinal(plainTextBytes)
    Base64.getEncoder.encodeToString(encryptedButes)
  }

  def decryptAES(encryptedText: String): String = {
    val encryptedTextBytes = Base64.getDecoder.decode(encryptedText)
    val cipher = Cipher.getInstance("AES")
    cipher.init(Cipher.DECRYPT_MODE, secretKey)
    val decryptedBytes = cipher.doFinal(encryptedTextBytes)
    new String(decryptedBytes)
  }

} 
Example 42
Source File: MockUtil.scala    From scalikejdbc-bigquery   with Apache License 2.0 5 votes vote down vote up
package com.google.cloud.bigquery

import java.util.Base64

import com.google.api.gax.paging.Page
import com.google.cloud.PageImpl
import com.google.cloud.PageImpl.NextPageFetcher
import com.google.cloud.bigquery.FieldValue.Attribute
import scalikejdbc.bigquery.{BqParameter, Format}

import scala.collection.JavaConverters._

object MockUtil {

  def fieldValueFromParameter(parameter: BqParameter, attribute: Attribute = Attribute.PRIMITIVE): FieldValue = {
    val underlying: AnyRef = parameter match {
      case BqParameter.Int64(value) =>
        value.toString
      case BqParameter.Float64(value) =>
        value.toString
      case BqParameter.Bool(value) =>
        value.toString
      case BqParameter.String(value) =>
        value
      case BqParameter.Bytes(value) =>
        // Bytes values are Base64 encoded.
        Base64.getEncoder.encodeToString(value)
      case BqParameter.Date(value) =>
        value.format(Format.date)
      case BqParameter.DateTime(value) =>
        value.format(Format.isoDateTime)
      case BqParameter.Time(value: java.time.LocalTime) =>
        value.format(Format.time)
      case BqParameter.Timestamp(value) =>
        val secPart = value.toEpochSecond
        val fractionPart = value.getNano.toDouble / 1000000000L

        (secPart.toDouble + fractionPart).toString
      // TODO: case Array(value) =>
      // TODO: case Struct() =>
    }

    FieldValue.of(attribute, underlying)
  }

  def tableResultFromSeq(source: Seq[Seq[FieldValue]], schema: Schema): TableResult = {
    val page = new PageImpl(
      new NextPageFetcher[FieldValueList] {
        override def getNextPage: Page[FieldValueList] = null
      },
      "cursor",
      source.map(seq => FieldValueList.of(seq.asJava)).asJava)

    new TableResult(schema, source.size, page)
  }
} 
Example 43
Source File: NRSService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.services

import java.nio.charset.StandardCharsets
import org.joda.time.DateTime
import java.util.Base64

import javax.inject.Inject
import play.api.Logger
import play.api.libs.json.Json
import uk.gov.hmrc.domain.Vrn
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.vatapi.connectors.NRSConnector
import uk.gov.hmrc.vatapi.httpparsers.NrsSubmissionHttpParser.NrsSubmissionOutcome
import uk.gov.hmrc.vatapi.models.{Metadata, NRSSubmission, SearchKeys, VatReturnDeclaration}
import uk.gov.hmrc.vatapi.resources.AuthRequest

import scala.concurrent.{ExecutionContext, Future}


class NRSService @Inject()(
                            nrsConnector: NRSConnector
                          ) {

  val logger: Logger = Logger(this.getClass)

  def submit(vrn: Vrn, submission: NRSSubmission)(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[NrsSubmissionOutcome] = {
    logger.debug(s"[NRSService][submit] - Submitting payload to NRS")
    nrsConnector.submit(vrn, submission)
  }

  def convertToNrsSubmission(vrn: Vrn, payload: VatReturnDeclaration)(implicit request: AuthRequest[_]): NRSSubmission = {

    val encoder = Base64.getEncoder
    NRSSubmission(
      payload = encoder.encodeToString(Json.toJson(payload).toString.getBytes(StandardCharsets.UTF_8)),
      metadata = Metadata(
        businessId = "vat",
        notableEvent = "vat-return",
        payloadContentType = "application/json",
        payloadSha256Checksum = None,
        userSubmissionTimestamp = DateTime.now(),
        identityData = request.authContext.identityData,
        userAuthToken = request.headers.get("Authorization").get,
        headerData = Json.toJson(request.headers.toMap.map { h => h._1 -> h._2.head }),
        searchKeys = SearchKeys(
          vrn = Some(vrn),
          periodKey = Some(payload.periodKey)
        )
      )
    )
  }
} 
Example 44
Source File: NrsService.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.services

import java.nio.charset.StandardCharsets
import java.util.Base64

import cats.data.EitherT
import cats.implicits._
import javax.inject.Inject
import org.joda.time.DateTime
import play.api.libs.json.Json
import uk.gov.hmrc.http.HeaderCarrier
import v1.connectors.NrsConnector
import v1.controllers.UserRequest
import v1.models.errors.{DownstreamError, ErrorWrapper}
import v1.models.nrs.request.{Metadata, NrsSubmission, SearchKeys}
import v1.models.nrs.response.NrsResponse
import v1.models.request.submit.SubmitRequest

import scala.concurrent.{ExecutionContext, Future}

class NrsService @Inject()(connector: NrsConnector) {

  def submitNrs(vatSubmission: SubmitRequest, submissionTimestamp: DateTime)(
    implicit request: UserRequest[_],
    hc: HeaderCarrier,
    ec: ExecutionContext): Future[Either[ErrorWrapper, NrsResponse]] = {

    val result = for {
      nrsResponse <- EitherT(connector.submitNrs(buildNrsSubmission(vatSubmission, submissionTimestamp, request)))
        .leftMap(_ => ErrorWrapper(None, DownstreamError, None))
    } yield nrsResponse

    result.value
  }

  def buildNrsSubmission(vatSubmission: SubmitRequest, submissionTimestamp: DateTime, request: UserRequest[_]): NrsSubmission = {

    import vatSubmission._

    val payloadString: String =
      Base64.getEncoder.encodeToString(
        Json.toJson(body)
          .toString()
          .getBytes(StandardCharsets.UTF_8)
      )

    NrsSubmission(
      payload = payloadString,
      Metadata(
        businessId = "vat",
        notableEvent = "vat-return",
        payloadContentType = "application/json",
        payloadSha256Checksum = None,
        userSubmissionTimestamp = submissionTimestamp,
        identityData = request.userDetails.identityData,
        userAuthToken = request.headers.get("Authorization").get,
        headerData = Json.toJson(request.headers.toMap.map { h => h._1 -> h._2.head }),
        searchKeys =
          SearchKeys(
            vrn = Some(vrn.vrn),
            companyName = None,
            periodKey = body.periodKey,
            taxPeriodEndDate = None
          )
      )
    )
  }
} 
Example 45
Source File: ConsulHttpProtocol.scala    From reactive-consul   with MIT License 5 votes vote down vote up
package stormlantern.consul.client.dao

import java.util.UUID

import spray.json._

import scala.util.control.NonFatal
import java.util.Base64

trait ConsulHttpProtocol extends DefaultJsonProtocol {

  implicit val uuidFormat = new JsonFormat[UUID] {
    override def read(json: JsValue): UUID = json match {
      case JsString(uuid) ⇒ try {
        UUID.fromString(uuid)
      } catch {
        case NonFatal(e) ⇒ deserializationError("Expected UUID, but got " + uuid)
      }
      case x ⇒ deserializationError("Expected UUID as JsString, but got " + x)
    }

    override def write(obj: UUID): JsValue = JsString(obj.toString)
  }

  implicit val binaryDataFormat = new JsonFormat[BinaryData] {
    override def read(json: JsValue): BinaryData = json match {
      case JsString(data) ⇒ try {
        BinaryData(Base64.getMimeDecoder.decode(data))
      } catch {
        case NonFatal(e) ⇒ deserializationError("Expected base64 encoded binary data, but got " + data)
      }
      case x ⇒ deserializationError("Expected base64 encoded binary data as JsString, but got " + x)
    }

    override def write(obj: BinaryData): JsValue = JsString(Base64.getMimeEncoder.encodeToString(obj.data))
  }

  implicit val serviceFormat = jsonFormat(
    (node: String, address: String, serviceId: String, serviceName: String, serviceTags: Option[Set[String]], serviceAddress: String, servicePort: Int) ⇒
      ServiceInstance(node, address, serviceId, serviceName, serviceTags.getOrElse(Set.empty), serviceAddress, servicePort),
    "Node", "Address", "ServiceID", "ServiceName", "ServiceTags", "ServiceAddress", "ServicePort"
  )
  implicit val httpCheckFormat = jsonFormat(HttpHealthCheck, "HTTP", "Interval")
  implicit val scriptCheckFormat = jsonFormat(ScriptHealthCheck, "Script", "Interval")
  implicit val ttlCheckFormat = jsonFormat(TTLHealthCheck, "TTL")
  implicit val checkWriter = lift {
    new JsonWriter[HealthCheck] {
      override def write(obj: HealthCheck): JsValue = obj match {
        case obj: ScriptHealthCheck ⇒ obj.toJson
        case obj: HttpHealthCheck   ⇒ obj.toJson
        case obj: TTLHealthCheck    ⇒ obj.toJson
      }
    }
  }
  implicit val serviceRegistrationFormat = jsonFormat(ServiceRegistration, "Name", "ID", "Tags", "Address", "Port", "Check")
  implicit val sessionCreationFormat = jsonFormat(SessionCreation, "LockDelay", "Name", "Node", "Checks", "Behavior", "TTL")
  implicit val keyDataFormat = jsonFormat(KeyData, "Key", "CreateIndex", "ModifyIndex", "LockIndex", "Flags", "Value", "Session")
  implicit val sessionInfoFormat = jsonFormat(SessionInfo, "LockDelay", "Checks", "Node", "ID", "CreateIndex", "Name", "Behavior", "TTL")
} 
Example 46
Source File: BasicAuthentication.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.scalaj.client

import java.util.Base64

import endpoints4s.{Tupler, algebra}
import endpoints4s.algebra.BasicAuthentication.Credentials
import endpoints4s.algebra.Documentation


trait BasicAuthentication extends algebra.BasicAuthentication with EndpointsWithCustomErrors {

  private[endpoints4s] def authenticatedRequest[U, E, H, UE, HCred, Out](
      method: Method,
      url: Url[U],
      entity: RequestEntity[E],
      headers: RequestHeaders[H],
      requestDocs: Documentation
  )(implicit
      tuplerUE: Tupler.Aux[U, E, UE],
      tuplerHCred: Tupler.Aux[H, Credentials, HCred],
      tuplerUEHCred: Tupler.Aux[UE, HCred, Out]
  ): Request[Out] = {
    val basicAuthenticationHeader: RequestHeaders[Credentials] =
      (credentials) => {
        Seq(
          (
            "Authorization",
            "Basic " + new String(
              Base64.getEncoder.encode(
                (credentials.username + ":" + credentials.password).getBytes
              )
            )
          )
        )
      }

    request(
      method,
      url,
      entity,
      requestDocs,
      headers ++ basicAuthenticationHeader
    )
  }

} 
Example 47
Source File: BasicAuthAuthenticatedAction.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package controllers.auth

import java.util.Base64

import play.api.{Configuration, Logging}
import play.api.mvc._

import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.Exception.allCatch

class BasicAuthAuthenticatedAction(parser: BodyParsers.Default, appConfig: Configuration)(implicit ec: ExecutionContext)
  extends ActionBuilderImpl(parser) with Logging {

  logger.debug("In BasicAuthAuthenticatedAction")

  val BASIC_AUTH_USER = appConfig.getOptional[String]("smui.BasicAuthAuthenticatedAction.user") match {
    case Some(strUser: String) =>
      strUser
    case None =>
      logger.error(":: No value for smui.BasicAuthAuthenticatedAction.user found. Setting user to super-default.")
      "smui"
  }

  val BASIC_AUTH_PASS = appConfig.getOptional[String]("smui.BasicAuthAuthenticatedAction.pass") match {
    case Some(strUser: String) =>
      strUser
    case None =>
      logger.error(":: No value for smui.BasicAuthAuthenticatedAction.pass found. Setting pass to super-default.")
      "smui"
  }

  override def invokeBlock[A](request: Request[A], block: Request[A] => Future[Result]): Future[Result] = {

    logger.debug(s":: invokeBlock :: request.path = ${request.path}")

    
    def requestAuthenticated(request: Request[A]): Boolean = {

      request.headers.get("Authorization") match {
        case Some(authorization: String) =>
          authorization.split(" ").drop(1).headOption.filter { encoded =>
            val authInfo = new String(Base64.getDecoder().decode(encoded.getBytes)).split(":").toList
            allCatch.opt {
              val (username, password) = (authInfo.head, authInfo(1))
              username.equals(BASIC_AUTH_USER) && password.equals(BASIC_AUTH_PASS)
            } getOrElse false
          }.exists(_ => true)
        case None => false
      }
    }

    if (requestAuthenticated(request)) {
      block(request)
    } else {
      Future {
        // TODO return error JSON with authorization violation details, redirect target eventually (instead of empty 401 body)
        Results.Unauthorized("401 Unauthorized").withHeaders(("WWW-Authenticate", "Basic realm=SMUI"))
      }
    }
  }
} 
Example 48
Source File: XmlProcessing.scala    From akka_streams_tutorial   with MIT License 5 votes vote down vote up
package alpakka.xml

import java.nio.file.Paths
import java.util.Base64

import akka.actor.ActorSystem
import akka.stream.alpakka.xml.scaladsl.XmlParsing
import akka.stream.alpakka.xml.{EndElement, ParseEvent, StartElement, TextEvent}
import akka.stream.scaladsl.{FileIO, Sink, Source}
import akka.util.ByteString

import scala.collection.immutable
import scala.concurrent.Future
import scala.util.{Failure, Success}



object XmlProcessing extends App {
  implicit val system = ActorSystem("XmlProcessing")
  implicit val executionContext = system.dispatcher

  val resultFileName = "testfile_result.jpg"

  val done = FileIO.fromPath(Paths.get("./src/main/resources/xml_with_base64_embedded.xml"))
    .via(XmlParsing.parser)
    .statefulMapConcat(() => {

      // state
      val stringBuilder: StringBuilder = StringBuilder.newBuilder
      var counter: Int = 0

      // aggregation function
      parseEvent: ParseEvent =>
        parseEvent match {
          case s: StartElement if s.attributes.contains("mediaType") =>
            stringBuilder.clear()
            val mediaType = s.attributes.head._2
            println("mediaType: " + mediaType)
            immutable.Seq(mediaType)
          case s: EndElement if s.localName == "embeddedDoc" =>
            val text = stringBuilder.toString
            println("File content: " + text) //large embedded files are read into memory
            Source.single(ByteString(text))
              .map(each => ByteString(Base64.getMimeDecoder.decode(each.toByteBuffer)))
              .runWith(FileIO.toPath(Paths.get(s"$counter-$resultFileName")))
            counter = counter + 1
            immutable.Seq(text)
          case t: TextEvent =>
            stringBuilder.append(t.text)
            immutable.Seq.empty
          case _ =>
            immutable.Seq.empty
        }
    })
    .runWith(Sink.ignore)

  terminateWhen(done)


  def terminateWhen(done: Future[_]) = {
    done.onComplete {
      case Success(_) =>
        println("Flow Success. About to terminate...")
        system.terminate()
      case Failure(e) =>
        println(s"Flow Failure: $e. About to terminate...")
        system.terminate()
    }
  }
} 
Example 49
Source File: DefaultInstanceAliasConverter.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.rpc.instancealias.impl

import java.util.Base64
import java.util.regex.Pattern

import com.webank.wedatasphere.linkis.rpc.instancealias.InstanceAliasConverter
import org.apache.commons.lang.StringUtils
import org.springframework.stereotype.Component


@Component
class DefaultInstanceAliasConverter extends InstanceAliasConverter  {

  val pattern = Pattern.compile("[a-zA-Z\\d=\\+/]+")

  // todo use base64 for the moment
  override def instanceToAlias(instance: String): String = {
    new String(Base64.getEncoder.encode(instance.getBytes()))
  }

  override def aliasToInstance(alias: String): String = {
    new String(Base64.getDecoder.decode(alias))
  }

  override def checkAliasFormatValid(alias: String): Boolean = {
    if (StringUtils.isBlank(alias)) {
      return false
    }
    val matcher = pattern.matcher(alias)
    matcher.find()
  }
} 
Example 50
Source File: Iot_managerSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import java.io.{IOException, File => JFile}
import java.net.ServerSocket
import java.util.Base64

import better.files._
import it.gov.daf.iotmanager.client.Iot_managerClient
import org.specs2.mutable.Specification
import org.specs2.specification.BeforeAfterAll
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.ahc.AhcWSClient
import play.api.libs.ws.{WSAuthScheme, WSResponse}
import play.api.test.{WithServer, WsTestClient}

import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.util.{Failure, Try}

import org.apache.solr.client.solrj.embedded.JettyConfig
import org.apache.solr.client.solrj.embedded.JettySolrRunner
import org.eclipse.jetty.servlet.ServletHolder


@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw"))
class Iot_managerSpec extends Specification with BeforeAfterAll {

  import Iot_managerSpec._

  def getAvailablePort: Int = {
    try {
      val socket = new ServerSocket(0)
      try {
        socket.getLocalPort
      } finally {
        socket.close()
      }
    } catch {
      case e: IOException =>
        throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e)
    }
  }

  def application: Application = GuiceApplicationBuilder().
    configure("hadoop_conf_dir" -> s"${ServiceSpec.confPath.pathAsString}").
    configure("pac4j.authenticator" -> "test").
    build()

  "The security_manager" should {
    "manage user tokens correctly" in new WithServer(app = application, port = getAvailablePort) {
      print("ciao ciao")


    }
  }

  override def beforeAll(): Unit = {
    val solrXml = new Nothing("/solr/home/solr.xml")
    val solrHomeDir = solrXml.getParentFile

    val port = 8080
    val context = "/solr"
    // use org.apache.solr.client.solrj.embedded.JettySolrRunner
    val jettySolr = new Nothing(solrHomeDir.getAbsolutePath, context, port)

    val waitUntilTheSolrWebAppHasStarted = true
    jettySolr.start(waitUntilTheSolrWebAppHasStarted)
  }

  override def afterAll(): Unit = {
    jettySolr.stop()
  }
}

@SuppressWarnings(Array("org.wartremover.warts.Var", "org.wartremover.warts.Null"))
object Iot_managerSpec {



} 
Example 51
Source File: ServiceSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import java.io.{IOException, File => JFile}
import java.net.ServerSocket
import java.util.Base64

import it.gov.daf.securitymanager.client.Security_managerClient
import org.specs2.mutable.Specification
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.ahc.AhcWSClient
import play.api.libs.ws.{WSAuthScheme, WSResponse}
import play.api.test.{WithServer, WsTestClient}

import scala.concurrent.Await
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.duration.Duration

//@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Throw"))
class ServiceSpec extends Specification {

  def getAvailablePort: Int = {
    try {
      val socket = new ServerSocket(0)
      try {
        socket.getLocalPort
      } finally {
        socket.close()
      }
    } catch {
      case e: IOException =>
        throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e)
    }
  }

  def application: Application = GuiceApplicationBuilder().
    configure("pac4j.authenticator" -> "test").
    build()

  "The security_manager" should {
    "manage user tokens correctly" in new WithServer(app = application, port = getAvailablePort) {

      private val token = WsTestClient.withClient { implicit client =>
        val response: WSResponse = Await.result[WSResponse](client.
          url(s"http://localhost:$port/security-manager/v1/token").
          withAuth("david", "david", WSAuthScheme.BASIC).
          execute, Duration.Inf)
        response.body
      }

      val ws: AhcWSClient = AhcWSClient()

      val plainCreds = "david:david"
      val plainCredsBytes = plainCreds.getBytes
      val base64CredsBytes = Base64.getEncoder.encode(plainCredsBytes)
      val base64Creds = new String(base64CredsBytes)

      val client = new Security_managerClient(ws)(s"http://localhost:$port")

      val token2 = Await.result(client.token(s"Basic $base64Creds"), Duration.Inf)

      s""""$token2"""" must be equalTo token

      Await.result(client.token(s"Bearer $token2").map(token => s""""$token""""), Duration.Inf) must be equalTo token
    }
  }

} 
Example 52
Source File: ServiceSpec.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import java.io.{File, FileNotFoundException, IOException}
import java.net.ServerSocket
import java.util.Base64

import it.gov.daf.entitymanager.Entity
import it.gov.daf.entitymanager.client.Entity_managerClient
import org.specs2.mutable.Specification
import org.specs2.specification.BeforeAfterAll
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.ahc.AhcWSClient
import play.api.test.WithServer

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.{Failure, Random, Try}

@SuppressWarnings(
  Array(
    "org.wartremover.warts.NonUnitStatements",
    "org.wartremover.warts.Throw",
    "org.wartremover.warts.Var"
  )
)
class ServiceSpec extends Specification with BeforeAfterAll {

  def getAvailablePort: Int = {
    try {
      val socket = new ServerSocket(0)
      try {
        socket.getLocalPort
      } finally {
        socket.close()
      }
    } catch {
      case e: IOException =>
        throw new IllegalStateException(s"Cannot find available port: ${e.getMessage}", e)
    }
  }

  private def constructTempDir(dirPrefix: String): Try[File] = Try {
    val rndrange = 10000000
    val file = new File(System.getProperty("java.io.tmpdir"), s"$dirPrefix${Random.nextInt(rndrange)}")
    if (!file.mkdirs())
      throw new RuntimeException("could not create temp directory: " + file.getAbsolutePath)
    file.deleteOnExit()
    file
  }

  private def deleteDirectory(path: File): Boolean = {
    if (!path.exists()) {
      throw new FileNotFoundException(path.getAbsolutePath)
    }
    var ret = true
    if (path.isDirectory)
      path.listFiles().foreach(f => ret = ret && deleteDirectory(f))
    ret && path.delete()
  }

  var tmpDir: Try[File] = Failure[File](new Exception(""))
  
  def application: Application = GuiceApplicationBuilder().
    configure("pac4j.authenticator" -> "test").
    configure("janusgraph.storage.directory" -> s"${tmpDir.map(_.getCanonicalPath).getOrElse("db")}/berkeleyje").
    configure("janusgraph.index.search.directory" -> s"${tmpDir.map(_.getCanonicalPath).getOrElse("db")}/lucene").
    build()

  "The entity_manager" should {
    "create an entity and retrieve it correctly" in new WithServer(app = application, port = getAvailablePort) {

      val ws: AhcWSClient = AhcWSClient()

      val plainCreds = "david:david"
      val plainCredsBytes = plainCreds.getBytes
      val base64CredsBytes = Base64.getEncoder.encode(plainCredsBytes)
      val base64Creds = new String(base64CredsBytes)

      val client = new Entity_managerClient(ws)(s"http://localhost:$port")

      val result = Await.result(client.createEntity(s"Basic $base64Creds", Entity("DAVID")), Duration.Inf)
      val entity = Await.result(client.getEntity(s"Basic $base64Creds", "DAVID"), Duration.Inf)

      entity must beEqualTo(Entity("DAVID"))
    }
  }

  override def beforeAll(): Unit = tmpDir = constructTempDir("test")

  override def afterAll(): Unit = tmpDir.foreach(deleteDirectory(_))
} 
Example 53
Source File: HasJwt.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.it.api.websockets

import java.security
import java.security.KeyPairGenerator
import java.util.Base64

import com.typesafe.config.{Config, ConfigFactory}
import com.wavesplatform.dex.api.ws.protocol.WsAddressSubscribe.JwtPayload
import com.wavesplatform.dex.auth.JwtUtils
import com.wavesplatform.dex.domain.account.KeyPair
import play.api.libs.json.Json

import scala.concurrent.duration.{FiniteDuration, _}

trait HasJwt extends JwtUtils {

  protected val authServiceKeyPair: security.KeyPair = {
    val kpg = KeyPairGenerator.getInstance("RSA")
    kpg.initialize(2048)
    kpg.generateKeyPair()
  }

  protected def jwtPublicKeyConfig: Config = ConfigFactory.parseString(
    s"""waves.dex.web-sockets.external-client-handler.jwt-public-key = \"\"\"-----BEGIN PUBLIC KEY-----
       |${Base64.getEncoder.encodeToString(authServiceKeyPair.getPublic.getEncoded).grouped(64).mkString("\n")}
       |-----END PUBLIC KEY-----\"\"\"
       |""".stripMargin
  )

  protected def mkJwt(payload: JwtPayload): String = mkJwt(authServiceKeyPair, Json.toJsObject(payload))

  protected def mkJwt(clientKeyPair: KeyPair, lifetime: FiniteDuration = 1.hour): String = {
    mkJwt(mkJwtSignedPayload(clientKeyPair, lifetime = lifetime))
  }
} 
Example 54
Source File: GatlingFeeder.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.load

import java.io.{File, PrintWriter}
import java.security
import java.security.KeyFactory
import java.security.spec.PKCS8EncodedKeySpec
import java.util.Base64

import com.wavesplatform.dex.api.ws.protocol.WsAddressSubscribe.JwtPayload
import com.wavesplatform.dex.auth.JwtUtils
import com.wavesplatform.dex.domain.account.{AddressScheme, PrivateKey, PublicKey}
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.wavesj.PrivateKeyAccount
import play.api.libs.json.Json

import scala.concurrent.duration._
import scala.io.Source
import scala.util.Random

object GatlingFeeder {

  def authServiceKeyPair(rawPrivateKey: String): security.PrivateKey = {
    val privateKeyContent = rawPrivateKey
      .replace("-----BEGIN PRIVATE KEY-----", "")
      .replace("-----END PRIVATE KEY-----", "")
      .replaceAll("\\n", "")

    val kf         = KeyFactory.getInstance("RSA")
    val ksPkcs8    = new PKCS8EncodedKeySpec(Base64.getDecoder.decode(privateKeyContent))
    val privateKey = kf.generatePrivate(ksPkcs8)

    privateKey
  }

  private def mkJwtSignedPayload(a: PrivateKeyAccount): JwtPayload = {
    val exp = System.currentTimeMillis() / 1000 + 24.hour.toSeconds
    JwtPayload(
      signature = ByteStr(Array.emptyByteArray),
      publicKey = PublicKey(a.getPublicKey),
      networkByte = AddressScheme.current.chainId.toChar.toString,
      clientId = "test",
      firstTokenExpirationInSeconds = exp,
      activeTokenExpirationInSeconds = exp,
      scope = List("general")
    ).signed(PrivateKey(a.getPrivateKey))
  }

  private def mkAusString(accountPrivateKey: PrivateKeyAccount, authKp: security.PrivateKey): String = {
    s"""{"T":"aus","S":"${accountPrivateKey.getAddress}","t":"jwt","j":"${JwtUtils.mkJwt(authKp,
                                                                                         Json.toJsObject(mkJwtSignedPayload(accountPrivateKey)))}"}"""
  }

  private def mkObsStrings(pairsFile: File, numberPerClient: Int): String = {
    val source = Source.fromFile(pairsFile)
    try {
      val pairs = Random.shuffle(source.getLines.toVector)
      require(numberPerClient <= pairs.size, "numberPerClient > available asset pairs in file")
      pairs.take(numberPerClient).map(x => s"""{"T":"obs","S":"$x","d":100}""").mkString(";")
    } finally source.close()
  }

  def mkFile(accountsNumber: Int,
             seedPrefix: String,
             authKp: security.PrivateKey,
             pairsFile: File,
             orderBookNumberPerAccount: Int,
             feederFile: File): Unit = {
    val output = new PrintWriter(feederFile, "utf-8")
    try {
      (0 until accountsNumber).foreach { i =>
        val pk = PrivateKeyAccount.fromSeed(s"$seedPrefix$i", 0, AddressScheme.current.chainId)
        output.println(s"""${pk.getAddress};${mkAusString(pk, authKp)};${mkObsStrings(pairsFile, orderBookNumberPerAccount)}""")
      }
    } finally output.close()
    println(s"Results have been saved to $feederFile")
  }
} 
Example 55
package com.ivan.nikolov.structural.decorator

import java.io.{BufferedInputStream, InputStreamReader, BufferedReader, ByteArrayOutputStream}
import java.nio.charset.Charset
import java.util.Base64
import java.util.zip.GZIPOutputStream

import com.ivan.nikolov.structural.decorator.common.{AdvancedInputReader, InputReader}
import com.typesafe.scalalogging.LazyLogging

trait CapitalizedInputReaderTrait extends InputReader {
  abstract override def readLines(): Stream[String] = super.readLines().map(_.toUpperCase)
}

trait CompressingInputReaderTrait extends InputReader with LazyLogging {
  abstract override def readLines(): Stream[String] = super.readLines().map {
    case line =>
      val text = line.getBytes(Charset.forName("UTF-8"))
      logger.info("Length before compression: {}", text.length.toString)
      val output = new ByteArrayOutputStream()
      val compressor = new GZIPOutputStream(output)
      try {
        compressor.write(text, 0, text.length)
        val outputByteArray = output.toByteArray
        logger.info("Length after compression: {}", outputByteArray.length.toString)
        new String(outputByteArray, Charset.forName("UTF-8"))
      } finally {
        compressor.close()
        output.close()
      }
  }
}

trait Base64EncoderInputReaderTrait extends InputReader {
  abstract override def readLines(): Stream[String] = super.readLines().map {
    case line => Base64.getEncoder.encodeToString(line.getBytes(Charset.forName("UTF-8")))
  }
}

object StackableTraitsExample {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new AdvancedInputReader(stream) with CapitalizedInputReaderTrait
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
}

object StackableTraitsBigExample {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new AdvancedInputReader(stream) with CapitalizedInputReaderTrait with Base64EncoderInputReaderTrait with CompressingInputReaderTrait
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
} 
Example 56
Source File: Runtime.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.api
package runtime

import javax.imageio.ImageIO
import java.io.{ByteArrayOutputStream, File}
import java.util.Base64
import java.awt.image.BufferedImage

import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Runtime extends SharedRuntime {
  def render[T](a: T)(implicit _ct: ClassTag[T] = null, _tt: TypeTag[T] = null): Render = {
    val ct = Option(_ct)
    val tt = Option(_tt)
    super.render(a, tt.map(_.tpe.toString).orElse(ct.map(_.toString)).getOrElse(""))
  }

  def image(path: String): Html = {
    val in = ImageIO.read(new File(path))
    toBase64(in)
  }

  def toBase64(in: BufferedImage): Html = {
    val width = in.getWidth
    val os = new ByteArrayOutputStream
    val b64 = Base64.getEncoder.wrap(os)
    ImageIO.write(in, "png", b64)
    val encoded = os.toString("UTF-8")

    Html(
      s"""
      <div style="width:${width}px; margin:0 auto">
        <image src="data:image/png;base64,$encoded">
      </div>
      """,
      folded = true
    )
  }
} 
Example 57
Source File: PlantUMLRenderer.scala    From gitbucket-plantuml-plugin   with Apache License 2.0 5 votes vote down vote up
package com.yotaichino.gitbucket.plugins.plantuml

import gitbucket.core.plugin.Renderer
import gitbucket.core.plugin.RenderRequest
import gitbucket.core.util.StringUtil
import java.nio.charset.Charset
import java.util.Base64
import play.twirl.api.Html

class PlantUMLRenderer extends Renderer {

  override def render(request: RenderRequest): Html = {
    Html(imgEmbedded(request.fileContent))
  }

  def imgEmbedded(content: String): String = {
    val raw = PlantUMLUtils.generateSVGImage(content)
    raw match {
      case null => {
        val c = StringUtil.escapeHtml(content)
        s"""<pre class="prettyprint linenums blob">$c</pre>"""
      }
      case _ => {
        val src = Base64.getEncoder.encodeToString(raw)
        s"""<img src="data:image/svg+xml;charset=utf-8;base64,$src">"""
      }
    }
  }
} 
Example 58
Source File: CirceEncodersDecoders.scala    From jsoniter-scala   with MIT License 5 votes vote down vote up
package com.github.plokhotnyuk.jsoniter_scala.benchmark

import java.time.Instant
import java.util.Base64

import com.github.plokhotnyuk.jsoniter_scala.benchmark.BitMask.toBitMask
import io.circe.Decoder._
import io.circe.Encoder._
import io.circe._
import io.circe.generic.extras._
import io.circe.generic.extras.decoding.UnwrappedDecoder
import io.circe.generic.extras.encoding.UnwrappedEncoder
import io.circe.generic.extras.semiauto._

import scala.collection.immutable.{BitSet, IntMap}
import scala.collection.mutable
import scala.util.Try

object CirceEncodersDecoders {
  val printer: Printer = Printer.noSpaces.copy(dropNullValues = true, reuseWriters = true, predictSize = true)
  val prettyPrinter: Printer = Printer.spaces2.copy(dropNullValues = true, reuseWriters = true, predictSize = true)
  val escapingPrinter: Printer = printer.copy(escapeNonAscii = true)
  implicit val config: Configuration = Configuration.default.withDefaults.withDiscriminator("type")
  implicit val adtC3c: Codec[ADTBase] = deriveConfiguredCodec[ADTBase]
  implicit val anyValsC3c: Codec[AnyVals] = {
    implicit def valueClassEncoder[A <: AnyVal : UnwrappedEncoder]: Encoder[A] = implicitly

    implicit def valueClassDecoder[A <: AnyVal : UnwrappedDecoder]: Decoder[A] = implicitly

    deriveConfiguredCodec[AnyVals]
  }
  val (base64D5r: Decoder[Array[Byte]], base64E5r: Encoder[Array[Byte]]) =
    (Decoder.decodeString.map[Array[Byte]](Base64.getDecoder.decode),
      Encoder.encodeString.contramap[Array[Byte]](Base64.getEncoder.encodeToString))
  implicit val bidRequestC3c: Codec[OpenRTB.BidRequest] = {
    import io.circe.generic.extras.auto._

    deriveConfiguredCodec[OpenRTB.BidRequest]
  }
  implicit val bigIntE5r: Encoder[BigInt] = encodeJsonNumber
    .contramap(x => JsonNumber.fromDecimalStringUnsafe(new java.math.BigDecimal(x.bigInteger).toPlainString))
  implicit val (bitSetD5r: Decoder[BitSet], bitSetE5r: Encoder[BitSet]) =
    (Decoder.decodeArray[Int].map(arr => BitSet.fromBitMaskNoCopy(toBitMask(arr, Int.MaxValue ))),
      Encoder.encodeSeq[Int].contramapArray((m: mutable.BitSet) => m.toVector))
  implicit val distanceMatrixC3c: Codec[GoogleMapsAPI.DistanceMatrix] = {
    import io.circe.generic.auto._

    deriveConfiguredCodec[GoogleMapsAPI.DistanceMatrix]
  }
  implicit val gitHubActionsAPIC3c: Codec[GitHubActionsAPI.Response] = {
    implicit val c1: Codec[GitHubActionsAPI.Artifact] =
      Codec.forProduct9("id", "node_id", "name", "size_in_bytes", "url", "archive_download_url",
        "expired", "created_at", "expires_at") {
        (id: Long, node_id: String, name: String, size_in_bytes: Long, url: String, archive_download_url: String,
        expired: String, created_at: Instant, expires_at: Instant) =>
          GitHubActionsAPI.Artifact(id, node_id, name, size_in_bytes, url, archive_download_url,
            expired.toBoolean, created_at, expires_at)
      } { a =>
        (a.id, a.node_id, a.name, a.size_in_bytes, a.url, a.archive_download_url,
        a.expired.toString, a.created_at, a.expires_at)
      }
    deriveConfiguredCodec[GitHubActionsAPI.Response]
  }
  implicit val extractFieldsC3c: Codec[ExtractFields] = deriveConfiguredCodec[ExtractFields]
  implicit val geoJSONC3c: Codec[GeoJSON.GeoJSON] = {
    implicit val c1: Codec[GeoJSON.SimpleGeometry] = deriveConfiguredCodec[GeoJSON.SimpleGeometry]
    implicit val c2: Codec[GeoJSON.Geometry] = deriveConfiguredCodec[GeoJSON.Geometry]
    implicit val c3: Codec[GeoJSON.SimpleGeoJSON] = deriveConfiguredCodec[GeoJSON.SimpleGeoJSON]
    deriveConfiguredCodec[GeoJSON.GeoJSON]
  }
  implicit val (intMapD5r: Decoder[IntMap[Boolean]], intMapE5r: Encoder[IntMap[Boolean]]) =
    (Decoder.decodeMap[Int, Boolean].map(_.foldLeft(IntMap.empty[Boolean])((m, p) => m.updated(p._1, p._2))),
      Encoder.encodeMap[Int, Boolean].contramapObject((m: IntMap[Boolean]) => m))
  implicit val (longMapD5r: Decoder[mutable.LongMap[Boolean]], longMapE5r: Encoder[mutable.LongMap[Boolean]]) =
    (Decoder.decodeMap[Long, Boolean].map(_.foldLeft(new mutable.LongMap[Boolean])((m, p) => m += (p._1, p._2))),
      Encoder.encodeMapLike[Long, Boolean, mutable.Map].contramapObject((m: mutable.LongMap[Boolean]) => m))
  implicit val missingRequiredFieldsC3c: Codec[MissingRequiredFields] = deriveConfiguredCodec[MissingRequiredFields]
  implicit val nestedStructsC3c: Codec[NestedStructs] = deriveConfiguredCodec[NestedStructs]
  implicit val (suitD5r: Decoder[Suit], suitE5r: Encoder[Suit]) =
    (decodeString.emap(s => Try(Suit.valueOf(s)).fold[Either[String, Suit]](_ => Left("Suit"), Right.apply)),
      encodeString.contramap[Suit](_.name))
  implicit val suitADTC3c: Codec[SuitADT] = deriveEnumerationCodec[SuitADT]
  implicit val (suitEnumDecoder: Decoder[SuitEnum.Value], suitEnumEncoder: Encoder[SuitEnum.Value]) =
    (decodeEnumeration(SuitEnum), encodeEnumeration(SuitEnum))
  implicit val primitivesC3c: Codec[Primitives] = deriveConfiguredCodec[Primitives]
  implicit val tweetC3c: Codec[TwitterAPI.Tweet] = {
    import io.circe.generic.auto._

    deriveConfiguredCodec[TwitterAPI.Tweet]
  }
} 
Example 59
Source File: Base64Benchmark.scala    From jsoniter-scala   with MIT License 5 votes vote down vote up
package com.github.plokhotnyuk.jsoniter_scala.benchmark

import java.nio.charset.StandardCharsets.UTF_8
import java.util.Base64

import org.openjdk.jmh.annotations.{Param, Setup}

abstract class Base64Benchmark extends CommonParams {
  @Param(Array("1", "10", "100", "1000", "10000", "100000", "1000000"))
  var size: Int = 1000
  var obj: Array[Byte] = _
  var jsonString: String = _
  var jsonBytes: Array[Byte] = _
  var preallocatedBuf: Array[Byte] = _

  @Setup
  def setup(): Unit = {
    obj = (1 to size).map(_.toByte).toArray
    jsonString = "\"" + Base64.getEncoder.encodeToString(obj) + "\""
    jsonBytes = jsonString.getBytes(UTF_8)
    preallocatedBuf = new Array[Byte](jsonBytes.length + 100)
  }
} 
Example 60
Source File: RequestFilters.scala    From fintrospect   with Apache License 2.0 5 votes vote down vote up
package io.fintrospect.filters

import java.nio.charset.StandardCharsets.ISO_8859_1
import java.util.Base64

import com.twitter.finagle.Filter
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.util.Future
import io.fintrospect.ContentType.fromAcceptHeaders
import io.fintrospect.configuration.{Authority, Credentials}
import io.fintrospect.formats.Argo.ResponseBuilder._
import io.fintrospect.renderers.ModuleRenderer
import io.fintrospect.renderers.simplejson.SimpleJson
import io.fintrospect.util.{Extracted, Extraction, ExtractionFailed, Extractor}
import io.fintrospect.{ContentType, ContentTypes}
import io.netty.handler.codec.http.HttpHeaderNames


  def ExtractBody[I](extractor: Extractor[Request, I])
                    (implicit moduleRenderer: ModuleRenderer = SimpleJson()):
  Filter[Request, Response, I, Response] = Filter.mk[Request, Response, I, Response] {
    (req, svc) => {
      extractor <--? req match {
        case Extracted(x) => svc(x)
        case ExtractionFailed(invalid) => Future(moduleRenderer.badRequest(invalid))
      }
    }
  }
}


object A extends App {
  println(HttpHeaderNames.USER_AGENT.toString)
} 
Example 61
Source File: InputReaderDecorator.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.structural.decorator

import java.io.{InputStreamReader, BufferedInputStream, ByteArrayOutputStream, BufferedReader}
import java.nio.charset.Charset
import java.util.Base64
import java.util.zip.GZIPOutputStream

import com.ivan.nikolov.structural.decorator.common.{AdvancedInputReader, InputReader}
import com.typesafe.scalalogging.LazyLogging

abstract class InputReaderDecorator(inputReader: InputReader) extends InputReader {
  override def readLines(): Stream[String] = inputReader.readLines()
}

class CapitalizedInputReader(inputReader: InputReader) extends InputReaderDecorator(inputReader) {
  override def readLines(): Stream[String] = super.readLines().map(_.toUpperCase)
}

class CompressingInputReader(inputReader: InputReader) extends InputReaderDecorator(inputReader) with LazyLogging {
  override def readLines(): Stream[String] = super.readLines().map {
    case line =>
      val text = line.getBytes(Charset.forName("UTF-8"))
      logger.info("Length before compression: {}", text.length.toString)
      val output = new ByteArrayOutputStream()
      val compressor = new GZIPOutputStream(output)
      try {
        compressor.write(text, 0, text.length)
        val outputByteArray = output.toByteArray
        logger.info("Length after compression: {}", outputByteArray.length.toString)
        new String(outputByteArray, Charset.forName("UTF-8"))
      } finally {
        compressor.close()
        output.close()
      }
  }
}

class Base64EncoderInputReader(inputReader: InputReader) extends InputReaderDecorator(inputReader) {
  override def readLines(): Stream[String] = super.readLines().map {
    case line => Base64.getEncoder.encodeToString(line.getBytes(Charset.forName("UTF-8")))
  }
}

object DecoratorExample {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new CapitalizedInputReader(new AdvancedInputReader(stream))
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
}

object DecoratorExampleBig {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new CompressingInputReader(
        new Base64EncoderInputReader(
          new CapitalizedInputReader(
            new AdvancedInputReader(stream)
          )
        )
      )
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
} 
Example 62
package com.ivan.nikolov.structural.decorator

import java.io.{BufferedInputStream, InputStreamReader, BufferedReader, ByteArrayOutputStream}
import java.nio.charset.Charset
import java.util.Base64
import java.util.zip.GZIPOutputStream

import com.ivan.nikolov.structural.decorator.common.{AdvancedInputReader, InputReader}
import com.typesafe.scalalogging.LazyLogging

trait CapitalizedInputReaderTrait extends InputReader {
  abstract override def readLines(): Stream[String] = super.readLines().map(_.toUpperCase)
}

trait CompressingInputReaderTrait extends InputReader with LazyLogging {
  abstract override def readLines(): Stream[String] = super.readLines().map {
    case line =>
      val text = line.getBytes(Charset.forName("UTF-8"))
      logger.info("Length before compression: {}", text.length.toString)
      val output = new ByteArrayOutputStream()
      val compressor = new GZIPOutputStream(output)
      try {
        compressor.write(text, 0, text.length)
        val outputByteArray = output.toByteArray
        logger.info("Length after compression: {}", outputByteArray.length.toString)
        new String(outputByteArray, Charset.forName("UTF-8"))
      } finally {
        compressor.close()
        output.close()
      }
  }
}

trait Base64EncoderInputReaderTrait extends InputReader {
  abstract override def readLines(): Stream[String] = super.readLines().map {
    case line => Base64.getEncoder.encodeToString(line.getBytes(Charset.forName("UTF-8")))
  }
}

object StackableTraitsExample {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new AdvancedInputReader(stream) with CapitalizedInputReaderTrait
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
}

object StackableTraitsBigExample {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new AdvancedInputReader(stream) with CapitalizedInputReaderTrait with Base64EncoderInputReaderTrait with CompressingInputReaderTrait
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
} 
Example 63
Source File: InputReaderDecorator.scala    From Scala-Design-Patterns-Second-Edition   with MIT License 5 votes vote down vote up
package com.ivan.nikolov.structural.decorator

import java.io.{InputStreamReader, BufferedInputStream, ByteArrayOutputStream, BufferedReader}
import java.nio.charset.Charset
import java.util.Base64
import java.util.zip.GZIPOutputStream

import com.ivan.nikolov.structural.decorator.common.{AdvancedInputReader, InputReader}
import com.typesafe.scalalogging.LazyLogging

abstract class InputReaderDecorator(inputReader: InputReader) extends InputReader {
  override def readLines(): Stream[String] = inputReader.readLines()
}

class CapitalizedInputReader(inputReader: InputReader) extends InputReaderDecorator(inputReader) {
  override def readLines(): Stream[String] = super.readLines().map(_.toUpperCase)
}

class CompressingInputReader(inputReader: InputReader) extends InputReaderDecorator(inputReader) with LazyLogging {
  override def readLines(): Stream[String] = super.readLines().map {
    case line =>
      val text = line.getBytes(Charset.forName("UTF-8"))
      logger.info("Length before compression: {}", text.length.toString)
      val output = new ByteArrayOutputStream()
      val compressor = new GZIPOutputStream(output)
      try {
        compressor.write(text, 0, text.length)
        val outputByteArray = output.toByteArray
        logger.info("Length after compression: {}", outputByteArray.length.toString)
        new String(outputByteArray, Charset.forName("UTF-8"))
      } finally {
        compressor.close()
        output.close()
      }
  }
}

class Base64EncoderInputReader(inputReader: InputReader) extends InputReaderDecorator(inputReader) {
  override def readLines(): Stream[String] = super.readLines().map {
    case line => Base64.getEncoder.encodeToString(line.getBytes(Charset.forName("UTF-8")))
  }
}

object DecoratorExample {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new CapitalizedInputReader(new AdvancedInputReader(stream))
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
}

object DecoratorExampleBig {
  def main(args: Array[String]): Unit = {
    val stream = new BufferedReader(
      new InputStreamReader(
        new BufferedInputStream(this.getClass.getResourceAsStream("data.txt"))
      )
    )
    try {
      val reader = new CompressingInputReader(
        new Base64EncoderInputReader(
          new CapitalizedInputReader(
            new AdvancedInputReader(stream)
          )
        )
      )
      reader.readLines().foreach(println)
    } finally {
      stream.close()
    }
  }
} 
Example 64
Source File: AccountStorage.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.db

import java.io.{File, FileInputStream, FileOutputStream}
import java.nio.file.Files
import java.util.Base64

import cats.syntax.either._
import com.google.common.primitives.{Bytes, Ints}
import com.wavesplatform.dex.crypto.Enigma
import com.wavesplatform.dex.db.AccountStorage.Settings.EncryptedFile
import com.wavesplatform.dex.domain.account.KeyPair
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.dex.domain.crypto
import net.ceedubs.ficus.readers.ValueReader

import scala.collection.mutable.ArrayBuffer

case class AccountStorage(keyPair: KeyPair)

object AccountStorage {

  sealed trait Settings

  object Settings {

    case class InMem(seed: ByteStr)                        extends Settings
    case class EncryptedFile(path: File, password: String) extends Settings

    implicit val valueReader: ValueReader[Settings] = ValueReader.relative[Settings] { config =>
      config.getString("type") match {
        case "in-mem" => InMem(Base64.getDecoder.decode(config.getString("in-mem.seed-in-base64")))
        case "encrypted-file" =>
          EncryptedFile(
            path = new File(config.getString("encrypted-file.path")),
            password = config.getString("encrypted-file.password")
          )
        case x => throw new IllegalArgumentException(s"The type of account storage '$x' is unknown. Please update your settings.")
      }
    }
  }

  def load(settings: Settings): Either[String, AccountStorage] = settings match {
    case Settings.InMem(seed) => Right(AccountStorage(KeyPair(seed)))
    case Settings.EncryptedFile(file, password) =>
      if (file.isFile) {
        val encryptedSeedBytes = readFile(file)
        val key                = Enigma.prepareDefaultKey(password)
        val decryptedBytes     = Enigma.decrypt(key, encryptedSeedBytes)
        AccountStorage(KeyPair(decryptedBytes)).asRight
      } else s"A file '${file.getAbsolutePath}' doesn't exist".asLeft
  }

  def save(seed: ByteStr, to: EncryptedFile): Unit = {
    Files.createDirectories(to.path.getParentFile.toPath)
    val key                = Enigma.prepareDefaultKey(to.password)
    val encryptedSeedBytes = Enigma.encrypt(key, seed.arr)
    writeFile(to.path, encryptedSeedBytes)
  }

  def getAccountSeed(baseSeed: ByteStr, nonce: Int): ByteStr = ByteStr(crypto.secureHash(Bytes.concat(Ints.toByteArray(nonce), baseSeed)))

  def readFile(file: File): Array[Byte] = {
    val reader = new FileInputStream(file)
    try {
      val buff = new Array[Byte](1024)
      val r    = new ArrayBuffer[Byte]
      while (reader.available() > 0) {
        val read = reader.read(buff)
        if (read > 0) {
          r.appendAll(buff.iterator.take(read))
        }
      }
      r.toArray
    } finally {
      reader.close()
    }
  }

  def writeFile(file: File, bytes: Array[Byte]): Unit = {
    val writer = new FileOutputStream(file, false)
    try writer.write(bytes)
    finally writer.close()
  }
} 
Example 65
Source File: PaginationToken.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.datamodel

import com.azavea.stac4s.meta._
import eu.timepit.refined.types.numeric.PosInt
import io.circe.generic.semiauto._
import io.circe.parser._
import io.circe.refined._
import io.circe.syntax._
import io.circe.{Decoder, Encoder}
import sttp.tapir.DecodeResult

import java.time.Instant
import java.util.Base64

final case class PaginationToken(
    timestampAtLeast: Instant,
    serialIdGreaterThan: PosInt
)

object PaginationToken {

  implicit class ToTapirDecodeResult[T](circeResult: Either[io.circe.Error, T]) {

    def toDecodeResult: DecodeResult[T] = {
      circeResult match {
        case Left(err) =>
          DecodeResult.Error(err.getMessage, err)
        case Right(value) =>
          DecodeResult.Value(value)
      }
    }
  }

  implicit val dec: Decoder[PaginationToken] = deriveDecoder
  implicit val enc: Encoder[PaginationToken] = deriveEncoder

  val b64Encoder = Base64.getEncoder()
  val b64Decoder = Base64.getDecoder()

  def encPaginationToken(token: PaginationToken): String = b64Encoder.encodeToString(
    token.asJson.noSpaces.getBytes
  )

  def decPaginationToken(encoded: String): DecodeResult[PaginationToken] = {
    val jsonString: String = new String(b64Decoder.decode(encoded))
    val circeResult = for {
      js      <- parse(jsonString)
      decoded <- js.as[PaginationToken]
    } yield decoded
    circeResult.toDecodeResult
  }

} 
Example 66
Source File: stringWrappers.scala    From play-swagger   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import java.util.Base64

import scala.language.implicitConversions


case class Base64String(value: String) {
  override val toString: String = Base64String.base64string2string(this)
}

object Base64String {
  implicit def string2base64string(s: String): Base64String =
    Base64String(new String(Base64.getEncoder.encode(s.getBytes)))
  implicit def base64string2string(s: Base64String): String =
    new String(Base64.getDecoder.decode(s.value))
}

case class BinaryString(value: Array[Byte])

object BinaryString {
  def fromString(s: String): BinaryString = BinaryString(s.getBytes)
  implicit def binaryString2String(s: BinaryString): String = new String(s.value)
  implicit def byteArray2binaryString(s: Array[Byte]): BinaryString = BinaryString(s)
  implicit def binaryString2byteArray(s: BinaryString): Array[Byte] = s.value
} 
Example 67
Source File: GameManager.scala    From telegram   with Apache License 2.0 5 votes vote down vote up
package com.bot4s.telegram.api

import java.net.URLDecoder
import java.nio.charset.StandardCharsets
import java.util.Base64

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive1, Route}
import com.bot4s.telegram.marshalling
import com.bot4s.telegram.methods.{GetGameHighScores, SetGameScore}
import com.bot4s.telegram.models.{CallbackQuery, ChatId, User}
import com.bot4s.telegram.future.BotExecutionContext
import io.circe.generic.extras.semiauto._
import io.circe.generic.semiauto.deriveDecoder
import io.circe.{Decoder, Encoder}

import scala.concurrent.Future
import scala.util.{Failure, Success}


case class Payload(
                    user            : User,
                    chatId          : Option[ChatId] = None,
                    messageId       : Option[Int] = None,
                    inlineMessageId : Option[String] = None,
                    gameManagerHost : String,
                    gameShortName   : String) {

  def toGetGameHighScores = GetGameHighScores(user.id, chatId, messageId, inlineMessageId)

  def base64Encode: String = {
    val payloadJson = marshalling.toJson[Payload](this)
    val encodedPayload = Base64.getEncoder.encodeToString(
      payloadJson.getBytes(StandardCharsets.UTF_8))

    encodedPayload
  }
}

object Payload {

  def base64Decode(encodedPayload: String): Payload = {
    val base64payload = URLDecoder.decode(encodedPayload, "UTF-8")
    val jsonPayload = new String(Base64.getDecoder.decode(base64payload),
      StandardCharsets.UTF_8)
    val payload = marshalling.fromJson[Payload](jsonPayload)

    payload
  }

  def forCallbackQuery(gameManagerHost: String)(implicit cbq: CallbackQuery): Payload = {
    Payload(
      cbq.from,
      cbq.message.map(_.source),
      cbq.message.map(_.messageId),
      cbq.inlineMessageId,
      gameManagerHost,
      cbq.gameShortName.get) // throws if not a game callback
  }

  import marshalling._
  implicit val payloadEncoder: Encoder[Payload] = deriveEncoder[Payload]
  implicit val payloadDecoder: Decoder[Payload] = deriveDecoder[Payload]
} 
Example 68
Source File: SessionUtil.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.session

import java.math.BigInteger
import java.util.Base64
import java.util.concurrent.ThreadLocalRandom

object SessionUtil {
  def randomString(length: Int): String = {
    // http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
    val random = ThreadLocalRandom.current()
    new BigInteger(length * 5, random).toString(32) // because 2^5 = 32
  }

  
  def randomServerSecret(): String = randomString(128)

  // Do not change this unless you understand the security issues behind timing attacks.
  // This method intentionally runs in constant time if the two strings have the same length.
  // If it didn't, it would be vulnerable to a timing attack.
  def constantTimeEquals(a: String, b: String): Boolean = {
    if (a.length != b.length) {
      false
    } else {
      var equal = 0
      for (i <- Array.range(0, a.length)) {
        equal |= a(i) ^ b(i)
      }
      equal == 0
    }
  }

  private val HexArray = "0123456789ABCDEF".toCharArray

  def toHexString(bytes: Array[Byte]): String = {
    // from https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
    val hexChars = new Array[Char](bytes.length * 2)
    var j = 0
    while (j < bytes.length) {
      val v = bytes(j) & 0xFF
      hexChars(j * 2) = HexArray(v >>> 4)
      hexChars(j * 2 + 1) = HexArray(v & 0x0F)
      j += 1
    }
    new String(hexChars)
  }

  def hexStringToByte(hexString: String): Array[Byte] = {
    // https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
    val len = hexString.length
    val data = new Array[Byte](len / 2)
    var i = 0
    while (i < len) {
      data(i / 2) = ((Character.digit(hexString.charAt(i), 16) << 4) +
        Character.digit(hexString.charAt(i + 1), 16)).toByte
      i += 2
    }

    data
  }

  def toBase64_v0_5_2(bytes: Array[Byte]): String = {
    Base64.getUrlEncoder.encodeToString(bytes)
  }

  def parseBase64_v0_5_2(s: String): Array[Byte] = {
    Base64.getUrlDecoder.decode(s)
  }
} 
Example 69
Source File: JwsAlgorithm.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.session

import java.nio.charset.StandardCharsets.UTF_8
import java.security.spec.PKCS8EncodedKeySpec
import java.security.{KeyFactory, PrivateKey, Signature}
import java.util.Base64

import com.typesafe.config.Config
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import scala.util.{Failure, Success, Try}

sealed trait JwsAlgorithm {
  def value: String
  def sign(message: String): String

  protected def encode(bytes: Array[Byte]): String =
    Base64.getUrlEncoder.withoutPadding().encodeToString(bytes)
}

object JwsAlgorithm {

  case class Rsa(privateKey: PrivateKey) extends JwsAlgorithm {

    override val value: String = "RS256"

    override def sign(message: String): String = {
      val privateSignature: Signature = Signature.getInstance("SHA256withRSA")
      privateSignature.initSign(privateKey)
      privateSignature.update(message.getBytes(UTF_8))

      encode(privateSignature.sign())
    }
  }

  object Rsa {

    def fromConfig(jwsConfig: Config): Try[Rsa] = {

      def readKeyFromConf(): Try[String] = {
        val configKey = "rsa-private-key"
        Option(jwsConfig.hasPath(configKey))
          .filter(identity)
          .flatMap(_ => Option(jwsConfig.getString(configKey)))
          .filter(_.trim.nonEmpty)
          .map(_.replaceAll("\\s", "").replaceAll("-----[^-]+-----", ""))
          .map(Success(_))
          .getOrElse(Failure(new IllegalArgumentException(
            "akka.http.session.jws.rsa-private-key must be defined in order to use alg = RS256")))
      }

      readKeyFromConf()
        .flatMap { key =>
          Try {
            val keyFactory = KeyFactory.getInstance("RSA")
            val privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder.decode(key)))
            Rsa(privateKey)
          }.recoverWith {
            case ex => Failure(new IllegalArgumentException("Invalid RSA private key", ex))
          }
        }
    }
  }

  case class HmacSHA256(serverSecret: String) extends JwsAlgorithm {
    override val value: String = "HS256"
    override def sign(message: String): String = {
      val key = serverSecret.getBytes("UTF-8")
      val mac = Mac.getInstance("HmacSHA256")
      mac.init(new SecretKeySpec(key, "HmacSHA256"))
      encode(mac.doFinal(message.getBytes("utf-8")))
    }
  }

} 
Example 70
Source File: Model.scala    From couchdb-scala   with Apache License 2.0 5 votes vote down vote up
package com.ibm.couchdb

import java.util.Base64

import org.http4s.headers.`Content-Type`

import scalaz.\/

case class Config(host: String, port: Int, https: Boolean, credentials: Option[(String, String)])

case class CouchDoc[D](
    doc: D,
    kind: String,
    _id: String = "",
    _rev: String = "",
    _deleted: Boolean = false,
    _attachments: Map[String, CouchAttachment] = Map.empty[String, CouchAttachment],
    _conflicts: Seq[String] = Seq.empty[String],
    _deleted_conflicts: Seq[String] = Seq.empty[String],
    _local_seq: Int = 0)

case class CouchDocRev(rev: String)

case class CouchKeyVal[K, V](id: String, key: K, value: V)

case class CouchReducedKeyVal[K, V](key: K, value: V)

case class CouchKeyError[K](key: K, error: String)

case class CouchKeyValWithDoc[K, V, D](id: String, key: K, value: V, doc: CouchDoc[D])

case class CouchKeyVals[K, V](offset: Int, total_rows: Int, rows: Seq[CouchKeyVal[K, V]])

case class CouchReducedKeyVals[K, V](rows: Seq[CouchReducedKeyVal[K, V]])

case class CouchKeyValsIncludesMissing[K, V](
    offset: Int,
    total_rows: Int,
    rows: Seq[\/[CouchKeyError[K], CouchKeyVal[K, V]]])

case class CouchDocs[K, V, D](
    offset: Int, total_rows: Int, rows: Seq[CouchKeyValWithDoc[K, V, D]]) {

  def getDocs: Seq[CouchDoc[D]] = rows.map(_.doc)

  def getDocsData: Seq[D] = rows.map(_.doc.doc)
}

case class CouchDocsIncludesMissing[K, V, D](
    offset: Int,
    total_rows: Int,
    rows: Seq[\/[CouchKeyError[K], CouchKeyValWithDoc[K, V, D]]]) {

  def getDocs: Seq[CouchDoc[D]] = rows.flatMap(_.toOption).map(_.doc)

  def getDocsData: Seq[D] = rows.flatMap(_.toOption).map(_.doc.doc)
}

case class CouchAttachment(
    content_type: String,
    revpos: Int = -1,
    digest: String = "",
    data: String = "",
    length: Int = -1,
    stub: Boolean = false) {
  def toBytes: Array[Byte] = Base64.getDecoder.decode(data)
}

case object CouchAttachment {
  def fromBytes(data: Array[Byte], content_type: String = ""): CouchAttachment = {
    CouchAttachment(
      content_type = content_type,
      data = Base64.getEncoder.encodeToString(data))
  }

  def fromBytes(data: Array[Byte], content_type: `Content-Type`): CouchAttachment = {
    CouchAttachment(
      content_type = content_type.toString,
      data = Base64.getEncoder.encodeToString(data))
  }
}

case class CouchView(map: String, reduce: String = "")

case class CouchDesign(
    name: String,
    _id: String = "",
    _rev: String = "",
    language: String = "javascript",
    validate_doc_update: String = "",
    views: Map[String, CouchView] = Map.empty[String, CouchView],
    shows: Map[String, String] = Map.empty[String, String],
    lists: Map[String, String] = Map.empty[String, String],
    _attachments: Map[String, CouchAttachment] = Map.empty[String, CouchAttachment],
    signatures: Map[String, String] = Map.empty[String, String])

case class CouchException[D](content: D) extends Throwable {
  override def toString: String = "CouchException: " + content
} 
Example 71
Source File: Auth.scala    From hammock   with MIT License 5 votes vote down vote up
package hammock
package hi

import java.util.Base64
import cats._
import cats.implicits._

sealed trait Auth
object Auth {
  case class BasicAuth(user: String, pass: String) extends Auth
  case class OAuth2Bearer(token: String)           extends Auth
  case class OAuth2Token(token: String)            extends Auth

  implicit val authShow = new Show[Auth] {
    def show(a: Auth): String = a match {
      case BasicAuth(user, pass) =>
        val toEncode = s"$user:$pass".getBytes
        val encoded  = Base64.getEncoder.encode(toEncode)
        s"Basic ${new String(encoded)}"
      case OAuth2Bearer(token) => s"Bearer $token"
      case OAuth2Token(token)  => s"token $token"
    }
  }

  implicit val authEq = new Eq[Auth] {
    def eqv(a: Auth, b: Auth): Boolean = (a, b) match {
      case (BasicAuth(u1, p1), BasicAuth(u2, p2)) => u1 === u2 && p1 === p2
      case (OAuth2Bearer(t1), OAuth2Bearer(t2)) => t1 === t2
      case (OAuth2Token(t1), OAuth2Token(t2)) => t1 === t2
      case _ => false
    }
  }
} 
Example 72
Source File: BasicAuthentication.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server

import java.util.Base64

import endpoints4s.algebra.BasicAuthentication.Credentials
import endpoints4s.algebra.Documentation
import endpoints4s.{Tupler, Valid, algebra}
import play.api.http.HeaderNames
import play.api.http.HeaderNames.AUTHORIZATION
import play.api.libs.streams.Accumulator
import play.api.mvc.{BodyParser, Results}

 )) =>
        _ =>
          Some(
            BodyParser(_ =>
              Accumulator.done(
                Left(
                  Results.Unauthorized.withHeaders(
                    HeaderNames.WWW_AUTHENTICATE -> "Basic realm=Realm"
                  )
                )
              )
            )
          )
      case (u, (h, Some(credentials))) =>
        headers =>
          entity(headers).map(
            _.map(e => tuplerUEHC(tuplerUE(u, e), tuplerHC(h, credentials)))
          )
    } { out =>
      val (ue, hc) = tuplerUEHC.unapply(out)
      val (u, _) = tuplerUE.unapply(ue)
      val (h, c) = tuplerHC.unapply(hc)
      (u, (h, Some(c)))
    }
  }

}