0% found this document useful (0 votes)
16 views14 pages

INS New

The document describes Python programs for implementing various cryptographic algorithms and techniques including substitution cipher, columnar transposition cipher, RSA encryption, HMAC, digital signatures, and multiplicative inverse calculation. The programs demonstrate encryption, decryption, signature verification and other cryptographic operations through code examples.

Uploaded by

giryahai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views14 pages

INS New

The document describes Python programs for implementing various cryptographic algorithms and techniques including substitution cipher, columnar transposition cipher, RSA encryption, HMAC, digital signatures, and multiplicative inverse calculation. The programs demonstrate encryption, decryption, signature verification and other cryptographic operations through code examples.

Uploaded by

giryahai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Practical 1 A

# Python program to demonstrate

# Substitution Cipher

import string

# A list containing all characters

all_letters= string.ascii_letters

"""

create a dictionary to store the substitution

for the given alphabet in the plain text

based on the key

"""

dict1 = {}

key = 4

for i in range(len(all_letters)):

dict1[all_letters[i]] = all_letters[(i+key)%len(all_letters)]

plain_txt= "I am TYCS student"


cipher_txt=[]

# loop to generate ciphertext

for char in plain_txt:

if char in all_letters:

temp = dict1[char]

cipher_txt.append(temp)

else:

temp =char

cipher_txt.append(temp)

cipher_txt= "".join(cipher_txt)

print("Cipher Text is: ",cipher_txt)

"""

create a dictionary to store the substitution

for the given alphabet in the cipher

text based on the key

"""

dict2 = {}

for i in range(len(all_letters)):

dict2[all_letters[i]] = all_letters[(i-key)%(len(all_letters))]
# loop to recover plain text

decrypt_txt = []

for char in cipher_txt:

if char in all_letters:

temp = dict2[char]

decrypt_txt.append(temp)

else:

temp = char

decrypt_txt.append(temp)

decrypt_txt = "".join(decrypt_txt)

print("Recovered plain text :", decrypt_txt)

Ptactical 1B

implementation of

# Columnar Transposition

import math

key = "HACK"

# Encryption

def encryptMessage(msg):

cipher = ""

# track key indices

k_indx = 0
msg_len = float(len(msg))

msg_lst = list(msg)

key_lst = sorted(list(key))

# calculate column of the matrix

col = len(key)

# calculate maximum row of the matrix

row = int(math.ceil(msg_len / col))

# add the padding character '_' in empty

# the empty cell of the matix

fill_null = int((row * col) - msg_len)

msg_lst.extend('_' * fill_null)

# create Matrix and insert message and

# padding characters row-wise

matrix = [msg_lst[i: i + col]

for i in range(0, len(msg_lst), col)]

# read matrix column-wise using key

for _ in range(col):

curr_idx = key.index(key_lst[k_indx])

cipher += ''.join([row[curr_idx]

for row in matrix])

k_indx += 1
return cipher

# Decryption

def decryptMessage(cipher):

msg = ""

# track key indices

k_indx = 0

# track msg indices

msg_indx = 0

msg_len = float(len(cipher))

msg_lst = list(cipher)

# calculate column of the matrix

col = len(key)

# calculate maximum row of the matrix

row = int(math.ceil(msg_len / col))

# convert key into list and sort

# alphabetically so we can access

# each character by its alphabetical position.

key_lst = sorted(list(key))

# create an empty matrix to


# store deciphered message

dec_cipher = []

for _ in range(row):

dec_cipher += [[None] * col]

# Arrange the matrix column wise according

# to permutation order by adding into new matrix

for _ in range(col):

curr_idx = key.index(key_lst[k_indx])

for j in range(row):

dec_cipher[j][curr_idx] = msg_lst[msg_indx]

msg_indx += 1

k_indx += 1

# convert decrypted msg matrix into a string

try:

msg = ''.join(sum(dec_cipher, []))

except TypeError:

raise TypeError("This program cannot",

"handle repeating words.")

null_count = msg.count('_')

if null_count > 0:

return msg[: -null_count]


return msg

# Driver Code

msg = "I am TYCS Student"

cipher = encryptMessage(msg)

print("Encrypted Message: {}".

format(cipher))

print("Decryped Message: {}".

# Practical no 2

#Python for RSA asymmetric cryptographic algorithm.

# For demonstration, values are

# relatively small compared to practical application

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

# Private key (d stands for decrypt)

# choosing d such that it satisfies

# 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)

# practical no 3

#code to demonstrate the working of hmac module.

import hmac

import hashlib

# creating new hmac object using sha1 hash algorithm

digest_maker = hmac.new(b'secret-key', b'msg', hashlib.sha1)

# print the Hexdigest of the bytes passed to update

print ("Hexdigest: " + digest_maker.hexdigest())

# call update to update msg

digest_maker.update(b'another msg')
# print the Hexdigest of the bytes passed to update

print ("Hexdigest after update: " + digest_maker.hexdigest())

print ("Digest size: " + str(digest_maker.digest_size) + " bytes")

print ("Block size: " + str(digest_maker.block_size) + " bytes")

print ("Canonical name: " + digest_maker.name)

# print the digest of the bytes passed to update

print ("Digest: ", end =" ")

print (digest_maker.digest())

# create a copy of the hmac object

digest_clone = digest_maker.copy()

print ("Hexdigest of clone: " + digest_clone.hexdigest())

# Function to find gcd

# of two numbers

def euclid(m, n):

if n == 0:

return m

else:

r=m%n

return euclid(n, r)
# Practical No 4

# Program to find

# Multiplicative inverse Digital signature 0

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)

# Select an encryption key

# from the above list

e = int(313)

# Obtain inverse of
# encryption key in Z_Pn

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

# Alice sends M and S both to Bob

# Bob generates message M1 using the

# signature S, Alice's public key e

# 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 ")

You might also like