Created
November 9, 2015 19:38
-
-
Save bholzer/aae3bf96a0830dcbbb19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def decodeSingleByteXOR(cipherText: String, char: Char): String = { | |
val cipherTextByteArray = decodeHex(cipherText) | |
new String(cipherTextByteArray.zip(Array.fill(cipherTextByteArray.length)(char)).map((t) => t._2 ^ t._1).map(_.toByte), "UTF-8") | |
} | |
def bruteForceSingleByteXOR(cipherText: String): Array[String] = { | |
(('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9')).toArray.map(decodeSingleByteXOR(cipherText,_)) | |
} | |
def decodeHex(hex: String): Array[Byte] = { | |
hex.replaceAll("[^0-9A-Fa-f]", "").sliding(2,2).toArray.map(Integer.parseInt(_, 16).toByte) | |
} | |
def trigramStringScoring(text: String): Int = { | |
val trigramRanks = Array("the", "and", "tha", "ent", "ing", "ion", "tio", "for", "nde", "has", "nce", "edt", "tis", "oft", "sth", "men") | |
text.toLowerCase.sliding(3).foldLeft(0) { (memo, sub) => | |
val score = if (trigramRanks.indexOf(sub) > -1) trigramRanks.length - trigramRanks.indexOf(sub) else 0 | |
memo + score | |
} | |
} | |
val source = scala.io.Source.fromFile("resources/mt4.txt") | |
source.getLines.toArray.flatMap(bruteForceSingleByteXOR).sortBy { (line) => | |
-trigramStringScoring(line) | |
}.take(2).foreach { (line) => | |
println(trigramStringScoring(line) + ": " + line) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment