diff options
author | iximeow <me@iximeow.net> | 2014-11-23 18:56:24 -0800 |
---|---|---|
committer | iximeow <me@iximeow.net> | 2014-11-23 18:56:24 -0800 |
commit | d32466d20399489ae5cf254588c87e009a9c29f7 (patch) | |
tree | 71bbf790220fd3daf574d3867dfd8c816e839fd4 /src/solvers/XorDecrypt.scala | |
parent | aa390776b26d794ab37aa13833fa7043aad16504 (diff) |
Add challenge 4
Diffstat (limited to 'src/solvers/XorDecrypt.scala')
-rw-r--r-- | src/solvers/XorDecrypt.scala | 12 |
1 files changed, 9 insertions, 3 deletions
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) |