blob: 7a310022d01431ef7badf99362a3753189e32dbe (
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
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"
}
}
|