-
Notifications
You must be signed in to change notification settings - Fork 7
/
cbc.py
68 lines (60 loc) · 1.95 KB
/
cbc.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class zeropad:
def __init__(self, block_size):
assert block_size > 0 and block_size < 256
self.block_size = block_size
def pad(self, pt):
ptlen = len(pt)
padsize = self.block_size - ((ptlen + self.block_size - 1) % self.block_size + 1)
return pt + "\0" * padsize
def unpad(self, ppt):
assert len(ppt) % self.block_size == 0
offset = len(ppt)
if (offset == 0):
return ''
end = offset - self.block_size + 1
while (offset > end):
offset -= 1;
if (ppt[offset] != "\0"):
return ppt[:offset + 1]
assert false
class cbc:
def __init__(self, padding, cipher, iv):
assert padding.block_size == cipher.block_size;
assert len(iv) == cipher.block_size;
self.padding = padding
self.cipher = cipher
self.iv = iv
def encrypt(self, pt):
ppt = self.padding.pad(pt)
offset = 0
ct = ''
v = self.iv
while (offset < len(ppt)):
block = ppt[offset:offset + self.cipher.block_size]
block = self.xorblock(block, v)
block = self.cipher.encrypt(block)
ct += block
offset += self.cipher.block_size
v = block
return ct;
def decrypt(self, ct):
assert len(ct) % self.cipher.block_size == 0
ppt = ''
offset = 0
v = self.iv
while (offset < len(ct)):
block = ct[offset:offset + self.cipher.block_size]
decrypted = self.cipher.decrypt(block)
ppt += self.xorblock(decrypted, v)
offset += self.cipher.block_size
v = block
pt = self.padding.unpad(ppt)
return pt;
def xorblock(self, b1, b2):
# sorry, not very Pythonesk
i = 0
r = '';
while (i < self.cipher.block_size):
r += chr(ord(b1[i]) ^ ord(b2[i]))
i += 1
return r