0% found this document useful (0 votes)
19 views25 pages

Ins Practical

The document outlines various encryption techniques including Caesar cipher, Rail Fence cipher, Columnar cipher, Playfair cipher, Vernam cipher, and RSA algorithm. Each section provides Python code examples for encryption and decryption processes, along with sample outputs. The document serves as a practical guide for implementing these cryptographic methods.

Uploaded by

zxcvbnm.we541
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)
19 views25 pages

Ins Practical

The document outlines various encryption techniques including Caesar cipher, Rail Fence cipher, Columnar cipher, Playfair cipher, Vernam cipher, and RSA algorithm. Each section provides Python code examples for encryption and decryption processes, along with sample outputs. The document serves as a practical guide for implementing these cryptographic methods.

Uploaded by

zxcvbnm.we541
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/ 25

PRACTICAL 1

Caesar cipher is a type of Monoalphabetic cipher. It uses the similar substitution method to receive
the cipher text characters for each plain text character.

def encrypt_text(plaintext,n):

ans = ""

# iterate over the given text

for i in range(len(plaintext)):

ch = plaintext[i]

if ch==" ":

ans+=" "

elif (ch.isupper()):

ans += chr((ord(ch) + n-65) % 26 + 65)

else:

ans += chr((ord(ch) + n-97) % 26 + 97)

return ans

plaintext = "DANCE"

n=1

print("Plain Text is : " + plaintext)

print("Shift pattern is : " + str(n))

print("Cipher Text is : " + encrypt_text(plaintext,n))

OUTPUT

Plain Text is : DANCE

Shift pattern is : 1

Cipher Text is : EBODF


PRACTICAL 2

Rail Fence Cipher


# Online Python-3 Compiler (Interpreter)

# Python3 program to illustrate

# Rail Fence Cipher Encryption

# and Decryption

# function to encrypt a message

def encryptRailFence(text, key):

# create the matrix to cipher

# plain text key = rows ,

# length(text) = columns

# filling the rail matrix

# to distinguish filled

# spaces from blank ones

rail = [['\n' for i in range(len(text))]

for j in range(key)]

# to find the direction

dir_down = False

row, col = 0, 0

for i in range(len(text)):

# check the direction of flow

# reverse the direction if we've just

# filled the top or bottom rail


if (row == 0) or (row == key - 1):

dir_down = not dir_down

# fill the corresponding alphabet

rail[row][col] = text[i]

col += 1

# find the next row using

# direction flag

if dir_down:

row += 1

else:

row -= 1

# now we can construct the cipher

# using the rail matrix

result = []

for i in range(key):

for j in range(len(text)):

if rail[i][j] != '\n':

result.append(rail[i][j])

return("" . join(result))

# This function receives cipher-text

# and key and returns the original

# text after decryption

def decryptRailFence(cipher, key):

# create the matrix to cipher

# plain text key = rows ,


# length(text) = columns

# filling the rail matrix to

# distinguish filled spaces

# from blank ones

rail = [['\n' for i in range(len(cipher))]

for j in range(key)]

# to find the direction

dir_down = None

row, col = 0, 0

# mark the places with '*'

for i in range(len(cipher)):

if row == 0:

dir_down = True

if row == key - 1:

dir_down = False

# place the marker

rail[row][col] = '*'

col += 1

# find the next row

# using direction flag

if dir_down:

row += 1

else:

row -= 1

# now we can construct the


# fill the rail matrix

index = 0

for i in range(key):

for j in range(len(cipher)):

if ((rail[i][j] == '*') and

(index < len(cipher))):

rail[i][j] = cipher[index]

index += 1

# now read the matrix in

# zig-zag manner to construct

# the resultant text

result = []

row, col = 0, 0

for i in range(len(cipher)):

# check the direction of flow

if row == 0:

dir_down = True

if row == key-1:

dir_down = False

# place the marker

if (rail[row][col] != '*'):

result.append(rail[row][col])

col += 1

# find the next row using

# direction flag
if dir_down:

row += 1

else:

row -= 1

return("".join(result))

# Driver code

if __name__ == "__main__":

print(encryptRailFence("attack ", 2))

print(encryptRailFence("helloworld ", 2))

# Now decryption of the

# same cipher-text

print(decryptRailFence("atctak", 2))

print(decryptRailFence("hlool elwrd", 2))

Output

atc tak

hlool elwrd

attack

helloworld

PRACTICAL 3
Columnar Cipher

# Python3 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 = "hihelloworld"

cipher = encryptMessage(msg)

print("Encrypted Message: {}".

format(cipher))

print("Decryped Message: {}".

format(decryptMessage(cipher)))

Output

Encrypted Message: ilrholhloewd

Decryped Message: hihelloworld

PRACTICAL - 4
PLAYFAIR CIPHER

def toLowerCase(text):

return text.lower()

def removeSpaces(text):

newText = ""

for i in text:

if i == " ":

continue

else:

newText = newText + i

return newText

# Function to group 2 elements of a string

# as a list element

def Diagraph(text):

Diagraph = []

group = 0

for i in range(2, len(text), 2):

Diagraph.append(text[group:i])

group = i

Diagraph.append(text[group:])

return Diagraph

# Function to fill a letter in a string element


# If 2 letters in the same string matches

def FillerLetter(text):

k = len(text)

if k % 2 == 0:

for i in range(0, k, 2):

if text[i] == text[i+1]:

new_word = text[0:i+1] + str('x') + text[i+1:]

new_word = FillerLetter(new_word)

break

else:

new_word = text

Else

for i in range(0, k-1, 2):

if text[i] == text[i+1]:

new_word = text[0:i+1] + str('x') + text[i+1:]

new_word = FillerLetter(new_word)

break

else:

new_word = text

return new_word

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm',

'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

# Function to generate the 5x5 key square matrix


def generateKeyTable(word, list1):

key_letters = []

for i in word:

if i not in key_letters:

key_letters.append(i)

compElements = []

for i in key_letters:

if i not in compElements:

compElements.append(i)

for i in list1:

if i not in compElements:

compElements.append(i)

matrix = []

while compElements != []:

matrix.append(compElements[:5])

compElements = compElements[5:]

return matrix

def search(mat, element):

for i in range(5):

for j in range(5):

if(mat[i][j] == element):

return i, j

def encrypt_RowRule(matr, e1r, e1c, e2r, e2c):


char1 = ''

if e1c == 4:

char1 = matr[e1r][0]

else:

char1 = matr[e1r][e1c+1]

char2 = ''

if e2c == 4:

char2 = matr[e2r][0]

else:

char2 = matr[e2r][e2c+1]

return char1, char2

def encrypt_ColumnRule(matr, e1r, e1c, e2r, e2c):

char1 = ''

if e1r == 4:

char1 = matr[0][e1c]

else:

char1 = matr[e1r+1][e1c]

char2 = ''

if e2r == 4:

char2 = matr[0][e2c]

else:

char2 = matr[e2r+1][e2c]

return char1, char2


def encrypt_RectangleRule(matr, e1r, e1c, e2r, e2c):

char1 = ''

char1 = matr[e1r][e2c]

char2 = ''

char2 = matr[e2r][e1c]

return char1, char2

def encryptByPlayfairCipher(Matrix, plainList):

CipherText = []

for i in range(0, len(plainList)):

c1 = 0

c2 = 0

ele1_x, ele1_y = search(Matrix, plainList[i][0])

ele2_x, ele2_y = search(Matrix, plainList[i][1])

if ele1_x == ele2_x:

c1, c2 = encrypt_RowRule(Matrix, ele1_x, ele1_y, ele2_x, ele2_y)

# Get 2 letter cipherText

elif ele1_y == ele2_y:

c1, c2 = encrypt_ColumnRule(Matrix, ele1_x, ele1_y, ele2_x, ele2_y)

else:

c1, c2 = encrypt_RectangleRule(

Matrix, ele1_x, ele1_y, ele2_x, ele2_y)

cipher = c1 + c2

CipherText.append(cipher)
return CipherText

text_Plain = 'instrument'

text_Plain = removeSpaces(toLowerCase(text_Plain))

PlainTextList = Diagraph(FillerLetter(text_Plain))

if len(PlainTextList[-1]) != 2:

PlainTextList[-1] = PlainTextList[-1]+'z'

key = "Monarchy"

print("Key text:", key)

key = toLowerCase(key)

Matrix = generateKeyTable(key, list1)

print("Plain Text:", text_Plain)

CipherList = encryptByPlayfairCipher(Matrix, PlainTextList)

CipherText = ""

for i in CipherList:

CipherText += i

print("CipherText:", CipherText)

OUTPUT

Key text: Monarchy

Plain Text: instrument

CipherText: gatlmzclrq

PRACTICAL 5

VERNAM CIPHER
# Python program Implementing One Time Pad Algorithm

# Importing required classes

# Method 1

# Returning encrypted text

def stringEncryption(text, key):

# Initializing cipherText

cipherText = ""

# Initialize cipher array of key length

# which stores the sum of corresponding no.'s

# of plainText and key.

cipher = []

for i in range(len(key)):

cipher.append(ord(text[i]) - ord('A') + ord(key[i])-ord('A'))

# If the sum is greater than 25

# subtract 26 from it

# and store that resulting value

for i in range(len(key)):

if cipher[i] > 25:

cipher[i] = cipher[i] - 26

# Converting the no.'s into integers

# Convert these integers to corresponding

# characters and add them up to cipherText


for i in range(len(key)):

x = cipher[i] + ord('A')

cipherText += chr(x)

# Returning the cipherText

return cipherText

# Method 2

# Returning plain text

def stringDecryption(s, key):

# Initializing plain text

plainText = ""

# Initializing integer array of key length

# which stores difference

# of corresponding no.'s of

# each character of cipherText and key

plain = []

# Running for loop for each character

# subtracting and storing in the array

for i in range(len(key)):

plain.append(ord(s[i]) - ord('A') - (ord(key[i]) - ord('A')))

# If the difference is less than 0

# add 26 and store it in the array.

for i in range(len(key)):

if (plain[i] < 0):


plain[i] = plain[i] + 26

# Converting int to corresponding char

# add them up to plainText

for i in range(len(key)):

x = plain[i] + ord('A')

plainText += chr(x)

# Returning plainText

return plainText

plainText = "Hello"

# Declaring key

key = "MONEY"

# Converting plain text to toUpperCase

# function call to stringEncryption

# with plainText and key as parameters

encryptedText = stringEncryption(plainText.upper(), key.upper())

# Printing cipher Text

print("Cipher Text - " + encryptedText)

print("Message - " + stringDecryption(encryptedText, key.upper()))

OUTPUT

Cipher Text - TSYPM

Message - HELLO
PRACTICAL - 6

RSA ALGORITHM
import math

# step 1
p=3
q=7

# step 2
n = p*q
print("n =", n)

# step 3
phi = (p-1)*(q-1)

# step 4
e=2
while(e<phi):
if (math.gcd(e, phi) == 1):
break
else:
e += 1

print("e =", e)
# step 5
k=2
d = ((k*phi)+1)/e
print("d =", d)
print(f'Public key: {e, n}')
print(f'Private key: {d, n}')

# plain text
msg = 11
print(f'Original message:{msg}')

# encryption
C = pow(msg, e)
C = math.fmod(C, n)
print(f'Encrypted message: {C}')

# decryption
M = pow(C, d)
M = math.fmod(M, n)

print(f'Decrypted message: {M}')

Output

n = 21
e=5
d = 5.0
Public key: (5, 21)
Private key: (5.0, 21)
Original message:11
Encrypted message: 2.0
Decrypted message: 11.0

PRACTICAL - 7

HMAC MODULE

# Python 3 code to demonstrate the working of the 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())

OUTPUT
Hexdigest: df2ae7cdb5c849001e33ee29eb1c51ba2cafbaa7
Hexdigest after update: 3923273eb3aa9328478eb5aabf2d96e185256b4b
Digest size: 20 bytes
Block size: 64 bytes
Canonical name: hmac-sha1
Digest: b"9#'>\xb3\xaa\x93(G\x8e\xb5\xaa\xbf-\x96\xe1\x85%kK"
Hexdigest of clone: 3923273eb3aa9328478eb5aabf2d96e185256b4b

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy