blob: d6d99ffa6e8c938947a6d0ee7522b75002ad8587 (
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
|
package ixee.cryptopals.utils.crypto
import javax.crypto.Cipher
import ixee.cryptopals.utils.ConversionUtils._
import ixee.cryptopals.utils.FunctionUtils._
import ixee.cryptopals.utils.CryptoUtils._
import ixee.cryptopals.utils.TupleUtils._
import ixee.cryptopals.utils.ByteUtils._
class CBCEncrypter(cipher: Cipher, init: Seq[Byte]) {
val blockSize = 16
var state: Seq[Byte] = init
var leftover: Seq[Byte] = Seq()
def enc(data: Seq[Byte]): Seq[Byte] = {
val (blocks, newLeftover) = blockized(leftover ++ data)(blockSize)
leftover = newLeftover
blocks.map(encBlock _).foldLeft(Seq[Byte]())(_ ++ _)
}
def encBlock(data: Seq[Byte]): Seq[Byte] = {
state = cipher.update((data xor state).toArray)
state
}
def end(): Seq[Byte] =
cipher.doFinal((pkcs7pad(leftover, blockSize) xor state).toArray)
def blockized(data: Seq[Byte])(size: Int): (Seq[Seq[Byte]], Seq[Byte]) =
groupBlocks <-: data.splitAt(data.length - (data.length % size))
def groupBlocks: Seq[Byte] => Seq[Seq[Byte]] = _.grouped(blockSize).toSeq
}
|