Friday, April 26, 2019

Encryption and decryption using Hill Cipher Technique - System Security | Python3

import numpy as np
from itertools import islice, chain, repeat
list2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
         'w', 'x', 'y','z']
l3=[]
l4=[]
lis4=[]
def chunk_pad(it, size, padval=23):
    it = chain(iter(it), repeat(padval))
    return iter(lambda: tuple(islice(it, size)), (padval,) * size)

#Key-matrix = a
a=[[6,24,1],[13,16,10],[20,17,15]]
x = np.array(a)
p=np.matrix(a)
msg= input("Enter msg: ")
list1=list(msg)
l2=[]

for i in range(len(list1)):
    for j in range((26)):
        if(list1[i]==list2[j]):
            l2.append(j)

b=list(chunk_pad(l2, 3, 23))
for e in range(len(b)):
    list0=b[e]
    list0=list(list0)
    mul=np.dot(a,list0)
    CT=mul%26
    for i in range(len(CT)):
        for j in range(26):
            if(CT[i]==j):
                l3.append(list2[j])
                lis4.append(j)
enc=''.join(l3)
print("\nEncrypted Message: "+str(enc))


#print("\n\n====Receiver Side====")
det1=np.linalg.det(x)
c=list(chunk_pad(lis4,3,23))
adj=np.linalg.inv(x).T * np.linalg.det(x)

PT1=[]
for e in range(len(c)):
    list11=c[e]
    list11=list(list11)
    for i in range(26):
        if (i*det1)%26==1:
            det2=i
            inverse=(det2 * adj % 26).T
            mul1 = np.dot(inverse, list11)
            PT = mul1 % 26
            PT1=PT %26
            PT3=[]
            for q in range(len(PT1)):
                PT3.append(int(round(PT1[q])))

            for o in range(len(PT3)):
                if(PT3[o]==26.):
                    PT3[o]=0
            for i in range(len(PT3)):
                for j in range(26):
                    if PT3[i] == j:
                        l4.append(list2[j])
            dec=''.join(l4)
            break
        else:
            continue
print("\nDecrypted Messge: " + str(dec))

Screenshot:

No comments:

Post a Comment