0% found this document useful (0 votes)
30 views

Cryptography Lab

Uploaded by

Sujal Parmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Cryptography Lab

Uploaded by

Sujal Parmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

CONTENTS

S.NO PROGRAMS Page No.


I Lab description 3
II Lab objectives 3
III Lab outcomes 3
1V Lab requirements 4

PROGRAMS TO BE PRACTICED
Part - A
1. Write a Java program to perform encryption and
decryption using the following algorithms
a) Ceaser Cipher 5
b) Substitution Cipher
c) Hill Cipher
2 Write a program to implement the DES algorithm logic 8
3. Write a program to implement RSA Algorithm 11
4. Implement the Diffie-Hellman Key Exchange
mechanism using HTML and JavaScript. Consider the
15
end user as one of the parties (Alice) and the JavaScript
application as other party (bob)
5. Calculate the message digest of a text using the SHA-1
19
algorithm
Part - B

1. Perform an experiment to demonstrate how to Sniff for


23
Router traffic by using the tool Wireshark
2 Perform a Wireless Audit of an Access Point / Router and
Decrypt Wep and Wpa. 30

3. Perform an axperiment to Sniff Traffic using Arp


38
Poisoning.
4. Install Jcrypt Tool (Or Any Other Equivalent) and
demonstrate Asymmetric, Symmetric Crypto Algorithm, 40
Hash and Digital/Pki Signatures.
5. Demonstrate Intrusion Detection System (Ids) using any
tool. Eg. Snort or any other S/W.
I. Lab DESCRIPTION
This laboratory course supplements the material taught in the theory course
Cryptography and Network Security. The objective of this lab is to get hands-on
experience in Computer Networks, Cryptography and Network Security
concepts using simulation tools Viz.Wireshark, Nmap, SNIFF, SNORT,
JCRYPT, etc.. Laboratory exercises will normally be conducted on UNIX
Operating system. The students will be exposed to simulating and analyzing
concepts.

II. LAB OBJECTIVES


The objectives of this lab course are to make students to:
• To understand basics of Cryptography and Network Security.
• To be able to secure a message over insecure channel by various means.
• To learn about how to maintain the Confidentiality, Integrity and
Availability of a data.
• To understand various protocols for network security to protect against
the threats in the networks.
III. LAB OUTCOMES
On successful completion of this course; the student will be able to:
CO1: Apply the cryptographic algorithms for data communication
CO2: Compare the performance of various security algorithms
CO3: Apply the Digital signature for secure data transmission
CO4: Calculate the message digest of a text using the SHA-1 algorithm
CO5: Utilize the different open source tools for network security and analysis.
CO6: Demonstrate intrusion detection system using network security tool.

IV. LAB REQUIREMENTS


Following are the required hardware and software for this lab.
ü Hardware: Desktop system or Virtual machine in a cloud with OS
installed. Presently in the Lab, i3Process or having 8GBRAM and
500GB HardDisk is available. Desktop systems are dual boot having
Windows as well as LinuxOS installed on them.
ü Software: A Java Editor with compiler. Wireshark, Packet Tracer and
Nmap, JCrypt, Snort.
PROGRAM 1
Write a python program to perform encryption and decryption using the
following algorithms
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher

A) CEASER CIPHER
AIM: Python program to perform encryption and Decryption of the Caesar
cipher algorithm.

SOURCE CODE:
def caesar_cipher(text, shift):
result = " "
# Loop through each character in the text
for char in text:
if char.isalpha(): # Check if the character is a letter
shift_amount = shift % 26 # Ensure shift is within alphabet range
# Determine the ASCII offset based on uppercase or lowercase letter
ascii_offset = 65 if char.isupper() else 97
# Calculate the new character's position in the alphabet
new_char = chr((ord(char) - ascii_offset + shift_amount) % 26 +
ascii_offset)
result += new_char
else
result += char

return result
plaintext = input("Enter the plain text")
shift = int(input("Entre the number of shifts"))
ciphertext = caesar_cipher(plaintext, shift)
print("Plaintext for caesar:", plaintext)
print("Shift:", shift)
print("Ciphertext from caesar:", ciphertext)
originaltext = caesar_cipher(ciphertext, -shift)
print("Originaltext for caesar:", originaltext)

OUTPUT:

RESULT:
We have successfully executed the source code for Caeser cipher and the output
is obtained.
B) SUBSTITUTION CIPHER

AIM: Python program to perform encryption and Decryption of the Substitution


cipher algorithm.

SOURCE CODE:
import string
def generate_substitution_key():
# Generates a random substitution key by shuffling the alphabet
alphabet = list(string.ascii_lowercase)
shuffled_alphabet = alphabet[:]
import random
random.shuffle(shuffled_alphabet)
return dict(zip(alphabet, shuffled_alphabet))

def encrypt(plaintext, key):


ciphertext = ""
for char in plaintext:
if char.isalpha():
# Preserve the case of the letter
is_upper = char.isupper()
# Get the corresponding encrypted character from the key
encrypted_char = key[char.lower()]
# Convert back to uppercase if necessary
if is_upper:
encrypted_char = encrypted_char.upper()
ciphertext += encrypted_char
else:
ciphertext += char # Non-alphabetic characters are added unchanged
return ciphertext

def decrypt(ciphertext, key):


reversed_key = {v: k for k, v in key.items()}
plaintext = ""
for char in ciphertext:
if char.isalpha():
# Preserve the case of the letter
is_upper = char.isupper()
# Get the corresponding decrypted character from the reversed key
decrypted_char = reversed_key[char.lower()]
# Convert back to uppercase if necessary
if is_upper:
decrypted_char = decrypted_char.upper()
plaintext += decrypted_char
else:
plaintext += char # Non-alphabetic characters are added unchanged
return plaintext

# Generate a substitution key


substitution_key = generate_substitution_key()
print("Substitution Key:", substitution_key)

# Example usage
plaintext = input("Enter the plain text")
ciphertext = encrypt(plaintext, substitution_key)
print("Plaintext:", plaintext)
print("Ciphertext:", ciphertext)

# Decrypt the ciphertext back to plaintext


decrypted_text = decrypt(ciphertext, substitution_key)
print("Decrypted Text:", decrypted_text)

OUTPUT:

RESULT

We have successfully executed the source code for Substitution cipher and the
output is obtained
C) HILL CIPHER

AIM: Python program to perform encryption and Decryption of the Hill


cipher algorithm.

SOURCE CODE:

import numpy as np

keyMatrix = [[0] * 3 for _ in range(3)]


messageVector = [[0] for _ in range(3)]
cipherMatrix = [[0] for _ in range(3)]

def getKeyMatrix(key):
k=0
for i in range(3):
for j in range(3):
keyMatrix[i][j] = ord(key[k]) - 65 # Convert to range 0-25
k += 1

def mod_inverse(a, m):


"""Compute the modular inverse of a modulo m."""
a=a%m
for x in range(1, m):
if (a * x) % m == 1:
return x
raise ValueError(f"No modular inverse for {a} modulo {m}")

def matrix_inverse(A, mod=26):


"""Compute the inverse of a 3x3 matrix modulo mod."""
def determinant(matrix):
"""Compute the determinant of a 3x3 matrix."""
a, b, c, d, e, f, g, h, i = matrix.flatten()
return (a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g)) % mod

def adjugate(matrix):
"""Compute the adjugate of a 3x3 matrix."""
a, b, c, d, e, f, g, h, i = matrix.flatten()
adjugate_matrix = np.array([
[e*i - f*h, c*h - b*i, b*f - c*e],
[f*g - d*i, a*i - c*g, c*d - a*f],
[d*h - e*g, b*g - a*h, a*e - b*d]
])
return adjugate_matrix

# Compute the determinant of A


det = determinant(A)

# Find the modular inverse of the determinant


det_inv = mod_inverse(det, mod)

# Compute the adjugate matrix


adjugate = adjugate(A)

# Compute the inverse matrix


inv_matrix = (det_inv * adjugate) % mod

return inv_matrix

def encrypt(messageVector):
for i in range(3):
for j in range(1):
cipherMatrix[i][j] = 0
for x in range(3):
cipherMatrix[i][j] += (messageVector[x][j] * keyMatrix[i][x])
cipherMatrix[i][j] = cipherMatrix[i][j] % 26

def decrypt(cipherMatrix, keyMatrix):


A = np.array(keyMatrix)
A_inv = matrix_inverse(A)

print("Inverse matrix modulo 26:")


print(A_inv)

decryptedMatrix = [[0] for _ in range(3)]


for i in range(3):
for j in range(1):
decryptedMatrix[i][j] = 0
for x in range(3):
decryptedMatrix[i][j] += (A_inv[i][x] * cipherMatrix[x][j])
decryptedMatrix[i][j] = decryptedMatrix[i][j] % 26

return decryptedMatrix

def HillCipher(message, key):


getKeyMatrix(key)

print("Key Matrix:")
for row in keyMatrix:
print(row)

for i in range(3):
messageVector[i][0] = ord(message[i]) - 65 # Convert message to
matrix
print("Message Matrix:")
for row in messageVector:
print(row)

encrypt(messageVector)

print("Cipher Matrix:")
for row in cipherMatrix:
print(row)

CipherText = []
for i in range(3):
CipherText.append(chr(cipherMatrix[i][0] + 65)) # Convert back to
letters
print("Ciphertext: ", "".join(CipherText))

decryptedMatrix = decrypt(cipherMatrix, keyMatrix)

print("Decrypted Matrix:")
for row in decryptedMatrix:
print(row)
DecryptedText = []
for i in range(3):
DecryptedText.append(chr(decryptedMatrix[i][0] + 65)) # Convert
back to letters
print("Decrypted Text: ", "".join(DecryptedText))

# Driver Code
def main():
message = "MOR" # Example message
key = "RVCRSCFVT" # Example key
HillCipher(message, key)

if __name__ == "__main__":
main()

OUTPUT:

RESULT:
We have successfully executed the source code for Hill cipher and the output is
obtained
PROGRAM 2
DATA ENCRYPTION STANDARDS

AIM: Write a program to implement the DES algorithm logic.

SOURCE CODE:
!pip install pycryptodome

from Crypto.Cipher import DES


from Crypto.Util.Padding import pad, unpad
import binascii

# Function to encrypt data using DES


def encrypt_des(key, data):
# Ensure the key is 8 bytes (DES key size)
key = key.encode('utf-8')
cipher = DES.new(key, DES.MODE_CBC)

# Pad the data to be multiple of block size (8 bytes for DES)


padded_data = pad(data.encode('utf-8'), DES.block_size)

# Encrypt the padded data


encrypted_data = cipher.encrypt(padded_data)

# Return the IV (Initialization Vector) and encrypted data


return binascii.hexlify(cipher.iv).decode('utf-
8'), binascii.hexlify(encrypted_data).decode('utf-8')
# Function to decrypt data using DES
def decrypt_des(key, iv, encrypted_data):
key = key.encode('utf-8')
iv = binascii.unhexlify(iv)
encrypted_data = binascii.unhexlify(encrypted_data)

# Create DES cipher with the same key and IV


cipher = DES.new(key, DES.MODE_CBC, iv)

# Decrypt the data


decrypted_data = cipher.decrypt(encrypted_data)

# Remove padding from the decrypted data


decrypted_data = unpad(decrypted_data, DES.block_size)

return decrypted_data.decode('utf-8')

# Example usage
if __name__ == "__main__":
# Sample key and data
key = '12345678' # Key must be 8 bytes for DES
data = 'naveen'

# Encrypt data
iv, encrypted_data = encrypt_des(key, data)
print("Encrypted Data:", encrypted_data)
print("IV:", iv)

# Decrypt data
decrypted_data = decrypt_des(key, iv, encrypted_data)
print("Decrypted Data:", decrypted_data)

OUTPUT:

RESULT:
We have successfully executed the DES source code and the output is obtained.
PROGRAM 3
RSA

AIM: Write a python code to perform encryption and decryption in RSA


algorithm.

SOURCE CODE:
from math import gcd

def RSA(p: int, q: int, message: int):


# Calculate n and t (Euler's Totient)
n=p*q
t = (p - 1) * (q - 1) # Correct totient

# Find e such that gcd(e, t) = 1


for e in range(2, t):
if gcd(e, t) == 1:
break

# Find d such that (e * d) % t = 1 (modular inverse)


d = pow(e, -1, t)

# Encrypt the message: ct = (message^e) % n


ct = pow(message, e, n)
print(f"Encrypted message is {ct}")

# Decrypt the message: mes = (ct^d) % n


mes = pow(ct, d, n)
print(f"Decrypted message is {mes}")

# Testing with p=3, q=7, and different messages


RSA(p=3, q=7, message=9)
RSA(p=3, q=7, message=17)

OUTPUT:

RESULT:
We have successfully executed the source code for RSA and the output is
obtained.
PROGRAM 4
DIFFIE-HELLMAN KEY EXCHANGE

AIM: Implement the Diffie-Hellman Key Exchange mechanism using HTML


and JavaScript. Consider the end user as one of the parties (Alice) and the
JavaScript application as other party (bob)

SOURCE CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diffie-Hellman Key Exchange</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
padding: 10px;
margin: 10px;
width: 300px;
font-size: 16px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.result {
margin-top: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Diffie-Hellman Key Exchange</h1>
<p>Enter your private key (Alice's private key)</p>
<input type="number" id="alicePrivateKey" placeholder="Enter Alice's
private key">
<button onclick="performKeyExchange()">Compute Shared Secret</button>

<div class="result" id="result"></div>

<script>
// Parameters agreed upon by Alice and Bob
const p = 23; // Prime number
const g = 5; // Primitive root mod p

// Bob's private key (This is chosen by Bob)


const bobPrivateKey = 6;

// Function to compute power modulo (base^exp % mod)


function powerMod(base, exp, mod) {
let result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 == 1) { // If exp is odd, multiply base with result
result = (result * base) % mod;
}
exp = Math.floor(exp / 2); // Divide exp by 2
base = (base * base) % mod; // Square the base
}
return result;
}

function performKeyExchange() {
// Get Alice's private key from the input field
const alicePrivateKey =
parseInt(document.getElementById("alicePrivateKey").value);

if (isNaN(alicePrivateKey) || alicePrivateKey <= 0) {


document.getElementById("result").innerText = "Please enter a valid
positive integer for Alice's private key.";
return;
}

// Compute Alice's public key (A = g^a mod p)


const alicePublicKey = powerMod(g, alicePrivateKey, p);

// Compute Bob's public key (B = g^b mod p)


const bobPublicKey = powerMod(g, bobPrivateKey, p);

// Exchange public keys and compute the shared secret key


const sharedSecretAlice = powerMod(bobPublicKey, alicePrivateKey,
p); // Alice computes
const sharedSecretBob = powerMod(alicePublicKey, bobPrivateKey, p);
// Bob computes

// Display the result


document.getElementById("result").innerHTML = `
Prime number (p): ${p} <br>
Primitive root (g): ${g} <br>
Alice's private key: ${alicePrivateKey} <br>
Alice's public key: ${alicePublicKey} <br>
Bob's public key: ${bobPublicKey} <br>
Shared secret key (Alice's calculation): ${sharedSecretAlice} <br>
Shared secret key (Bob's calculation): ${sharedSecretBob} <br>
`;
if (sharedSecretAlice === sharedSecretBob) {
document.getElementById("result").innerHTML += "<br>Success!
Both Alice and Bob have the same shared secret key.";
} else {
document.getElementById("result").innerHTML += "<br>Error! The
shared secret keys do not match.";
}
}
</script>
</body>
</html>
OUTPUT:

RESULT:
We have successfully executed the source code for Diffie-Hellman Key
Exchange and the output is obtained.
PROGRAM 5
SECURED HASH FUNCTION
AIM: Write a program in python to calculate the message digest of a text using
the SHA-1 algorithm

SOURCE CODE:

import hashlib
import ipywidgets as widgets
from IPython.display import display

# Function to perform hash step by step


def hash_step_by_step(input_string, output_widget, hash_algo):
input_bytes = input_string.encode('utf-8')
output_widget.clear_output()

with output_widget:
print(f"Step 1: Input string converted to bytes:
{input_bytes.hex()}")

# Choose hash algorithm based on user selection


if hash_algo == "SHA-1":
hash_object = hashlib.sha1()
hash_name = 'SHA-1'
else:
hash_object = hashlib.sha512()
hash_name = 'SHA-512'

with output_widget:
print(f"Step 2: {hash_name} object initialized")

hash_object.update(input_bytes)

with output_widget:
print(f"Step 3: Hash object updated with input bytes.
Intermediate {hash_name} hash value: {hash_object.hexdigest()}")

final_hash = hash_object.hexdigest()

with output_widget:
print(f"Step 4: Final {hash_name} hash: {final_hash}")

return final_hash

# Input text box for the user


input_box = widgets.Text(
description='Input String:',
placeholder='Type Something...',
style={'description_width': 'initial'}
)

# Button to trigger hash computation


compute_button = widgets.Button(
description='Compute Hashes',
button_style='primary' # Optional styling
)

# Output area for displaying results


output_area = widgets.Output()

# Dropdown to select hash algorithm (SHA-1 or SHA-512)


hash_algo_dropdown = widgets.Dropdown(
options=['SHA-1', 'SHA-512'],
value='SHA-512',
description='Hash Algorithm:'
)

# Button click event handler


def on_button_click(b):
input_string = input_box.value
selected_hash_algo = hash_algo_dropdown.value
if input_string:
hash_step_by_step(input_string, output_area,
selected_hash_algo)
else:
with output_area:
print("Please enter a valid input string.")

# Attach the button click handler


compute_button.on_click(on_button_click)

# Display the widgets


display(input_box, hash_algo_dropdown, compute_button,
output_area)

OUTPUT:
Text: Hello World

Step 1: Input string converted to bytes: 68656c6c6f20776f726c64


Step 2: SHA-512 object initialized
Step 3: Hash object updated with input bytes. Intermediate SHA-512
hash value:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b170e5a57ff7425e88c89f7f3d
9bb3f8b0cf91c4f489ed8f1d3e7a3b9189c5e9a7de9fbe1d9ad1fa87b6e
3a3baf74cf
Step 4: Final SHA-512 hash:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b170e5a57ff7425e88c89f7f3d
9bb3f8b0cf91c4f489ed8f1d3e7a3b9189c5e9a7de9fbe1d9ad1fa87b6e
3a3baf74cf
Text: Hello World
Step 1: Input string converted to bytes: 68656c6c6f20776f726c64
Step 2: SHA-1 object initialized
Step 3: Hash object updated with input bytes. Intermediate SHA-1
hash value: 2ef7bde608ce5404e97d5f042f95f89f1c232871
Step 4: Final SHA-1 hash:
2ef7bde608ce5404e97d5f042f95f89f1c232871

RESULT:
We have successfully executed the source code and the output for
both the algorithsm have been obtained .

You might also like