-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctr.py
151 lines (126 loc) · 4.55 KB
/
ctr.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import binascii
from multiprocessing import Process
from multiprocessing import Pool
from Crypto.Cipher import AES
import os, random, sys
from binascii import unhexlify
def long_to_bytes (val, endianness='big'):
"""
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param long val: The value to pack
:param str endianness: The endianness of the result. ``'big'`` for
big-endian, ``'little'`` for little-endian.
If you want byte- and word-ordering to differ, you're on your own.
Using :ref:`string formatting` lets us use Python's C innards.
"""
# one (1) hex digit per four (4) bits
width = val.bit_length()
# unhexlify wants an even multiple of eight (8) bits, but we don't
# want more digits than we need (hence the ternary-ish 'or')
width += 8 - ((width % 8) or 8)
# format width specifier: four (4) bits per hex digit
fmt = '%%0%dx' % (width // 4)
# prepend zero (0) to the width, to zero-pad the output
s = unhexlify(fmt % val)
if endianness == 'little':
# see http://stackoverflow.com/a/931095/309233
s = s[::-1]
return s
def get_incremented_iv(iv, increment):
counter = int.from_bytes(binascii.unhexlify(iv), byteorder='big')
counter += increment
res = long_to_bytes(counter)
hex_res = binascii.hexlify(res).decode('utf-8')
while len(hex_res) < 16:
hex_res = '0' + hex_res
return hex_res
def get_hex_iv():
return binascii.hexlify(os.urandom(16)).decode('utf-8')
def encrypt(key, raw):
'''
Takes in a string of clear text and encrypts it.
@param raw: a string of clear text
@return: a string of encrypted ciphertext
'''
if (raw is None) or (len(raw) == 0):
raise ValueError('input text cannot be null or empty set')
cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
ciphertext = cipher.encrypt(raw)
return binascii.hexlify(bytearray(ciphertext)).decode('utf-8')
def decrypt(key, enc):
if (enc is None) or (len(enc) == 0):
raise ValueError('input text cannot be null or empty set')
enc = binascii.unhexlify(enc)
cipher = AES.AESCipher(key[:32], AES.MODE_ECB)
enc = cipher.decrypt(enc)
return enc#.decode('utf-8')
def xor_hex_string(a, b):
c, d = binascii.unhexlify(a), binascii.unhexlify(b)
result = bxor(c, d)
return binascii.hexlify(result).decode('utf-8')
def bxor(b1, b2): # use xor for bytes
result = bytearray()
for b1, b2 in zip(b1, b2):
result.append(b1 ^ b2)
return result
def ctr_encrypt(key, hex, iv):
last_block = encrypt(key, binascii.unhexlify(iv))
result = xor_hex_string(last_block, hex)
return binascii.unhexlify(result)
if __name__ == "__main__":
input = ""
output = ""
keyfile=""
ivfile =""
checkiv=0
for a in range(1,len(sys.argv)):
if sys.argv[a] == "-k":
keyfile = sys.argv[a+1]
if sys.argv[a] == "-v":
ivfile = sys.argv[a+1]
checkiv =1
if sys.argv[a]=="-o":
output=sys.argv[a+1]
if sys.argv[a] == "-i":
input = sys.argv[a + 1]
if sys.argv[a] == "-f":
function = sys.argv[a + 1]
infile=open(input,"rb")
hex_data= infile.read()
infile.close()
outfile=open(output,"wb")
keyring=open(keyfile,"r")
key= keyring.read()
hex_data = binascii.hexlify(hex_data).decode('utf-8')
if function == "encrypt":
if checkiv:
ivhold=open(ivfile,"r")
iv=ivhold.read()
else:
iv = get_hex_iv()
last_block=iv
iv_int = iv
answer = binascii.unhexlify(iv)
pool = Pool(processes = 4)
count=1
for i in range(0, len(hex_data), 32):
p = pool.apply_async(ctr_encrypt,(key,hex_data[i:i+32],get_incremented_iv(iv, count)))
count+=1
answer += p.get()
outfile.write(answer)
elif function == "decrypt":
if checkiv:
ivhold = open(ivfile, "r")
iv = ivhold.read()
else:
iv = hex_data[:32]
last_block = iv
print(iv)
answer = ""
pool = Pool(processes=4)
count = 1
for i in range(32, len(hex_data), 32):
p = pool.apply_async(ctr_encrypt, (key, hex_data[i:i + 32], get_incremented_iv(iv, count)))
count += 1
outfile.write(p.get())