0% found this document useful (0 votes)
25 views35 pages

Is Ex - 1 - To - 10

Gtu Material

Uploaded by

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

Is Ex - 1 - To - 10

Gtu Material

Uploaded by

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

211260107049

Practical : - 1

AIM: Write a Program to implement Caesar Cipher.


EXERCISE:
write a program to implement Caesar cipher in any programming language.
Ans:-
Language Used:- Python
Code:-
def encrypt(text, shift):
result = ""
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
# Encrypt lowercase characters
elif char.islower():
result += chr((ord(char) + shift - 97) % 26 + 97)
# Non-alphabetical characters are added as is
else:
result += char
return result
def decrypt(text, shift):
return encrypt(text, -shift)
# Get user input
message = input("Enter the message: ")
shift_value = int(input("Enter the shift key (number): "))

1
IS(3170720)
211260107049

# Perform encryption
encrypted_message = encrypt(message, shift_value)
print(f"Encrypted Message: {encrypted_message}")
# Perform decryption
decrypted_message = decrypt(encrypted_message, shift_value)
print(f"Decrypted Message: {decrypted_message}")

Output:-

2
IS(3170720)
211260107049

Practical : - 2

AIM: Write a Program to implement Mono-alphabetic Cipher.


EXCERCISE:
write a program to implement mono-alphabetic cipher in any programming
language.
Ans:-
Language Used:- Python
Code:-
import string
def generate_cipher_alphabet(key):
# Create a substitution alphabet based on the provided key
alphabet = string.ascii_lowercase
cipher_alphabet = ''
for char in key.lower():
if char not in cipher_alphabet and char in alphabet:
cipher_alphabet += char
# Add remaining letters that are not in the key
for char in alphabet:
if char not in cipher_alphabet:
cipher_alphabet += char
return cipher_alphabet
def encrypt(plaintext, cipher_alphabet):
alphabet = string.ascii_lowercase
ciphertext = ""
for char in plaintext.lower():
if char in alphabet:
index = alphabet.index(char)
3
IS(3170720)
211260107049

ciphertext += cipher_alphabet[index]
else:
ciphertext += char # Non-alphabet characters are added as is
return ciphertext
def decrypt(ciphertext, cipher_alphabet):
alphabet = string.ascii_lowercase
plaintext = ""
for char in ciphertext:
if char in cipher_alphabet:
index = cipher_alphabet.index(char)
plaintext += alphabet[index]
else:
plaintext += char # Non-alphabet characters are added as is
return plaintext
# Example usage
key = input("Enter the key for the cipher (a word or phrase): ").replace(" ", "")
plaintext = input("Enter the message to encrypt: ")
cipher_alphabet = generate_cipher_alphabet(key)
encrypted_message = encrypt(plaintext, cipher_alphabet)
print(f"Encrypted Message: {encrypted_message}")
decrypted_message = decrypt(encrypted_message, cipher_alphabet)
print(f"Decrypted Message: {decrypted_message}")
Output:-

4
IS(3170720)
211260107049

Practical : - 3

AIM: Write a Program to implement Polyalphabetic Cipher.


EXERCISE:
write a program to implement poly-alphabetic cipher in any programming
language.
Ans:-
Language Used:- Python
Code:-
def generate_key(plaintext, keyword):
key = list(keyword)
if len(plaintext) == len(key):
return key
else:
for i in range(len(plaintext) - len(key)):
key.append(key[i % len(key)])
return "".join(key)
def encrypt_vigenere(plaintext, keyword):
key = generate_key(plaintext, keyword)
ciphertext = []
for i in range(len(plaintext)):
if plaintext[i].isalpha():
# Calculate shift and wrap around using modulo
shift = (ord(plaintext[i].upper()) + ord(key[i].upper())) % 26
cipher_char = chr(shift + ord('A'))
ciphertext.append(cipher_char if plaintext[i].isupper() else
cipher_char.lower())
else:
5
IS(3170720)
211260107049

ciphertext.append(plaintext[i]) # Non-alphabetic characters are


unchanged
return "".join(ciphertext)
def decrypt_vigenere(ciphertext, keyword):
key = generate_key(ciphertext, keyword)
plaintext = []
for i in range(len(ciphertext)):
if ciphertext[i].isalpha():
# Calculate shift and wrap around using modulo
shift = (ord(ciphertext[i].upper()) - ord(key[i].upper()) + 26) % 26
plain_char = chr(shift + ord('A'))
plaintext.append(plain_char if ciphertext[i].isupper() else
plain_char.lower())
else:
plaintext.append(ciphertext[i]) # Non-alphabetic characters are
unchanged
return "".join(plaintext)
# Example usage
plaintext = input("Enter the plaintext: ")
keyword = input("Enter the keyword: ")
# Encrypting the plaintext
ciphertext = encrypt_vigenere(plaintext, keyword)
print(f"Encrypted Message: {ciphertext}")
# Decrypting the ciphertext
decrypted_message = decrypt_vigenere(ciphertext, keyword)
print(f"Decrypted Message: {decrypted_message}")

6
IS(3170720)
211260107049

Output:-

7
IS(3170720)
211260107049

Practical : - 4

AIM: Write a Program to implement Play fair Cipher.


EXCERCISE:
write a program to implement play fair cipher in any programming
language.
Ans:-
Language Used:- Python
Code:-
def create_matrix(key):
key = key.upper().replace("J", "I")
matrix = []
used_chars = set()
for char in key:
if char not in used_chars and char.isalpha():
matrix.append(char)
used_chars.add(char)
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
for char in alphabet:
if char not in used_chars:
matrix.append(char)
return [matrix[i:i+5] for i in range(0, 25, 5)]
def format_message(message):
message = message.upper().replace("J", "I").replace(" ", "")
formatted_message = ""
i=0
while i < len(message):
formatted_message += message[i]
8
IS(3170720)
211260107049

if i + 1 < len(message) and message[i] == message[i + 1]:


formatted_message += "X"
elif i + 1 < len(message):
formatted_message += message[i + 1]
i += 2
if len(formatted_message) % 2 != 0:
formatted_message += "X"
return formatted_message
def find_position(matrix, char):
for i, row in enumerate(matrix):
for j, matrix_char in enumerate(row):
if matrix_char == char:
return i, j
return None
def encrypt_pair(pair, matrix):
row1, col1 = find_position(matrix, pair[0])
row2, col2 = find_position(matrix, pair[1])
if row1 == row2:
return matrix[row1][(col1 + 1) % 5] + matrix[row2][(col2 + 1) % 5]
elif col1 == col2:
return matrix[(row1 + 1) % 5][col1] + matrix[(row2 + 1) % 5][col2]
else:
return matrix[row1][col2] + matrix[row2][col1]
def encrypt_message(message, matrix):
formatted_message = format_message(message)
ciphertext = ""
for i in range(0, len(formatted_message), 2):

9
IS(3170720)
211260107049

pair = formatted_message[i:i+2]
ciphertext += encrypt_pair(pair, matrix)
return ciphertext
# Main program to take input from user
key = input("Enter the keyword: ")
message = input("Enter the message to encrypt: ")
matrix = create_matrix(key)
ciphertext = encrypt_message(message, matrix)
print("\nPlayfair Cipher Key Matrix:")
for row in matrix:
print(" ".join(row))
print("\nFormatted Message:", format_message(message))
print("Encrypted Message:", ciphertext)

Output:-

10
IS(3170720)
211260107049

Practical : - 5

AIM: Write a Program to implement Hill Cipher for 3*3 matrix.


EXCERCISE:
write a program to implement Hill cipher in any programming language.
Ans:-
Language Used:-
Code:-
import numpy as np
from math import gcd
def mod_inverse(matrix, modulus):
determinant = int(np.round(np.linalg.det(matrix)))
determinant_mod = determinant % modulus
if gcd(determinant_mod, modulus) != 1:
raise ValueError(f"The key matrix is not invertible under modulo
{modulus}. Please choose a different key matrix.")
inverse_determinant = pow(determinant_mod, -1, modulus)
matrix_modulus_inverse = (
inverse_determinant * np.round(np.linalg.inv(matrix) *
determinant).astype(int)
) % modulus
return matrix_modulus_inverse
def encrypt(message, key_matrix):
message = message.upper().replace(" ", "")
message_numbers = [ord(char) - ord('A') for char in message]
# Padding with 'X' if the length of the message is not a multiple of key matrix
size
while len(message_numbers) % key_matrix.shape[0] != 0:

11
IS(3170720)
211260107049

message_numbers.append(ord('X') - ord('A')) # Padding with 'X'


message_matrix = np.array(message_numbers).reshape(-1,
key_matrix.shape[0])
cipher_matrix = (np.dot(message_matrix, key_matrix) % 26)
ciphertext = ''.join(chr(num + ord('A')) for num in cipher_matrix.flatten())
return ciphertext
def decrypt(ciphertext, key_matrix):
inverse_key_matrix = mod_inverse(key_matrix, 26)
cipher_numbers = [ord(char) - ord('A') for char in ciphertext]
cipher_matrix = np.array(cipher_numbers).reshape(-1, key_matrix.shape[0])
message_matrix = (np.dot(cipher_matrix, inverse_key_matrix) % 26)
message = ''.join(chr(num + ord('A')) for num in message_matrix.flatten())
return message
def main():
message = input("Enter the plaintext message: ")
key_size = int(input("Enter the size of the key matrix (e.g., 2 for 2x2 matrix, 3
for 3x3 matrix): "))
print("Enter the key matrix (row-wise, separated by spaces):")
key_elements = list(map(int, input().split()))
key_matrix = np.array(key_elements).reshape(key_size, key_size)
print("\nKey Matrix:")
print(key_matrix)
try:
ciphertext = encrypt(message, key_matrix)
print("\nEncrypted Message:", ciphertext)
decrypted_message = decrypt(ciphertext, key_matrix)
print("Decrypted Message:", decrypted_message)
except ValueError as e:

12
IS(3170720)
211260107049

print(f"Error: {e}")
if name == " main ":
main()

Output:-

13
IS(3170720)
211260107049

Practical : - 6

AIM: Write a Program to implement Transposition technique.


EXCERCISE:
write a program to implement Transposition technique in any programming
language.
Ans:-
Language Used:- Python
Code:-
def rail_fence_encrypt(plaintext, rails):
# Remove spaces and handle lowercase characters
plaintext = plaintext.replace(" ", "").upper()
if rails <= 1:
raise ValueError("Number of rails must be greater than 1.")
# Create the rail fence grid
fence = [['' for _ in range(len(plaintext))] for _ in range(rails)]
row, step = 0, 1
# Fill the rail fence grid
for i in range(len(plaintext)):
fence[row][i] = plaintext[i]
if row == 0 or row == rails - 1:
step = -step
row += step
# Read off the rows to create the ciphertext
ciphertext = ''.join(''.join(row).replace('', '') for row in fence)
return ciphertext
def rail_fence_decrypt(ciphertext, rails):

14
IS(3170720)
211260107049

if rails <= 1:
raise ValueError("Number of rails must be greater than 1.")
num_cols = len(ciphertext)
rail = [['' for _ in range(num_cols)] for _ in range(rails)]
# Reconstruct the rail fence grid with placeholders
row, step = 0, 1
for i in range(num_cols):
rail[row][i] = '*'
if row == 0 or row == rails - 1:
step = -step
row += step
# Fill the rail fence grid with ciphertext characters
index = 0
for i in range(rails):
for j in range(num_cols):
if rail[i][j] == '*':
rail[i][j] = ciphertext[index]
index += 1
# Read off the grid in zigzag pattern to get the plaintext
result = []
row, step = 0, 1
for i in range(num_cols):
result.append(rail[row][i])
if row == 0 or row == rails - 1:
step = -step
row += step
return ''.join(result)

15
IS(3170720)
211260107049

def main():
message = input("Enter the plaintext message: ")
rails = int(input("Enter the number of rails: "))
if rails < 2:
print("Number of rails must be 2 or more.")
return
print("\nEncrypting...")
try:
ciphertext = rail_fence_encrypt(message, rails)
print("Encrypted Message:", ciphertext)
print("\nDecrypting...")
decrypted_message = rail_fence_decrypt(ciphertext, rails)
print("Decrypted Message:", decrypted_message)
except Exception as e:
print(f"ERROR! {e}")
if name == " main ":
main()
Output:-

16
IS(3170720)
211260107049

Practical : - 7

AIM: Write a Program to implement RSA Algorithm.


EXCERCISE:
write a program to implement RSA Algorithm in any programming
language.
Ans:-
Language Used:- Python
Code:-
import random
# Function to compute gcd
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# Function to generate large prime numbers
def generate_large_prime():
while True:
prime_candidate = random.randint(100, 200)
if is_prime(prime_candidate):
return prime_candidate
# Function to check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
17
IS(3170720)
211260107049

return True
# Function to compute modular inverse using the Extended Euclidean Algorithm
def mod_inverse(e, phi):
t, newt = 0, 1
r, newr = phi, e
while newr != 0:
quotient = r // newr
t, newt = newt, t - quotient * newt
r, newr = newr, r - quotient * newr
if r > 1:
raise ValueError("e is not invertible")
if t < 0:
t = t + phi
return t
# RSA Key Generation
def generate_keys():
# Step 1: Select two large prime numbers p and q
p = generate_large_prime()
q = generate_large_prime()
print(f"Selected primes: p = {p}, q = {q}")
# Step 2: Compute n = p * q
n=p*q
# Step 3: Compute Euler's Totient function phi(n)
phi_n = (p - 1) * (q - 1)
# Step 4: Choose e such that 1 < e < phi(n) and gcd(e, phi(n)) = 1
e = random.randrange(2, phi_n)
while gcd(e, phi_n) != 1:

18
IS(3170720)
211260107049

e = random.randrange(2, phi_n)
print(f"Public exponent e = {e}")
# Step 5: Compute d, the modular multiplicative inverse of e modulo phi(n)
d = mod_inverse(e, phi_n)
print(f"Private exponent d = {d}")
# Public key: (e, n), Private key: (d, n)
return (e, n), (d, n)
# RSA Encryption: c = m^e mod n
def encrypt(plaintext, public_key):
e, n = public_key
ciphertext = [pow(ord(char), e, n) for char in plaintext]
return ciphertext
# RSA Decryption: m = c^d mod n
def decrypt(ciphertext, private_key):
d, n = private_key
decrypted_text = ''.join([chr(pow(char, d, n)) for char in ciphertext])
return decrypted_text
# Driver code
if name == ' main ':
# Key generation
public_key, private_key = generate_keys()
print(f"Public Key: {public_key}")
print(f"Private Key: {private_key}")
# Plaintext message
message = input("Enter the message to encrypt: ")
# Encrypt the message
encrypted_message = encrypt(message, public_key)

19
IS(3170720)
211260107049

print(f"Encrypted message: {encrypted_message}")


# Decrypt the message
decrypted_message = decrypt(encrypted_message, private_key)
print(f"Decrypted message: {decrypted_message}")

Output:-

20
IS(3170720)
211260107049

Practical : - 8

AIM: Write a Program to implement Diffie-Hellman Key Exchange Algorithm.


EXCERCISE:
write a program to implement Diffie-Hellman Key in any programming
language.
Ans:-
Language Used:- Python
Code:-
import random
# Function to perform modular exponentiation
# It returns (base^exp) % mod
def mod_exp(base, exp, mod):
return pow(base, exp, mod)
# Diffie-Hellman Key Exchange
def diffie_hellman_key_exchange():
# Step 1: Agree on a large prime number p and a base g
p = 23 # A small prime number for simplicity, but in practice, it should be
much larger
g = 5 # A primitive root modulo p
print(f"Publicly known values: p = {p}, g = {g}")
# Step 2: Alice selects a private key a (secret)
a = random.randint(1, p - 1)
print(f"Alice's private key (a): {a}")

# Step 3: Bob selects a private key b (secret)


b = random.randint(1, p - 1)
print(f"Bob's private key (b): {b}")
21
IS(3170720)
211260107049

# Step 4: Alice computes A = g^a mod p and sends it to Bob


A = mod_exp(g, a, p)
print(f"Alice computes A = g^a mod p: A = {A}")
# Step 5: Bob computes B = g^b mod p and sends it to Alice
B = mod_exp(g, b, p)
print(f"Bob computes B = g^b mod p: B = {B}")
# Step 6: Alice computes the shared secret key: K_A = B^a mod p
K_A = mod_exp(B, a, p)
print(f"Alice computes the shared secret key: K_A = B^a mod p: K_A =
{K_A}")
# Step 7: Bob computes the shared secret key: K_B = A^b mod p
K_B = mod_exp(A, b, p)
print(f"Bob computes the shared secret key: K_B = A^b mod p: K_B =
{K_B}")
# The shared secret key should be the same for both Alice and Bob
if K_A == K_B:
print(f"Shared secret key successfully computed: {K_A}")
else:
print("Error in key exchange! The keys do not match.")

# Driver code
if name == ' main ':
diffie_hellman_key_exchange()

22
IS(3170720)
211260107049

Output:-

23
IS(3170720)
211260107049

Practical : - 9

AIM: Perform Various Encryption-Decryption techniques with cryptool.


EXCERCISE:
1. What is Cryptool?
Ans:-
CrypTool is a comprehensive, free e-learning program about cryptography and
cryptanalysis
(cryptology). CrypTool is a freeware and open source program which enables you
to apply
and analyze cryptographic mechanisms. It has the typical look-and-feel of
Windows
applications.
CrypTool contains exhaustive online help, which can be understood without
extensive
knowledge of cryptography.
CrypTool has been continuously developed since 1998. It is available in English,
German,
Polish, Serbian and Spanish. Versions in Greek und Russian are currently under
construction. CrypTool has implemented almost all state-of-the-art crypto
functions and
allows you to learn about and use cryptography within the same environment.
2. Encryption and Decryption of Any Cipher (implement for atleast 4
techniques).
Ans:-
Caesar Cipher Technique:
The formula of encryption is:
En (x) = (x + n) mod 26
The formula of decryption is:

24
IS(3170720)
211260107049

Dn (x) = (xi - n) mod 26

Example:

Plain Text: Google Cipher Text: Jrrjoh


Key: 3

Vigenere Cipher:

Formula of encryption is, Ei = (Pi + Ki) mod 26 Formula of decryption is, Di =

(Ei - Ki) mod 26 Example:

Plain Text: Hello Cipher Text: Khoor

Key: D

25
IS(3170720)
211260107049

Hill cipher:

Formula of encryption is, E(K, P) = (K * P)

mod 26 Formula of decryption is, D(K, C) =

(K-1 * C) mod 26 Example:

Plain Text: WORLD Cipher Text: ALBDND


Key: WV AA

Monoalphabetic Cipher:

Formula of encryption is,

C=( P + K ) mod 26

Formula of decryption is,

P=( C-K ) mod 26.

(‘P’ is the character in plain text, ‘K’ is the key, and ‘C’ is the Cipher.)

Example:

26
IS(3170720)
211260107049

Plain Text: SECURITY Cipher Text:


SDBURHTY

Key: LABCDEFGHIJKMNOPQRSTUVWXYZ

27
IS(3170720)
211260107049

Practical : - 10

AIM: Study and use the wires hark for the various network Protocols
EXCERCISE:
Explain Installation and working of Wireshak for Windows?
Ans:-
Wireshark is software that is widely used in the analysis of data packets in a
network. Wireshark is completely free and open source. This packet analyzer is
used for a variety of purposes like troubleshooting networks, understanding
communication between two systems, developing new protocols, etc. The
original name of Wireshark was Ethereal which was changed in 2006 due to some
company’s copyright issues. This software is written in C and C++, and its initial
release was in the year 1998. Its latest release is 3.6.0 which got released on 22
November 2021. Wireshark is a cross-platform software, it can be run on Linux,
windows, mac, and any other operating system.
Installing Wireshark on Windows:
Follow the below steps to install Wireshark on Windows:
Step 1: Visit the official Wireshark website using any web browser.

Step 2: Click on Download, a new webpage will open with different


installers of Wireshark.

28
IS(3170720)
211260107049

Step 3: Downloading of the executable file will start shortly. It is a small


73.69 MB file that will take some time.

Step 4: Now check for the executable file in downloads in your system and
run it.

29
IS(3170720)
211260107049

Step 5: It will prompt confirmation to make changes to your system. Click


on Yes.

Step 6: Setup screen will appear, click on Next.

Step 7: The next screen will be of License Agreement, click on Noted.

30
IS(3170720)
211260107049

Step 8: This screen is for choosing components, all components are already
marked so don’t change anything just click on the Next button.

Step 9: This screen is of choosing shortcuts like start menu or desktop icon
along with file extensions which can be intercepted by Wireshark, tick all
boxes and click on Next button.

Step 10: The next screen will be of installing location so choose the drive
which will have sufficient memory space for installation. It needed only a
memory space of 223.4 MB.

31
IS(3170720)
211260107049

Step 11: Next screen has an option to install Npcap which is used with
Wireshark to capture packets pcap means packet capture so the install
option is already checked don’t change anything and click the next button.

Step 12: Next screen is about USB network capturing so it is one’s choice to
use it or not, click on Install.

Step 13: After this installation process will start.

32
IS(3170720)
211260107049

Step 14: This installation will prompt for Npcap installation as already
checked so the license agreement of Npcap will appear to click on the I
Agree button.

Step 15: Next screen is about different installing options of npcap, don’t do
anything click on Install.

Step 16: After this installation process will start which will take only a
minute.

Step 17: After this installation process will complete click on the Next
button.

33
IS(3170720)
211260107049

Step 18: Click on Finish after the installation process is complete.

Step 19: After this installation process of Wireshark will complete click on
the Next button.

Step 20: Click on Finish after the installation process of Wireshark is


complete.

34
IS(3170720)
211260107049

Wireshark is successfully installed on the system and an icon is created on


the desktop as shown below:

Now run the software and see the interface.

At this point, successfully installed Wireshark on your windows system.

35
IS(3170720)

You might also like