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


Scala Hex类代码示例

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


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

示例1: BEncodeTest

//设置package包名称以及导入依赖的类
import java.time.Instant

import com.karasiq.bittorrent.format.{Torrent, TorrentFile, TorrentPiece}
import org.apache.commons.codec.binary.Hex
import org.apache.commons.io.IOUtils
import org.scalatest.{FlatSpec, Matchers}

class BEncodeTest extends FlatSpec with Matchers  {
  val testFile = IOUtils.toByteArray(getClass.getResource("ubuntu-15.10-desktop-amd64.iso.torrent"))

  "BEncode parser" should "parse torrent file" in {
    val torrent = Torrent(testFile)
    Hex.encodeHexString(torrent.infoHash.toArray).toUpperCase shouldBe "3F19B149F53A50E14FC0B79926A391896EABAB6F"
    torrent.announce shouldBe "http://torrent.ubuntu.com:6969/announce"
    torrent.announceList shouldBe Vector(Vector("http://torrent.ubuntu.com:6969/announce"), Vector("http://ipv6.torrent.ubuntu.com:6969/announce"))
    torrent.comment shouldBe Some("Ubuntu CD releases.ubuntu.com")
    torrent.date shouldBe Some(Instant.parse("2015-10-22T09:48:19Z"))
    torrent.data.pieceLength shouldBe 524288L
    torrent.data.pieces.length shouldBe 44960
    torrent.data.files.headOption shouldBe Some(TorrentFile("ubuntu-15.10-desktop-amd64.iso", 1178386432L))
  }

  "Torrent pieces" should "be constructed" in {
    val torrent = Torrent(testFile)
    val pieces = TorrentPiece.pieces(torrent.data)
    pieces.length shouldBe (torrent.data.pieces.length / 20)
    pieces.map(_.size).sum shouldBe torrent.size
    pieces.head.sha1.length shouldBe 20
  }

  "Torrent piece blocks" should "be constructed" in {
    val torrent = Torrent(testFile)
    val pieces = TorrentPiece.pieces(torrent.data)
    val blocks = TorrentPiece.blocks(pieces.head, 10000)
    blocks.map(_.size).sum shouldBe pieces.head.size
  }
} 
开发者ID:Karasiq,项目名称:torrentstream,代码行数:38,代码来源:BEncodeTest.scala

示例2: PublicKeyBase

//设置package包名称以及导入依赖的类
package com.spooky.inbound

import javax.crypto.spec.DHParameterSpec
import java.math.BigInteger
import java.security.KeyPairGenerator
import javax.crypto.KeyAgreement
import javax.crypto.interfaces.DHPublicKey
import org.apache.commons.codec.binary.Hex

abstract class PublicKeyBase extends Base {
  protected val p = new java.math.BigInteger("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563", 16)

  private val dhParamSpec = new DHParameterSpec(DH_P_BI, DH_G_BI, DH_L)
  val dh_key_generator = KeyPairGenerator.getInstance("DH")
  dh_key_generator.initialize(dhParamSpec)

  private val keyPair = dh_key_generator.generateKeyPair()

  val keyAgreement = KeyAgreement.getInstance("DH")
  keyAgreement.init(keyPair.getPrivate())

  private val dhPublicKey = keyPair.getPublic.asInstanceOf[DHPublicKey]
  private val dh_y = dhPublicKey.getY()

  println("New: " + LocalPublicKey.parse(dh_y, DH_SIZE_BYTES))
  println("Old: " + Hex.encodeHexString(bigIntegerToBytes(dh_y, DH_SIZE_BYTES)))

  val publicKey = LocalPublicKey(bigIntegerToBytes(dh_y, DH_SIZE_BYTES))

  def decodeString(str: String): Array[Byte] = {
    val chars = str.toCharArray();

    val chars_length = chars.length - chars.length % 2;

    val res = Array.ofDim[Byte](chars_length / 2);

    for (i <- 0.until(chars_length, 2)) {

      val b = new String(chars, i, 2);

      res(i / 2) = Integer.parseInt(b, 16).asInstanceOf[Byte];
    }

    return (res);
  }

  def bigIntegerToBytes(bi: BigInteger, num_bytes: Int): Array[Byte] = {
    var str = bi.toString(16);
    // System.out.println(str.length() + "|" + str);
    while (str.length() < num_bytes * 2) {
      str = "0" + str;
    }
    // System.out.println(num_bytes * 2 + "||" + str);
    return (decodeString(str));
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:57,代码来源:PublicKeyBase.scala

示例3: Checksum

//设置package包名称以及导入依赖的类
package com.spooky.bittorrent

import scala.annotation.tailrec
import java.security.MessageDigest
import java.util.Arrays
import org.apache.commons.codec.binary.Hex
import java.nio.ByteBuffer

sealed case class Checksum(sum: Array[Byte], algorithm: Algorithm) {
  def check(other: Array[Byte]): Boolean = {
    check(other.length, other)
  }
  def check(length: Int, other: Array[Byte]*): Boolean = {
      @tailrec
      def rec(length: Int, other: Seq[Array[Byte]], index: Int, digest: MessageDigest): Array[Byte] = {
        if (other.length - 1 == index) {
          digest.update(other(index), 0, length)
          digest.digest
        } else {
          digest.update(other(index))
          rec(length, other, index + 1, digest)
        }
      }
    val digester = MessageDigest.getInstance(algorithm.toString)
    MessageDigest.isEqual(sum, rec(length, other, 0, digester))
  }
  def compare(other: Array[Byte]): Boolean = MessageDigest.isEqual(sum, other)
  override def toString: String = Hex.encodeHexString(sum)
  override def hashCode: Int = Arrays.hashCode(sum)
  override def equals(o: Any): Boolean = o match {
    case Checksum(otherHash, Sha1) => MessageDigest.isEqual(otherHash, sum)
    case _                         => false
  }
}
object Checksum {
  def parse(raw: ByteBuffer, algorithm: Algorithm): Checksum = {
    val checksum = Array.ofDim[Byte](algorithm.bytes)
    for (n <- 0 until algorithm.bytes) {
      checksum(n) = raw.get
    }
    Checksum(checksum, algorithm)
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:44,代码来源:Checksum.scala

示例4: InfoHash

//设置package包名称以及导入依赖的类
package com.spooky.bittorrent

import org.apache.commons.codec.binary.Hex
import java.util.Arrays
import java.security.MessageDigest
import java.nio.ByteBuffer

sealed case class InfoHash(raw: Array[Byte]) {
  override def toString: String = Hex.encodeHexString(raw)
  override def hashCode: Int = Arrays.hashCode(raw)
  override def equals(o: Any): Boolean = o match {
    case InfoHash(otherHash) => MessageDigest.isEqual(otherHash, raw)
    case _                   => false
  }
}
object InfoHash {
  def apply(sha1: Sha1): InfoHash = InfoHash(sha1.raw)
  def hex(hex: String): InfoHash = InfoHash(Hex.decodeHex(hex.toCharArray()))
  def parse(arr: Array[Byte]): InfoHash = {
    println(arr.length)
    assert(arr.length >= 20)
    InfoHash(arr.take(20))
  }
  def parse(buffer: ByteBuffer): InfoHash = {
    assert(buffer.remaining >= 20)
    val result = new Array[Byte](20)
    buffer.get(result)
    InfoHash(result)
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:31,代码来源:InfoHash.scala

示例5: WorldPayMacHelper

//设置package包名称以及导入依赖的类
package cjp.payments.util

import java.security.MessageDigest
import org.apache.commons.codec.binary.Hex


class WorldPayMacHelper() {

  def checkMac(orderKey: String,
               paymentAmount: String,
               paymentCurrency: String,
               paymentStatus: String,
               mac: String,
               macSecret:String): Boolean = {
    mac == createMac(orderKey, paymentAmount, paymentCurrency, paymentStatus, macSecret)
  }

  def createMac(orderKey: String,
                paymentAmount: String,
                paymentCurrency: String,
                paymentStatus: String,
                macSecret:String): String = {
    val msg = orderKey + paymentAmount + paymentCurrency + paymentStatus + macSecret
    val digest = MessageDigest.getInstance("MD5").digest(msg.getBytes)
    new String(Hex.encodeHex(digest))
  }

} 
开发者ID:UKHomeOffice,项目名称:worldpay-stub,代码行数:29,代码来源:WorldPayMacHelper.scala

示例6: MessageMsgPackProcessorActor

//设置package包名称以及导入依赖的类
package com.ubirch.avatar.core.actor

import akka.actor.{Actor, ActorLogging, Props}
import akka.http.scaladsl.HttpExt
import akka.stream.Materializer
import com.ubirch.avatar.core.device.DeviceDataRawManager
import com.ubirch.avatar.core.msgpack.MsgPacker
import com.ubirch.util.json.MyJsonProtocol
import com.ubirch.util.model.JsonErrorResponse
import com.ubirch.util.mongo.connection.MongoUtil
import org.apache.commons.codec.binary.Hex

import scala.concurrent.ExecutionContextExecutor


class MessageMsgPackProcessorActor(implicit mongo: MongoUtil, httpClient: HttpExt, materializer: Materializer)
  extends Actor
    with MyJsonProtocol


    with ActorLogging {

  implicit val executionContext: ExecutionContextExecutor = context.dispatcher

  private val validatorActor = context.system.actorOf(Props(new MessageValidatorActor()))
  //private val validatorActor = context.system.actorSelection(ActorNames.MSG_VALIDATOR)

  override def receive: Receive = {
    case binData: Array[Byte] =>
      val s = sender()

      val hexVal = Hex.encodeHexString(binData)
      log.info(s"got some MsgPack data: $hexVal")
      try {
        val (u, t) = MsgPacker.unpack(binData)
        DeviceDataRawManager.create(did = u, vals = t, mpraw = binData) match {
          case Some(drd) =>
            validatorActor forward drd
          case None =>
            log.error("could not parse input msgpack data")
            s ! JsonErrorResponse(errorType = "Validation Error", errorMessage = "Invalid Data")
        }
      }
      catch {
        case e: Exception =>
          log.error("received invalid data", e)
          sender ! JsonErrorResponse(errorType = "Invalid Data Error", errorMessage = "Incalid Dataformat")
      }
    case _ =>
      log.error("received unknown message")
      sender ! JsonErrorResponse(errorType = "Validation Error", errorMessage = "Invalid Input Data")
  }

} 
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:55,代码来源:MessageMsgPackProcessorActor.scala

示例7: EncryptionUtils

//设置package包名称以及导入依赖的类
package io.policarp.scala.credstash

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import org.apache.commons.codec.binary.Hex

object EncryptionUtils {

  implicit class ToHexDigest(bytes: Array[Byte]) {
    def toHexDigest = new String(Hex.encodeHex(bytes))
  }

  implicit class FromHexDigest(chars: Array[Char]) {
    def fromHexDigest = Hex.decodeHex(chars)
  }

  
  object HmacSHA256 {
    @throws[Exception]
    def apply(data: Array[Byte], key: Array[Byte]) = {
      val algorithm = "HmacSHA256"
      val mac = Mac.getInstance(algorithm)
      mac.init(new SecretKeySpec(key, algorithm))
      mac.doFinal(data)
    }
  }

} 
开发者ID:kdrakon,项目名称:scala-credstash,代码行数:30,代码来源:EncryptionUtils.scala

示例8: JsonWebSignature

//设置package包名称以及导入依赖的类
package authentikat.jwt

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import org.apache.commons.codec.binary.Hex



object JsonWebSignature {

  object HexToString{
    implicit def converter (bytes: Array[Byte]): String = {
      Hex.encodeHexString(bytes)
    }
  }

  def apply(algorithm: String, data: String, key: String): Array[Byte] = {
    algorithm match {
      case "HS256" => apply(HS256, data, key)
      case "HS384" => apply(HS384, data, key)
      case "HS512" => apply(HS512, data, key)
      case "none" => apply(none, data, key)
      case x => throw new UnsupportedOperationException(x + " is an unknown or unimplemented JWT algo key")
    }
  }

  def apply(algorithm: Algorithm, data: String, key: String = null): Array[Byte] = {
    algorithm match {
      case HS256 => HmacSha("HmacSHA256", data, key)
      case HS384 => HmacSha("HmacSHA384", data, key)
      case HS512 => HmacSha("HmacSHA512", data, key)
      case none => Array.empty[Byte]
      case x => throw new UnsupportedOperationException(x + " is an unknown or unimplemented JWT algo key")
    }
  }

  private case object HmacSha {
    def apply(algorithm: String, data: String, key: String): Array[Byte] = {

      val _key = Option(key).getOrElse(throw new IllegalArgumentException("Missing key for JWT encryption via " + algorithm))
      val mac: Mac = Mac.getInstance(algorithm)
      val secretKey: SecretKeySpec = new SecretKeySpec(_key.getBytes, algorithm)
      mac.init(secretKey)
      mac.doFinal(data.getBytes)
    }
  }

  abstract class Algorithm

  case object none extends Algorithm

  case object HS256 extends Algorithm

  case object HS384 extends Algorithm

  case object HS512 extends Algorithm

} 
开发者ID:astrofed,项目名称:akka-slick-auth-token-microservices,代码行数:60,代码来源:JsonWebSignature.scala

示例9: Bytes

//设置package包名称以及导入依赖的类
package com.avsystem.scex.util

import java.io.UnsupportedEncodingException
import java.nio.charset.StandardCharsets

import com.avsystem.commons.jiop.JavaInterop._
import com.avsystem.scex.presentation.annotation.Documentation
import org.apache.commons.codec.binary.{Base64, Hex}

import scala.collection.mutable
import scala.util.hashing.MurmurHash3

final class Bytes(val bytes: Array[Byte]) extends Comparable[Bytes] {
  override def hashCode(): Int = MurmurHash3.bytesHash(bytes)
  override def equals(other: Any): Boolean = other match {
    case b: Bytes => java.util.Arrays.equals(bytes, b.bytes)
    case _ => false
  }
  override def toString: String = s"Bytes($escaped)"
  override def compareTo(o: Bytes): Int = {
    def loop(i: Int): Int =
      if (i == bytes.length && i == o.bytes.length) 0
      else if (i == bytes.length) -1
      else if (i == o.bytes.length) 1
      else {
        val b1 = bytes(i)
        val b2 = o.bytes(i)
        if (b1 == b2) loop(i + 1) else b1 - b2
      }
    loop(0)
  }

  @Documentation("Encodes this sequence of bytes as string with non-ASCII bytes and backslash escaped, e.g. 'hsg\\x7c\\x0dfoo\\\\bar'")
  def escaped: String = EscapedBytes.render(bytes)

  @Documentation("Encodes this sequence of bytes as hexadecimal string")
  def hex: String = Hex.encodeHexString(bytes)

  @Documentation("Encodes this sequence of bytes as BASE64 string")
  def base64: String = Base64.encodeBase64String(bytes)

  @Documentation("Decodes this sequence of bytes as UTF-8 string")
  def decodeUTF8: String = new String(bytes, StandardCharsets.UTF_8)

  @Documentation("Decodes this sequence of bytes as string using given charset")
  def decode(charset: String): String =
    try new String(bytes, charset) catch {
      case e: UnsupportedEncodingException => throw new IllegalArgumentException(e)
    }

  def asList: JList[Byte] = new mutable.WrappedArray.ofByte(bytes).asJava
} 
开发者ID:AVSystem,项目名称:scex,代码行数:53,代码来源:Bytes.scala

示例10: PoloniexAuth

//设置package包名称以及导入依赖的类
package models.poloniex.trade

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import org.apache.commons.codec.binary.Hex
import play.api.libs.ws.WSRequest


class PoloniexAuth(apiKey: String, secretKey: String) {

  protected def generateSignature(params: String): String = {
    val keyspec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA512")
    val shaMac = Mac.getInstance("HmacSHA512")
    shaMac.init(keyspec)

    val macData = shaMac.doFinal(params.getBytes())
    Hex.encodeHexString(macData)
  }

  def setAuthenticationHeaders(request: WSRequest,
                               params: String = ""): WSRequest = {

    val signature = generateSignature(params)

    request.withHeaders(
      "Key" -> apiKey,
      "Sign" -> signature)
  }

  def setNonAuthenticationHeaders(request: WSRequest) = {
    val gdaxRequest = request.withHeaders(
      "Accept" -> "application/json")
  }
} 
开发者ID:asciiu,项目名称:polo,代码行数:36,代码来源:PoloniexAuth.scala

示例11: PrivateKey

//设置package包名称以及导入依赖的类
package org.reactormonk

import javax.crypto.{ Cipher, Mac }
import javax.crypto.spec.{ IvParameterSpec, SecretKeySpec }
import org.apache.commons.codec.binary.Hex

case class PrivateKey(key: Array[Byte])

case class CryptoBits(key: PrivateKey) {

  def sign(message: String): String = {
    val mac = Mac.getInstance("HmacSHA1")
    mac.init(new SecretKeySpec(key.key, "HmacSHA1"))
    Hex.encodeHexString(mac.doFinal(message.getBytes("utf-8")))
  }

  def signToken(token: String, nonce: String): String = {
    val joined = nonce + "-" + token
    sign(joined) + "-" + joined
  }

  def validateSignedToken(token: String): Option[String] = {
    token.split("-", 3) match {
      case Array(signature, nonce, raw) => {
        val signed = sign(nonce + "-" + raw)
        if(constantTimeEquals(signature, signed)) Some(raw) else None
      }
      case _ => None
    }
  }

  def constantTimeEquals(a: String, b: String): Boolean = {
    var equal = 0
    for (i <- 0 until (a.length min b.length)) {
      equal |= a(i) ^ b(i)
    }
    if (a.length != b.length) {
      false
    } else {
      equal == 0
    }
  }
} 
开发者ID:reactormonk,项目名称:cryptobits,代码行数:44,代码来源:cryptobits.scala


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