Created
August 27, 2015 04:05
-
-
Save bholzer/9f83f610f1ba1117b15f 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
object Matasano { | |
def hexToBytes(hex: String): Array[Byte] = { | |
hex.replaceAll("[^0-9A-Fa-f]", "").sliding(2,2).toArray.map(Integer.parseInt(_, 16).toByte) | |
} | |
def bytesToHex(bytes: Array[Byte]): String = { | |
bytes.map("%02x" format _).mkString | |
} | |
def encode64(b: Array[Byte]): String = { | |
def sixBits(x: Array[Byte]): Array[Int] = { | |
val a = (x(0) & 0xfc) >> 2 | |
val b = ((x(0) & 0x3) << 4) | ((x(1) & 0xf0) >> 4) | |
val c = ((x(1) & 0xf) << 2) | ((x(2) & 0xc0) >> 6) | |
val d = (x(2)) & 0x3f | |
Array(a, b, c, d) | |
} | |
val zero = Array(0, 0).map(_.toByte) | |
val pad = (3 - b.length % 3) % 3 | |
val encodeTable = ('A' to 'Z') ++ ('a' to 'z') ++ ('0' to '9') ++ Seq('+', '/') | |
((b ++ zero.take(pad)).grouped(3) | |
.flatMap(sixBits) | |
.map(encodeTable) | |
.toArray | |
.dropRight(pad) :+ "="*pad) | |
.mkString | |
} | |
def fixedXOR(hex: String, xor: String): String = { | |
bytesToHex(hexToBytes(hex).zip(hexToBytes(xor)).map((t) => t._1 ^ t._2).map(_.toByte)) | |
} | |
def singleByteXOR(cipherText: String): Array[String] = { | |
val cipherByteArray = hexToBytes(cipherText) | |
(('A' to 'Z') ++ ('a' to 'z')).toArray.map((char) => | |
new String(cipherByteArray.zip(Array.fill(cipherByteArray.length)(char)).map((t) => t._2 ^ t._1).map(_.toByte), "UTF-8") | |
) | |
} | |
def main(args: Array[String]) { | |
// Test hex/base64 | |
assert( | |
encode64(hexToBytes("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d")) == | |
"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t" | |
) | |
// Test fixed-length XOR | |
assert( | |
fixedXOR("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") == | |
"746865206b696420646f6e277420706c6179" | |
) | |
singleByteXOR("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736").map(println) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment