package ixee.cryptopals.utils import ixee.cryptopals.utils.crypto._ import ixee.cryptopals.utils.StreamUtils._ import ixee.cryptopals.utils.FunctionUtils._ import javax.crypto.Cipher import javax.crypto.spec.SecretKeySpec object CryptoUtils { def pkcs7pad(s: Seq[Byte], blockSize: Int): Seq[Byte] = { val padLength = blockSize - (s.length % blockSize) s ++ Stream.continually(padLength.toByte).take(padLength) } def stripPkcs7Pad(s: Seq[Byte]): Seq[Byte] = s.dropRight(s.last) def cbcEncrypt(builder: CbcBuilder)(data: Seq[Byte]) = builder.encrypt.end(data) def cbcDecrypt(builder: CbcBuilder)(data: Seq[Byte]) = stripPkcs7Pad(builder.decrypt.end(data)) def ecbEncrypt(builder: EcbBuilder)(data: Seq[Byte]) = builder.encrypt.end(data) def ecbDecrypt(builder: EcbBuilder)(data: Seq[Byte]) = stripPkcs7Pad(builder.decrypt.end(data)) def detectMode(xs: Seq[Byte]): String = { def dupBlocks(xs: Seq[Seq[Byte]]) = pairsOf(xs).map(tup(_ == _)).count(_ == true) def countDupBlocks(xs: Seq[Byte]): Int = dupBlocks(xs.grouped(16).toSeq.init.toStream) //.... well very probably. if (countDupBlocks(xs) > 0) "ECB" else "CBC" } }