summaryrefslogtreecommitdiff
path: root/src/utils/ConversionUtils.scala
blob: 26f2d24fe3a248e82394292cd0c86725dac76d01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package ixee.cryptopals.utils

import ByteUtils.WithBitOpts

object ConversionUtils {
  def hexStr2Bytes(s: String): Iterator[Byte] =
    padToByte(s).grouped(2).map(byteStr2Byte)

  def byteStr2Byte(str: String): Byte =
    charSeq2Byte(str.toSeq)

  def charSeq2Byte(seq: Seq[Char]): Byte =
    seq.map(octet2nibble).reduce(joinNibbles)

  def joinNibbles(a: Byte, b: Byte): Byte =
    ((a @<< 4) @+ b)

  def padToByte(s: String): String = 
    if (s.length % 2 != 0) "0" + s else s

  def octet2nibble(c: Char): Byte = {
    (c.toLower match {
      case c if c >= 'a' && c <= 'f' =>
        (c - 'a') + 10.toByte
      case c if c >= '0' && c <= '9' =>
        c - '0'
      case _ =>
        throw new IllegalArgumentException(s"Invalid hexadecimal character: $c")
    }).toByte
  }

  def hexStr2Base64String(s: String): String = {
    import io.github.marklister.base64.Base64._

    hexStr2Bytes(s).toArray.toBase64
  }
}