summaryrefslogtreecommitdiff
path: root/src/utils/ConversionUtils.scala
diff options
context:
space:
mode:
authoriximeow <me@iximeow.net>2014-11-21 00:48:10 -0800
committeriximeow <me@iximeow.net>2014-11-21 00:48:10 -0800
commit708c0c523df97d1542b7b6d128c5218f6e2cc460 (patch)
tree7377685c7718a6028ee845614d902726422f1f1e /src/utils/ConversionUtils.scala
parent481bbd0ee786ec6056918fb2016244836e450907 (diff)
Move things around a bit
Diffstat (limited to 'src/utils/ConversionUtils.scala')
-rw-r--r--src/utils/ConversionUtils.scala38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/utils/ConversionUtils.scala b/src/utils/ConversionUtils.scala
new file mode 100644
index 0000000..26f2d24
--- /dev/null
+++ b/src/utils/ConversionUtils.scala
@@ -0,0 +1,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
+ }
+}
+