summaryrefslogtreecommitdiff
path: root/src/solvers/Challenge4.scala
blob: ba771a8b699800da1cc3ddcc49b4305c59e7ecdf (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.decryptToAsciiSingleByteKey(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(_))
    )
  }
}