코드 (python)
EP = [4,1,2,3,2,3,4,1]
S0 = [[1,0,3,2],[3,2,1,0],[0,2,1,3],[3,1,3,2]]
S1 = [[0,1,2,3],[2,0,1,3],[3,0,1,0],[2,1,0,3]]
P4 = [2,4,3,1]
P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
P8 = [6, 3, 7, 4, 8, 5, 10, 9]
IP_1 = [4,1,3,5,7,2,8,6]
IP = [2, 6, 3, 1, 4, 8, 5, 7]
def shift_left(n, d, length):
result = ((n<<d) & (2**length -1)) | (n>>(length - d))
return result
def key_generator(key):
#P10(key)
p10 = [0] * len(P10)
n = 0
for i in P10:
p10[n] = key[i-1]
n+=1
p10_key = ''.join(p10)
#key1 = P8(LS-1(P10(key)))
c1 = p10_key[:5]
d1 = p10_key[5:]
#leftshift
ls1_c = bin(shift_left(int(c1,2), 1, len(c1)))[2:].zfill(5)
ls1_d = bin(shift_left(int(d1,2), 1, len(d1)))[2:].zfill(5)
ls1_key = ls1_c + ls1_d
#P8, Key1 generator
p8 = [0] * len(P8)
n = 0
for i in P8:
p8[n] = ls1_key[i-1]
n+=1
key1 = ''.join(p8)
ls2_c = bin(shift_left(int(ls1_c,2), 2, len(ls1_c)))[2:].zfill(5)
ls2_d = bin(shift_left(int(ls1_d,2), 2, len(ls1_d)))[2:].zfill(5)
ls2_key = ls2_c + ls2_d
p8 = [0] * len(P8)
n = 0
for i in P8:
p8[n] = ls2_key[i-1]
n+=1
key2 = ''.join(p8)
return [key1, key2]
def decryption(cipher, key1, key2):
#IP(cipher)
ip_list = [0]*len(IP)
n=0
for i in IP:
ip_list[n] = cipher[i-1]
n+=1
ip = ''.join(ip_list)
l2 = ip[:4]
r2 = ip[4:]
#swap
r1 = bin(int(l2,2) ^ int(func(r2,key2),2))[2:].zfill(4)
l1 = r2
r0 = r1
l0 = bin(int(l1,2)^ int(func(r1,key1),2))[2:].zfill(4)
lr = l0+r0
pt_list = [0]*len(IP_1)
n=0
for i in IP_1:
pt_list[n] = lr[i-1]
n+=1
pt= ''.join(pt_list)
return pt
def func(r, key):
ep_text = [0]*len(EP)
n=0
for i in EP:
ep_text[n] = r[i-1]
n+=1
ep_r= ''.join(ep_text)
ep_r_key = bin(int(ep_r, 2) ^ int(key, 2))[2:].zfill(8)
bit_array = []
n=0
for i in ep_r_key:
bit_array.append(i)
if(n==3):
row = int("0b"+bit_array[0]+bit_array[3],2)
col = int("0b"+bit_array[1]+bit_array[2],2)
s_0 = bin(S0[row][col])[2:].zfill(2)
bit_array = []
if(n==7):
row = int("0b"+bit_array[0]+bit_array[3],2)
col = int("0b"+bit_array[1]+bit_array[2],2)
s_1 = bin(S1[row][col])[2:].zfill(2)
n+=1
s = s_0+s_1
p4_list = [0]*len(P4)
n=0
for i in P4:
p4_list[n] = s[i-1]
n+=1
p4 = ''.join(p4_list)
return p4
c1 = "11001000010010011010011101111100000001001011000001010111010101110111110011011100"
c2 = "0000101000011001000010101011110001111100000010001101110001001001"
c3 = "0000010001111100101001111101110011111010101"
c4 = "10000010101110111110011001000010010011010011101111100111110101011110011001000"
cipher = c1+c2+c3+c4
for i in range(1024):
pt_list = []
cipher_list = []
key = bin(i)[2:].zfill(10)
[key1, key2] = key_generator(key)
for j in cipher :
cipher_list.append(j)
if len(cipher_list) == 8 :
cipher_text = ''.join(cipher_list)
pt = decryption(cipher_text, key1, key2)
cipher_list = []
pt_a = int(pt,2)
if(pt_a > 31 and pt_a < 128 ) :
pt_list.append(chr(pt_a))
if(len(pt_list) > 32):
print("key :: ("+str(bin(i)[2:])+")",str(i)," / PlainText :: ",''.join(pt_list))
출력화면