-
Notifications
You must be signed in to change notification settings - Fork 0
/
feistal.py
55 lines (41 loc) · 1.68 KB
/
feistal.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
from Crypto.Util.strxor import strxor
from Crypto.Util.Padding import pad
from random import getrandbits
KEY_LENGTH = 12
BLOCK_SIZE = 8
NUM_ROUNDS = 3
def feistel_block(plaintext: bytearray, key: bytearray):
left_array = plaintext[4:8]
right_array = plaintext[0:4]
round_keys = list()
round_keys.append(((key & 0xf0) >> 4) ^ ((key & 0xf00) >> 8))
round_keys.append(key & 0xf ^ ((key & 0xf0) >> 4))
round_keys.append(key & 0xf ^ ((key & 0xf00) >> 8))
# print(round_keys)
for i in range(NUM_ROUNDS):
left_array_new = right_array
right_array = bin(int(left_array, 2) ^ round_keys[i]).strip('0b')
left_array = left_array_new
# print(f'LEFT: {left_array} RIGHT: {right_array}')
left_array = left_array.zfill(len(left_array) + 4-len(left_array) % 5)
right_array = right_array.zfill(len(right_array) + 4-len(right_array) % 5)
ciphertext_block = left_array + right_array
return bytearray(ciphertext_block, encoding='utf-8')
def feistel_system_3(plaintext, key):
ciphertext = ''
for i in range(int(len(plaintext)/8)):
plaintext_block = plaintext[8*i:8*i+8]
ciphertext_block = feistel_block(plaintext_block, key)
ciphertext += chr(int(ciphertext_block, 2))
print(repr(ciphertext))
def main():
plaintext = bytes(
input("Please enter your plaintext").strip('\n'), encoding='utf-8')
plaintext = bin(int(plaintext.hex(), 16)).strip('0b')
# Now the plaintext is a string of 0's and 1's only
plaintext = plaintext.zfill(len(plaintext) + 8-len(plaintext) % 9)
key = getrandbits(12)
print(f'KEY: {key}')
feistel_system_3(plaintext, key)
if __name__ == '__main__':
main()