summaryrefslogtreecommitdiff
path: root/src/solvers/Challenge4.scala
blob: f71f6c0facf1549b7e13799f90dea9882cc00678 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package ixee.cryptopals.solvers

import scala.io.Source
import ixee.cryptopals.utils.ByteUtils._
import ixee.cryptopals.utils.ConversionUtils._
import ixee.cryptopals.utils.FunctionUtils._
import ixee.cryptopals.utils._

object Challenge4 {
  def findSingleCharacterXor(strings: Seq[Seq[Byte]]): (String, Int) = {
    strings
      .map(XorDecrypt.findBestSingleByteKey)
      .zip(strings)
      .zipWithIndex
      .map { pair => (pair._1._1, pair._1._2, pair._2) }
      .filter(_._1 != 0)
      .map { triplet => (XorDecrypt.decryptToAscii(triplet._2)(triplet._1), triplet._3) }
      .map { pair => (pair._1, TextScorer.score(pair._1.asBytes), pair._2) }
      .sortBy(_._2)
      .map { triplet => (triplet._1, triplet._3) }
      .head
  }

  def run(inputFile: String) = {
    findSingleCharacterXor(
      Source.fromFile(inputFile).getLines().toSeq.map(hexStr2Bytes(_))
    )
  }
}