-
Notifications
You must be signed in to change notification settings - Fork 0
/
feistel.py
60 lines (54 loc) · 1.61 KB
/
feistel.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
import random as rd
import sys
def cipher(inp, keys, f):
for key in keys:
L, R = split(inp)
Ln = xor(L, f(key, R))
inp = R+Ln
return Ln+R
def split(inp):
assert len(inp)%2==0
return inp[:int(len(inp)/2)], inp[int(len(inp)/2):]
def xor(a, b):
output=""
for i in range(len(a)):
#print(i, a, b)
inter=int(a[i])+int(b[i])
if inter==2: inter=0
output = output+str(inter)
return output
def keyGen(l,n):
o=[]
for i in range(n):
k=""
for i in range(l):
k = k + str(rd.randint(0,1))
o.append(k)
return o
def binToHex(binary):
res="0x"
hexList = [hex(int(binary[i:i+8], 2))[2:] for i in range(0, len(binary),8)]
for hexa in hexList:
if len(hexa)==1: hexa ="0"+hexa
res = res + hexa
return res
def action(plainText):
plainInts = [bin(ord(letter))[2:] for letter in plainText]
plainBin=""
for integer in plainInts:
while len(integer)!=8:
integer = "0"+integer
plainBin = plainBin+integer
keyList = keyGen(int(len(plainBin)/2), 16)
C = cipher(plainBin, keyList, xor)
keyList.reverse()
result = cipher(C, keyList, xor)
resultToChar = [chr(int(result[i:i+8], 2)) for i in range(0, len(result),8)]
resultText=""
for letter in resultToChar:
resultText = resultText+letter
print("Plain text: {}".format(plainText))
print('Plain text to hexa: {}'.format(binToHex(plainBin)))
print("Cipher: {}".format(binToHex(C)))
print("Result as hexa: {}".format(binToHex(result)))
print("Result to text: {}".format(resultText))