summaryrefslogtreecommitdiff
path: root/src/solvers/XorDecrypt.scala
diff options
context:
space:
mode:
Diffstat (limited to 'src/solvers/XorDecrypt.scala')
-rw-r--r--src/solvers/XorDecrypt.scala12
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)