-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathset2_utils.py
63 lines (43 loc) · 1.43 KB
/
set2_utils.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
from pwn import *
import itertools as it
from pprint import *
import operator as op
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
import random
import json
def padPKCS7(x, padto):
diff = (padto - (len(x)%padto)) % 16
padded = x + pack(diff, 'all')*diff
return padded
class CBC():
def __init__(self, cipher, iv):
self.cipher = cipher
self.iv = iv
self.blocksize = 16
def encrypt(self, plaintext):
e = self.cipher.encryptor()
# plaintext = padPKCS7(plaintext, 16)
blocks = [plaintext[i:i+self.blocksize] for i in xrange(0, len(plaintext), self.blocksize)]
prev_xor_block = self.iv
ciphertext = ""
for i in xrange(0, len(blocks)):
#xor with previous block
pre_aes_block = xor(blocks[i], prev_xor_block)
# Encrypt with cipher algorithm
current_cipher_block = e.update(pre_aes_block)
prev_xor_block = current_cipher_block
ciphertext += current_cipher_block
return ciphertext
def decrypt(self, ciphertext):
plaintext = ""
d = self.cipher.decryptor()
blocks = [ciphertext[i:i+self.blocksize] for i in xrange(0, len(ciphertext), self.blocksize)]
decrypted_block = d.update(blocks[0])
plaintext += xor(decrypted_block, self.iv)
for i in xrange(1, len(blocks)):
decrypted_block = d.update(blocks[i])
# print decrypted_block
plaintext += xor(decrypted_block, blocks[i-1])
return plaintext