IS EXP1-8

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

NAME: NEEL GABANI

SAP ID : 60004210127
SUB: INFORMATION
SECURITY
C21 COMPS

EXP 1 – PLAYFAIR CIPHER

CODE:
key=input("Enter key")
key=key.replace(" ", "")
key=key.upper()
def matrix(x,y,initial):
return [[initial for i in range(x)] for j in range(y)]

result=list()
for c in key: #storing key
if c not in result:
if c=='J':
result.append('I')
else:
result.append(c)
flag=0
for i in range(65,91): #storing other character
if chr(i) not in result:
if i==73 and chr(74) not in result:
result.append("I")
flag=1
elif flag==0 and i==73 or i==74:
pass
else:
result.append(chr(i))
k=0
my_matrix=matrix(5,5,0) #initialize matrix
for i in range(0,5): #making matrix
for j in range(0,5):
my_matrix[i][j]=result[k]
k+=1

def locindex(c): #get location of each character


loc=list()
if c=='J':
c='I'
for i ,j in enumerate(my_matrix):
for k,l in enumerate(j):
if c==l:
loc.append(i)
loc.append(k)
return loc

def encrypt(): #Encryption


msg=str(input("ENTER MSG:"))
msg=msg.upper()
msg=msg.replace(" ", "")
i=0
for s in range(0,len(msg)+1,2):
if s<len(msg)-1:
if msg[s]==msg[s+1]:
msg=msg[:s+1]+'X'+msg[s+1:]
if len(msg)%2!=0:
msg=msg[:]+'X'
print("CIPHER TEXT:",end=' ')
while i<len(msg):
loc=list()
loc=locindex(msg[i])
loc1=list()
loc1=locindex(msg[i+1])
if loc[1]==loc1[1]:
print("{}{}".format(my_matrix[(loc[0]+1)%5]
[loc[1]],my_matrix[(loc1[0]+1)%5][loc1[1]]),end=' ')
elif loc[0]==loc1[0]:
print("{}{}".format(my_matrix[loc[0]]
[(loc[1]+1)%5],my_matrix[loc1[0]][(loc1[1]+1)%5]),end=' ')
else:
print("{}{}".format(my_matrix[loc[0]]
[loc1[1]],my_matrix[loc1[0]][loc[1]]),end=' ')
i=i+2

def decrypt(): #decryption


msg=str(input("ENTER CIPHER TEXT:"))
msg=msg.upper()
msg=msg.replace(" ", "")
print("PLAIN TEXT:",end=' ')
i=0
while i<len(msg):
loc=list()
loc=locindex(msg[i])
loc1=list()
loc1=locindex(msg[i+1])
if loc[1]==loc1[1]:
print("{}{}".format(my_matrix[(loc[0]-1)%5]
[loc[1]],my_matrix[(loc1[0]-1)%5][loc1[1]]),end=' ')
elif loc[0]==loc1[0]:
print("{}{}".format(my_matrix[loc[0]][(loc[1]-
1)%5],my_matrix[loc1[0]][(loc1[1]-1)%5]),end=' ')
else:
print("{}{}".format(my_matrix[loc[0]]
[loc1[1]],my_matrix[loc1[0]][loc[1]]),end=' ')
i=i+2

while(1):
choice=int(input("\n 1.Encryption \n 2.Decryption: \n 3.EXIT"))
if choice==1:
encrypt()
elif choice==2:
decrypt()
elif choice==3:
exit()
else:
print("Choose correct choice")

OUTPUT:

EXP2 – VIGENERE CIPHER

CODE:
def create_vigenere_matrix():
matrix = [[chr((i + j) % 26 + ord('A')) for j in range(26)] for i
in range(26)]
return matrix

def vigenere_encrypt(plain_text, key):


result = []
key_length = len(key)
for i in range(len(plain_text)):
char = plain_text[i]
if char.isalpha():
shift = ord(key[i%len(key)])- ord ('A')
if char.isupper():
result.append(chr((ord(char) + shift - ord('A')) % 26 +
ord('A')))
else:
result.append(char)
return ''.join(result)

plain_text=input("Enter Plain Text:")


key=input("Enter Key:")
plain_text=plain_text.upper()
key=key.upper()

matrix_print=create_vigenere_matrix()
print("Matrix",matrix_print)

cipher_text = vigenere_encrypt(plain_text, key)


print("Encrypted:", cipher_text)

OUTPUT:

EXP3- VERMAN CIPHER

CODE:
plaintext = input("Enter plaintext: \n")
key = input("Enter key:\n")
if len(plaintext)==len (key):
result = [chr((((ord (a) - ord ("a")) ^ (ord(b) - ord("a"))) % 26)
+ ord ("a") )
for a, b in zip(plaintext.lower(), key.lower())]
print("".join(result))
OUTPUT:

EXP4 – COLUMNAR CIPHER

CODE:

import math pt = input("Enter the plaintext : ").upper() key =

input("Enter the key : ").upper() def find_rank(key):

rank = 0 for i in sorted(key):

key = key.replace(i, str(rank), 1) rank += 1 key = [int(i) for i in key] return key

def encrypt(pt, key): cols = len(key) rows = math.ceil(len(pt) / cols) key_rank =


find_rank(key) print(key_rank) pt += "".join(["X"] * (rows * cols - len(pt))) matrix =

[list(pt[i : i + cols]) for i in range(0, len(pt), cols)] for i in range(rows):

print(matrix[i]) ciphertext = ["*" for i in range(cols)]

j = 0

for i in key_rank:

ciphertext[i] = [row[j] for row in matrix]

j += 1 res = [] for i in ciphertext:

res.extend(i) return "".join(res) def decrypt(cip, key): cols = len(key) rows =

math.ceil(len(cip) / cols) key_rank = find_rank(key) cip += "".join(["X"] * (rows * cols -

len(cip))) cip_mat = [list(cip[i:i+rows]) for i in range(0, len(cip), rows)] res = [] for i

in range(rows):

a = ["*"] *(len(key_rank))
count = 0 for r in key_rank: a[count] = cip_mat[r][i] count +=1

res.extend(a) return "".join(res).rstrip("X") print(f"\nPlain text : {pt}\

nKey:{key}\n") ciphertext = encrypt(pt, key) print(f"After encryption, Cipher

Text : {ciphertext}\n") decrypted_text = decrypt(ciphertext, key)

print(f"After decryption, Plain Text : {decrypted_text}")

OUTPUT:
EXP5- RSA

CODE:
import math
def gcd(a, h):
temp = 0
while(1):
temp = a % h
if (temp == 0):
return h
a=h
h = temp
p=3
q=7
n = p*q
e=2
phi = (p-1)*(q-1)
while (e < phi):
# e must be co-prime to phi and
# smaller than phi.
if(gcd(e, phi) == 1):
break
else:
e = e+1
# d*e = 1 + k * totient
k=2
d = (1 + (k*phi))/e
# Message to be encrypted
msg = 12.0
print("Message data = ", msg)
# Encryption c = (msg ^ e) % n
c = pow(msg, e)
c = math.fmod(c, n)
print("Encrypted data = ", c)
# Decryption m = (c ^ d) % n
m = pow(c, d)
m = math.fmod(m, n)
print("Original Message Sent = ", m)

OUTPUT:

EXP6- DIFFIE HELLMAN KEY EXCHANGE

CODE:
from random import randint
P=
23 Q
=9
print('The Value of P is :%d'%(P))
print('The Value of Q is :%d'%(Q))

# Alice will choose the private


key a
a=4
print('The Private Key a for Alice is :%d'%(a))

# gets the generated key


x = int(pow(Q,a,P))

# Bob will choose the private


key b b = 3
print('The Private Key b for Bob is :%d'%(b))
# gets the generated
key y =
int(pow(Q,b,P))

# Secret key for


Alice ka =
int(pow(y,a,P))

# Secret key for


Bob kb =
int(pow(x,b,P))

print('Secret key for the Alice is : %d'%(ka))


print('Secret Key for the Bob is : %d'%(kb))

OUTPUT:
EXP7- MD5

CODE:
import hashlib

def md5_hash(text):

encoded_text = text.encode('utf-8') md5_hash_object = hashlib.md5()


md5_hash_object.update(encoded_text)

md5_hash_hex = md5_hash_object.hexdigest() return md5_hash_hex

text = "Hello, world!" md5_hash_value = md5_hash(text) print("MD5 hash:",


md5_hash_value)

OUTPUT:
EXP8 – RSA DIGITAL SIGNATURE

CODE:
def euclid(m, n):

if n == 0: return m else:
r=m%n
return euclid(n, r) def exteuclid(a, b):
r1 = a
r2 = b
s1 = int(1) s2 = int(0) t1 = int(0) t2 = int(1)

while r2 > 0:

q = r1//r2 r = r1-q * r2 r1 = r2 r2 = r s = s1-q * s2 s1 = s2 s2 = s


t = t1-q * t2 t1 = t2 t2 = t

if t1 < 0: t1 = t1 % a

return (r1, t1)

# Enter two large prime # numbers p and q p = 823 q = 953


n=p*q
Pn = (p-1)*(q-1)

# Generate encryption key # in range 1<e<Pn key = []

for i in range(2, Pn):

gcd = euclid(Pn, i)

if gcd == 1: key.append(i) e=int(313) r, d = exteuclid(Pn, e) if r == 1: d = int(d)


print("decryption key is: ", d)

else:
print("Multiplicative inverse for\ the given encryption key does not \ exist. Choose a different
encryption key ")

# Enter the message to be sent


M = 19070

# Signature is created by Alice


S = (M**d) % n # and product n.
M1 = (S**e) % n

# If M = M1 only then Bob accepts # the message sent by Alice.

if M == M1:
print("As M = M1, Accept the\ message sent by Alice") else:
print("As M not equal to M1,\ Do not accept the message\ sent by Alice ")

OUTPUT:

You might also like