You are on page 1of 25

600042102u4

cIASSMAte
kapul Date :
Te Comps C32 Pece:

infonmaton Secity Cnpeument

Ain To umplemeat playta p h


|Theorg' 5x5 matix Ceeysqua
Ploytau capheu opeuates On

letes, ecludiag duplcates genated trom a keywcrcfhe


wwth the seeaning tetter
dhe matrix is flad wuth o
alphabet. Jhe process done as tolldws

(a) Enoypon
· Same colwn
Sau J’wrap auoUnd

Rectange
() oecaupon
Same colemn |11 wrap aond.
"Seme

retange MUMBAI |NOI ANS 1LL Lase VSING

JNFOKMATICS.

N F R

M A C
B D H
K P
cIASSMAte

Mare
diagams.
Deagiam! tncypted text A tuon
MU
MB
Re
etanale
Coluni

actangle
AI MN

NF
DI
AN
BN
Atangle
coen
Sw

PP
nctadgle
RC
EX PE
Aetangle
Lox is a falle char autel.

.'.
Enduypted text is SkBKMNNF DN DA A 2 NK PPRCPF

Con clLsion :- nEfere we hawe cmplennted plaf


Jhenetere
ciphe
IS Experiment 1

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
600042(029
Kapt
Te Comps C32
cIASSMAte

Pace

tnformatuen Secuuty Expexument 2


Aimi To mplenent Vignta Cophe
hecny' Vignee cupheu is a palyalphabeic aubiitution
phe fhat uae a io mplement the method. lnit
Cacse cpher ouch hitts tne (ettew by aa constant Valu
Vignee cipheu vanies the shift for each lette s the plaus
text baeid nthne
Cettee in the keywerd
cOYrespondung
To encypt the epeatet keuwd is aligned cuuth.
plantext Each Cutter is thes shtted by the
wih the

corcespondung
tette in the keyoard wsng a stanad caesen shfttt.
Jhe Eyord represented neded ntu the entue
plan t t is
eneypred
lengih o keoord cngth c plaintext
duing en cypton. Ci = Pi ki mod mmod 26
m

duun decypton CiD ki = Pi


m odnm

Duawbact is that the S repeated so ct cs


attacee t
decup The

Das we have mplemented Vignes


Cephee
IS Experiment 2

Code:

def generate_key(string, key):


key = list(key)
if len(string) == len(key):
return key
else:
for i in range(len(string) - len(key)):
key.append(key[i % len(key)])
return "".join(key)

def cipher_text(string, key):


cipher_text = []
for i in range(len(string)):
x = (ord(string[i]) + ord(key[i])) % 26
x += ord('A')
cipher_text.append(chr(x))
return "".join(cipher_text)

def original_text(cipher_text, key):


orig_text = []
for i in range(len(cipher_text)):
x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26
x += ord('A')
orig_text.append(chr(x))
return "".join(orig_text)

if __name__ == "__main__":
string = "GEEKSFORGEEKS"
keyword = "AYUSH"
key = generate_key(string, keyword)
cipher_text = cipher_text(string, key)
print("Ciphertext:", cipher_text)
print("Original/Decrypted Text:", original_text(cipher_text, key))
60004310249
Kapd
Te Cornps C32
Injormaton Enpement 33
Aum To mplement Veanan Cuphe
Theory Veaman Ciphea is a poly alphabetic upher 2 is
also knon as One tune pad. St i9.a Syrmnetie ey
met hod Key is ehated dahdo my 2 shaed
cncyphon
betwen mered2 heKey
the sendh l fheeewel
each Lette tnthe plaunt est iscombuned with
To'he eneayp fhe kes eina modulau addtor
corrsponding lutea n fhe key ing
and the usultis
esult 1s the capher tekt. he the s
long as fhe messoge an d
ony
when w2ed cometly
G= Pi Ki (Xo R)
Dueng entuyphon Pi =

he one hoe poad otfea a evel oj seuly as long


Te key is tnoly aanoom r enly once b Kept
used ony
as Howeue practeat challenge is nqeneatnq
Quch lona 2 smaly bngd's widispee
andom keys 'ntng
use. toen en cyptun nethocs often ere

ache' ioto
feasibl apprcach ky man agennt uhe mmantanng
atrong auty.
Concloion: Thus we have Cmplemented veAnam cphe
IS Experiment 3

Code:

def string_encryption(text, key):


cipher_text = ""
cipher = []
for i in range(len(key)):
cipher.append(ord(text[i]) - ord('A') + ord(key[i]) - ord('A'))
for i in range(len(key)):
if cipher[i] > 25:
cipher[i] = cipher[i] - 26
for i in range(len(key)):
x = cipher[i] + ord('A')
cipher_text += chr(x)
return cipher_text

def string_decryption(s, key):


plain_text = ""
plain = []
for i in range(len(key)):
plain.append(ord(s[i]) - ord('A') - (ord(key[i]) - ord('A')))
for i in range(len(key)):
if plain[i] < 0:
plain[i] = plain[i] + 26
for i in range(len(key)):
x = plain[i] + ord('A')
plain_text += chr(x)
return plain_text

plain_text = "kapilka"
key = "kashyap"
encrypted_text = string_encryption(plain_text.upper(), key.upper())
print("Cipher Text:", encrypted_text)
print("Message:", string_decryption(encrypted_text, key.upper()))
Output
6o O042024g
cIASSMAte
Kaçil
Te comps C32 Pas

Infomatuon Secuity Zxpeumant 44.


Auo Implement Sugie columna aphe

Theony' The sing le columra cupher isa transpositon cph


that mwowes eauanging the chaateus 04 the plaintext
by placung them
them in aaud
gua e th en deadisg the ciphetext
coloun ie
s wtten 9ut ow ky ww
TO
To enypt the plantext
ad, he ciphe-text is geneated by eadng the c o n
Thu quid na spcie ende sohich Ys cetermned by Ley
which is a pemtahon ot nos. repesentaq The
Eq 1f the 3142 the coumns aue ead tho
des froo tie cuphertext In a qid based cn the key
eadin the os toeceal tae original pleintexti
Whele tae cengle coumna cuphe provides a baai devel ot
secuty It 1s vulnerable to ceutas atta ceg ueh as
freqey analya
Modn ytgtaphy
Sophtcattd
techniq otem
mere
et ct secu
Concusi on : Thus we hawe implemented
cingle olemna
ciphea
IS Experiment 4

Code:
def CCT_Enc(plain_text, key):
new_text = ''
for i in plain_text:
new_text = new_text+(chr(ord(i)+key))
print("Cipher text of Caesar Cipher is " + new_text)
return new_text
def CCT_Dec(cypher_text, key):
plain_text = ''
for i in cypher_text:
plain_text = plain_text+(chr(ord(i)-key))
print("Decrypted text of Caesar Cypher is " + plain_text)
def ColTT_Enc(plain_text, key):
matrix = []
for i in range(key):
matrix.append([])
for i in range(len(plain_text)):
matrix[i % key].append(plain_text[i])
for i in matrix:
print(i)
cypher_text = ''
for i in matrix:
for char in i:
cypher_text += char
print("Cipher text of Columnar Transposition is " + cypher_text)
return cypher_text
def ColTT_Dec(cypher_text, key):
matrix = []
for i in range(key):
matrix.append([])
count = int(len(cypher_text)/key)
length = 0
extra = int(len(cypher_text) % key)
for charlist in matrix:
for j in range(count):
charlist.append(cypher_text[length])
length = length+1
if (extra != 0):
charlist.append(cypher_text[length])
length = length+1
extra = extra-1
for i in matrix:
print(i)
plain_text = ''
for i in range(key+1):
for charlist in matrix:
if i > len(charlist)-1:
continue
plain_text = plain_text + charlist[i]
print("Decrypted text of Columnar Transposition is " + plain_text)
string = input("Enter a string:")
key = int(input("Enter key:"))
col = int(input("Enter column number:"))
print("Cypher Caesar")
c1 = CCT_Enc(string, key)
CCT_Dec(c1, key)
print("Columnar Transposition")
c2 = ColTT_Enc(string, col)
ColTT_Dec(c2, col)

Output
600042(0 249
cIASSmAte
Kapl
Comps TE C32
5
nformahion Secuity erpeumnent
Aio To mplement RSA algeritim
Theowy RSA 1s aa oidely used asypmetnc encqphen
algertiin lt reliss on mathematical" dfculty of facttnng
procucte 2 agepme noc, tD Secui data. In RSA each
sea haa a par of kys i a public ky and a pruate kuy
the pubic key is weed for enypten hile pnwate key
is kept secul andA ua ed tr dec4pion.The key is kp
seeet. Secuicty is based ine dyfuculty of jacnng
based on fhe
product of 2 Lauge pime ass a thack thct becomES
camputatcnclly infeasuble aslength c key cnccaae
RSA is commonly ued for seceung cohLLnLLaton OVe

utent, cncludu test such Qo secuue comad enlne


rans actoni ete

Public key Ce,o)


Prate ky (dn)
Cn) =
ue PLe ns
n
dCo) ie
Mist be elanuely pits io

Te funl exa) mod Cdln)) =|


(p-T) modn
mLo c Ciphec text
ncypten P.J= (c-1) odn
Decafnon
cIASSMAte

A comon isse Man in the mi ddu etface


ohee a 3rd
pason nes to deypt the pAwate tey
that is shad/e shaud pebic eey
Concuson: heefore We haueLmplemented eSA
algenthm.
IS Experiment 5
Code:
import math

def enc(plain,e,n):
return (plain**e)%n

def dec(cipher,d,n):
return (cipher**d)%n

def get_public_key(phi):
e=2
while e < phi:
if math.gcd(e,phi) == 1:
break
else:
e += 1
return e

def get_private_key(e,phi):
d=2
while d < phi:
if (d*e)%phi == 1:
break
else:
d += 1
return d

if __name__=='__main__':
p,q = input('Enter two prime numbers: ').split()
plain = int(input('Enter the plain text: '))
p,q = int(p),int(q)
n = p*q
phi = (p-1)*(q-1)
e = get_public_key(phi)
d = get_private_key(e,phi)
print('Public key(e,n): ',e,n)
print('Private key(d,n): ',d,n)
cipher = enc(plain,e,n)
print('Cipher text: ',cipher)
print('Plain text: ',dec(cipher,d,n))
Output
6o0042l02Ua cIASSMAte
Kapil |
Te comps (32
Infomanon ecuity Expeunt 6
Aum Impilereat Ditte kullman Agontikn
Theony Ditte Hellman alqo isis wsed 0o eatablsh a che
deret that can be wsed for
or se
secet eonnuncaton
tuble eKChangag data over pubdue networt sena
the ellphe ave geneate poent gt sewet kuy
waing pauametes
paranete Aice Bob

public key
puate key

Jeey aeeued
b
Seciet y Ka=modp KB- modp
it KA= KB_ sers cmunate uthe

Concuscon es ee have cmplemcated Die Hellm an


P23 q=5a =4,be3
X= 5f mod 23
Y5^3 mod 23

K= (0'mod23 BK = 44
3
mod 23

AKBK co m n t fehea
IS Experiment 6
Code:
from random import randint
P = 23
Q=9
print('The Value of P is:', P)
print('The Value of Q is:', Q)
a=4
print('The Private Key a for Alice is:', a)
x = int(pow(Q, a, P))
b=3
print('The Private Key b for Bob is:', b)
y = int(pow(Q, b, P))
ka = int(pow(y, a, P))
kb = int(pow(x, b, P))
print('Secret key for Alice is:', ka)
print('Secret key for Bob is:', kb)

Output
Concduson
Theefere alVulnealihes
and tascri,veytyna
s censedeed ap sge Las hash
cetaLo
plcatena. r
pucatons opeaatea
enatng Theery
Implement
AiMDSm:
consdu secaihy Informain
wed output a
mmeageuncton '
Lentenk
cyptgaphcally
w whe a
Message
atenate aensiue
n that
makinanuqe
Somaydegay tnat
duet Sewuty
t collson mae
is t podues
Ogeat
applcatens stable
ntegeity
iwe esetal
cyptqapwe ayatem hash lied
uhile bette
unsuitable
agonth. 6
hawe bette valu to128 is Expeumnt
esstane
of tor vety a
40n
to Depute 2t comps
(32 210249
Te 66004
cnplennented eam
eleUant MS
MDS and
and 1asts t uudely
cunclustand flee kapd
haah secity cs fer cach dota hash
A s sch as y
not
t's catcal.
cypogaple It
junctens qwea valuewed
integty
recanmrd
sewealhasho
t's
weakness,
cutical
MoS cypga cIASSMAt
lt shrEng inpt alao
Lemite is
al by
IS Experiment 7
Code:
Experiment 7: MD5
Code:
import math

S = [7, 12, 17, 22] * 4 + [5, 9, 14, 20] * 4 + [4, 11, 16, 23] * 4 + [6, 10, 15, 21] * 4
K = [int(2**32 * abs(math.sin(i + 1))) for i in range(64)]
A0 = 0x67452301
B0 = 0xEFCDAB89
C0 = 0x98BADCFE
D0 = 0x10325476

# Auxiliary functions
def F(x, y, z): return (x & y) | (~x & z)
def G(x, y, z): return (x & z) | (y & ~z)
def H(x, y, z): return x ^ y ^ z
def I(x, y, z): return y ^ (x | ~z)
funcs = [F, G, H, I]

# Left rotate function


def left_rotate(x, c): return (x << c) | (x >> (32 - c))

# MD5 main algorithm


def md5(message):
message = bytearray(message, 'utf-8') # Convert the message to bytes
orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message.append(0x80)
while len(message) % 64 != 56:
message.append(0)
message += orig_len_in_bits.to_bytes(8, byteorder='little')

hash_pieces = [A0, B0, C0, D0]

for chunk_ofst in range(0, len(message), 64):


a, b, c, d = hash_pieces
chunk = message[chunk_ofst:chunk_ofst+64]
for i in range(64):
f = funcs[i//16](b, c, d)
g = (i*7 + 1) % 16 if i < 16 else (5*i + 1) % 16 if i < 32 else (3*i + 5) % 16 if i < 48 else (i *
3) % 16
to_rotate = a + f + K[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
new_b = (b + left_rotate(to_rotate, S[i])) & 0xFFFFFFFF
a, b, c, d = d, new_b, b, c
for i, val in enumerate([a, b, c, d]):
hash_pieces[i] += val
hash_pieces[i] &= 0xFFFFFFFF

return ''.join(f'{piece:08x}' for piece in hash_pieces)

msg = input("Enter message: ")


print(md5(msg))

Output
IS Experiment 8
Code:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key,
load_pem_public_key
from cryptography.exceptions import InvalidSignature
import base64

# Generate a key pair


def generate_key_pair():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
return private_key, public_key

# Sign a message with the private key


def sign(message, private_key):
signature = private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return base64.b64encode(signature)

# Verify a signature with the public key


def verify(message, signature, public_key):
try:
signature_bytes = base64.b64decode(signature)
public_key.verify(
signature_bytes,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except InvalidSignature:
return False

# Example usage
private_key, public_key = generate_key_pair()
message = b'This is a message to be signed'
signature = sign(message, private_key)

print(f'Message: {message}')
print(f'Signature: {signature}')

is_valid = verify(message, signature, public_key)


print(f'Is the signature valid? {is_valid}')

Output

You might also like