From d32466d20399489ae5cf254588c87e009a9c29f7 Mon Sep 17 00:00:00 2001 From: iximeow Date: Sun, 23 Nov 2014 18:56:24 -0800 Subject: Add challenge 4 --- src/solvers/XorDecrypt.scala | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'src/solvers/XorDecrypt.scala') diff --git a/src/solvers/XorDecrypt.scala b/src/solvers/XorDecrypt.scala index b7f7c43..6b82c34 100644 --- a/src/solvers/XorDecrypt.scala +++ b/src/solvers/XorDecrypt.scala @@ -2,18 +2,24 @@ package ixee.cryptopals.solvers import ixee.cryptopals.utils._ import ixee.cryptopals.utils.ByteUtils._ +import ixee.cryptopals.utils.FunctionUtils._ object XorDecrypt { implicit val freq = Frequencies.cornell40kSample - def tryBestDecrypt(ciphertext: Seq[Byte]) = { - val key = findBestSingleByteKey(ciphertext) + def decryptToAscii(ciphertext: Seq[Byte])(key: Byte): String = { new String((ciphertext xor Stream.continually(key)).toArray) } + def tryBestDecrypt(ciphertext: Seq[Byte]): String = { + (findBestSingleByteKey _ :| decryptToAscii(ciphertext) _)(ciphertext) + } + def findBestSingleByteKey(ciphertext: Seq[Byte]): Byte = candidates(ciphertext) - .minBy(_._1)._2.toByte + .reduceOption( (a: (Double, Int), b: (Double, Int)) => + if (a._1 < b._1) a else b + ).map(_._2.toByte).getOrElse(0.toByte) def candidates(ciphertext: Seq[Byte]) = (0 until 256) -- cgit v1.1