From 91b4cfc801b7c156c231ca60aba69a8d171e9226 Mon Sep 17 00:00:00 2001 From: iximeow Date: Wed, 26 Nov 2014 18:10:58 -0800 Subject: Challenge 8, 9 --- src/utils/ByteUtils.scala | 3 +++ src/utils/ConversionUtils.scala | 2 +- src/utils/CryptoUtils.scala | 10 ++++++++++ src/utils/StreamUtils.scala | 5 +++++ 4 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 src/utils/CryptoUtils.scala (limited to 'src/utils') diff --git a/src/utils/ByteUtils.scala b/src/utils/ByteUtils.scala index 18942c0..723164d 100644 --- a/src/utils/ByteUtils.scala +++ b/src/utils/ByteUtils.scala @@ -108,4 +108,7 @@ object ByteUtils { def hammingDistance[T : BitOps : SizedNumeric](a: Seq[T], b: Seq[T]): Int = (a xor b).map(_.bitsSet).reduce(_ @+ _) + + def avgHammingDistance[T : BitOps : SizedNumeric](xs: Seq[Seq[T]]): Double = + xs.sliding(2).map({ case Stream(a: Seq[T], b: Seq[T]) => hammingDistance(a, b) }).reduce(_ @+ _) / xs.length.toDouble } diff --git a/src/utils/ConversionUtils.scala b/src/utils/ConversionUtils.scala index 95d08ce..ec3f813 100644 --- a/src/utils/ConversionUtils.scala +++ b/src/utils/ConversionUtils.scala @@ -5,7 +5,7 @@ import FunctionUtils._ object ConversionUtils { def hexStr2Bytes(s: String): Seq[Byte] = - padToByte(s).grouped(2).map(byteStr2Byte).toSeq + padToByte(s).grouped(2).map(byteStr2Byte).toStream.force def byteStr2Byte(str: String): Byte = charSeq2Byte(str.toSeq) diff --git a/src/utils/CryptoUtils.scala b/src/utils/CryptoUtils.scala new file mode 100644 index 0000000..5418895 --- /dev/null +++ b/src/utils/CryptoUtils.scala @@ -0,0 +1,10 @@ +package ixee.cryptopals.utils + +object CryptoUtils { + + def pkcs7pad(s: String, blockSize: Int) = { + val padLength = blockSize - (s.length % blockSize) + s + s"${padLength.toChar}" * padLength + } + +} diff --git a/src/utils/StreamUtils.scala b/src/utils/StreamUtils.scala index 4f803c0..be5246c 100644 --- a/src/utils/StreamUtils.scala +++ b/src/utils/StreamUtils.scala @@ -17,6 +17,11 @@ object StreamUtils { def continuous[A](xs: Seq[A]): Stream[A] = xs.to[Stream] append continuous(xs.to[Stream]) + def pairsOf[A](xs: Seq[A]): Seq[(A, A)] = + (xs.init zip xs.tail.tails.toSeq) flatMap { case (elem, rest) => + rest zip Stream.continually(elem) + } + /* // Or just xs.to[Stream] ... def fromSeq[A](xs: Seq[A]): Stream[A] = -- cgit v1.1