Practical 4 & 5 CNS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

2CEIT5PE11: Cryptography and Network Security Practical - 4

Aim : Write a program to perform encryption and decryption using Polyalphabetic


Cipher (Vigenere Cipher) Technique.
def vigenere_encrypt(plain_text, key):
encrypted_text = ''
key_repeated = (key * (len(plain_text) // len(key))) + key[:len(plain_text) % len(key)]

for i in range(len(plain_text)):
if plain_text[i].isalpha():
shift = ord(key_repeated[i].upper()) - ord('A')
if plain_text[i].isupper():
encrypted_text += chr((ord(plain_text[i]) + shift - ord('A')) % 26 +
ord('A'))
else:
encrypted_text += chr((ord(plain_text[i]) + shift - ord('a')) % 26 +
ord('a'))
else:
encrypted_text += plain_text[i]
return encrypted_text

def vigenere_decrypt(cipher_text, key):


decrypted_text = ''
key_repeated = (key * (len(cipher_text) // len(key))) + key[:len(cipher_text) %
len(key)]
for i in range(len(cipher_text)):
if cipher_text[i].isalpha():
shift = ord(key_repeated[i].upper()) - ord('A')
if cipher_text[i].isupper():
decrypted_text += chr((ord(cipher_text[i]) - shift - ord('A')) % 26 +
ord('A'))
else:
decrypted_text += chr((ord(cipher_text[i]) - shift - ord('a')) % 26 +
ord('a'))
else:
decrypted_text += cipher_text[i]
return decrypted_text

key = input("enter key:")


plaintext = input('[!] Enter your message: ')
cipher_text = vigenere_encrypt(plaintext, key)
print("plain text is : ",plaintext)
print("Cipher is: ",cipher_text)
ask_to_decrypt = input('\n\n[?] Do you want to decrypt the message?\n[?] Y or N:
').lower()
if ask_to_decrypt == 'y':
decrypted_text = vigenere_decrypt(cipher_text, key)
print("Decrypted text: ",decrypted_text)
elif ask_to_decrypt == 'n':
sys.exit()
else:
print(f"{Fore.RED}[-] Invalid input.")

Enrollment No: 22012021100 Page No: 5


2CEIT5PE11: Cryptography and Network Security Practical - 4

Enrollment No: 22012021100 Page No: 6


2CEIT5PE11: Cryptography and Network Security Practical - 5
Aim : Write a program to perform encryption and decryption using Play-fair Cipher
Technique.
Procedure: The best-known multiple letter encryption cipher is the Playfair. It is a symmetric-encryption
technique. The Play-Fair algorithm uses a 5x5 matrix of letters called Playfair square or Wheatston-square,
constructed using keyword.

Steps for filling a Keyword Matrix:


Procedure
• The keyword is filled from left to right in the matrix.
• Here “I/J” is supposed to be placed in a single block since there are 26 letters in English.
• Only “I/J” are supposed to be placed in a single block.
• Repeated letters are ignored.
• After filling the keyword, the remaining letters are filled in alphabetical order.

Rules
1. Divide Plain text into pairs of letters. Example: BA|LL|OO|N
2. If a pair contains repeated letters, we can use a filler letter such as “X” and rearrange the letters.
Example: BA|LX|LO|ON
3. When a letter is left alone, we can add “x” in the end. Example: BUT -> BU|TX 4. If two letters are
in the same row, replace them with the immediate right.
5. If two letters are in the same column, replace them with immediate below.
6. If two letters are not in the same row or column, we draw a rectangle enclosed with those letters. In
this case direction will be matter to choose the letter as cipher letter.
7. If two letters are in the same row, but there is no letter to the right, we return to the first letter from
the left in circular way.
8. If two letters are in the same column, but there is no letter immediate below, we return to the first
letter from the column in circular way.

EXAMPLE:

PLAIN TEXT: BALLOONS


KEYWORD (or PLAY-FAIR KEYWORD): CEITDEPARTMENT

OUTPUT:
PLAY-FAIR KEYWORD MATRIX:
C E I T D
P A R M N
B F G H K
L O Q S U
V W X Y Z
ENCRYPTION:
PLAIN-TEXT ARRANGMENT: BA LX LO ON SX
CIPHER-TEXT: FPQVOQUAQY

DECRYPTION:
CIPHER-TEXT: FPQVOQUAQY
PLAIN-TEXT: BALXLOONSX --> Remove ‘X’ So, Message is: BALLOONS

Enrollment No: 22012021100 Page No: 7


2CEIT5PE11: Cryptography and Network Security Practical - 5
Code:
# Function to locate the position of a character in the 5x5 cipher matrix
def indexlocator(char):
for i in range(5):
for j in range(5):
if ciphermatrix[i][j] == char:
return i, j
#Initializing variables a and b for use in recursion in filling other characters
a = b = 0
#Getting user inputs Key (to make the 5x5 char matrix) and Plain Text
key = input("Enter key: ")
key = key.replace(" ", "")
key = key.upper()
plaintext = input("Plain text: ")
plaintext = plaintext.replace(" ", "")
plaintext = plaintext.upper()
# The function matrix that creates a nested list recursively (5x5 grid)
def matrix(x, y, initial):
return [[initial for i in range(x)] for j in range(y)]
# Populating keyintomatrix with unique characters from the key
keyintomatrix = list()
for c in key:
if c not in keyintomatrix:
if c == 'J':
keyintomatrix.append('I')
else:
keyintomatrix.append(c)
# Filling the rest of the matrix with unused letters from the alphabet
for i in range(65, 91):
if chr(i) not in keyintomatrix:
if i == 73 and chr(74) not in keyintomatrix:
keyintomatrix.append("I")
a = 1
elif a == 0 and i == 73 or i == 74:
pass
else:
keyintomatrix.append(chr(i))
# Defining the cipher matrix as a 5x5 matrix with an initial value of 0
ciphermatrix = matrix(5, 5, 0)
for i in range(0, 5):
for j in range(0, 5):
ciphermatrix[i][j] = keyintomatrix[b] # Populating ciphermatrix with characters
b += 1
# Encryption function using the Playfair cipher encryption method
def encryption(text):
i = 0
# Adjusting the text by inserting 'X' if there are identical pairs or if the length is odd
for s in range(0, len(text) + 1, 2):
if s < len(text) - 1:
if text[s] == text[s + 1]:
text = text[:s + 1] + 'X' + text[s + 1:]
if len(text) % 2 != 0:
text = text[:] + 'X'
Enrollment No: 22012021100 Page No: 8
2CEIT5PE11: Cryptography and Network Security Practical - 5
print("Cipher Text: ", end=' ')
while i < len(text):
# Locating the positions of the two characters in the matrix
lst = indexlocator(text[i])
lon = indexlocator(text[i + 1])

# If both characters are in the same column


if lst[1] == lon[1]:
print(f"{ciphermatrix[(lst[0] + 1) % 5][lst[1]]}{ciphermatrix[(lon[0] + 1) %
5][lon[1]]}", end=' ')
# If both characters are in the same row
elif lst[0] == lon[0]:
print(f"{ciphermatrix[lst[0]][(lst[1] + 1) % 5]}{ciphermatrix[lon[0]][(lon[1]
+ 1) % 5]}", end=' ')
# If the characters form a rectangle, swap their columns
else:
print(f"{ciphermatrix[lst[0]][lon[1]]}{ciphermatrix[lon[0]][lst[1]]}", end='
')
i += 2

# Running the encryption function


encryption(plaintext)

Q.1: PLAIN TEXT : GOODMORNING KEY: HELLO

Q.2: PLAIN TEXT: GANPATUNIVERSITY KEY: CEITDEPARTMENT

Q.3: PLAIN TEXT: PLAYFAIR KEY: CIPHER

Q.4: PLAIN TEXT: PRACTICAL KEY: THEORY

Q.5: PLAIN TEXT: FINDANSWER KEY: TECHNIQUE

Q.6: PLAIN TEXT: ENCIPHER KEY: LAB

Q.7: PLAIN TEXT: FINALANSWER KEY: LASTQUESTION

Enrollment No: 22012021100 Page No: 9

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