0% found this document useful (0 votes)
8 views37 pages

Isrecord (21211a05b5)

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)
8 views37 pages

Isrecord (21211a05b5)

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/ 37

B.V.

Raju Institute of Technology


(UGC AUTONOMUS)
Vishnupur (V), Narsapur (M), Medak (Dist)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INFORMATION SECURITY LAB

LAB RECORD
(III B. Tech. II SEM)
(Computer Science and Engineering)
B.V. RAJU INSTITUTE OF TECHNOLOGY
(UGC Autonomous, NBA and NAAC Accredited)
VISHNUPUR, NARSAPUR, MEDAK DIST.
www.bvrit.ac.in

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

Certified that this is a bonafide record of lab work done by

Mr./Ms. ……………….…………….…………………. bearing Roll No.

………………… of …………Year B.Tech..………Sem. in the

……….………………….... during the academic year …………. …..

Number of Programs done:

Date:

Signature of Lab Faculty Signature of HOD

External Examiner

1
INDEX

S.No. Experiment Name Page no Date of Date of signat


conduct submit ure

2
S.No Experiment Name Page no Date of Date of signat
conduct submit ure

3
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-1
1. Implement the following Substitution Techniques
a) Ceaser Cipher
b) Playfair Cipher
1a) Ceaser Cipher:
AIM: Python program to implement Ceaser Cipher substitution Technique
def caesar_encrypt(text, shift):
"""Encrypts the given text using Caesar Cipher with the specified shift."""
encrypted_text = "
for char in text:
if char.isalpha():
shift_amount = 65 if char.isupper() else 97
encrypted_char = chr((ord(char) - shift_amount + shift) % 26 + shift_amount)
encrypted_text += encrypted_char
else:
encrypted_text += char

return encrypted_text

def caesar_decrypt(text, shift):


"""Decrypts the given text using Caesar Cipher with the specified shift."""
return caesar_encrypt(text, -shift)

# Get inputs from user


plain_text = input("Enter the text to be encrypted: ")
shift = int(input("Enter the shift value: "))

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________

# Encrypt the text


encrypted_text = caesar_encrypt(plain_text, shift)
print(f"Encrypted: {encrypted_text}")

# Decrypt the text


decrypted_text = caesar_decrypt(encrypted_text, shift)
print(f"Decrypted: {decrypted_text}")

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
1b) Playfair cipher
AIM: Python program to implement Playfair Cipher substitution Technique
def generate_playfair_matrix(key):
key = ''.join(sorted(set(key), key=lambda x: key.index(x))) # Remove duplicates while
preserving order
key = key.replace('J', 'I') # Replace 'J' with 'I' to fit into the 5x5 matrix
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
matrix = [char for char in key if char in alphabet]
matrix.extend([char for char in alphabet if char not in matrix])
return [matrix[i * 5:(i + 1) * 5] for i in range(5)]

def preprocess_text(text):
text = text.upper().replace('J', 'I').replace(' ', '')
new_text = ''
i=0
while i < len(text):
new_text += text[i]
if i + 1 < len(text) and text[i] == text[i + 1]:
new_text += 'X'
elif i + 1 == len(text):
new_text += 'X'
else:
new_text += text[i + 1]
i += 1
i += 1
return new_text

def find_position(matrix, char):

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
for row in range(5):
for col in range(5):
if matrix[row][col] == char:
return row, col
return None

def playfair_encrypt(matrix, text):


encrypted_text = ''
text = preprocess_text(text)
for i in range(0, len(text), 2):
char1, char2 = text[i], text[i + 1]
row1, col1 = find_position(matrix, char1)
row2, col2 = find_position(matrix, char2)
if row1 == row2:
encrypted_text += matrix[row1][(col1 + 1) % 5]
encrypted_text += matrix[row2][(col2 + 1) % 5]
elif col1 == col2:
encrypted_text += matrix[(row1 + 1) % 5][col1]
encrypted_text += matrix[(row2 + 1) % 5][col2]
else:
encrypted_text += matrix[row1][col2]
encrypted_text += matrix[row2][col1]
return encrypted_text

def playfair_decrypt(matrix, text):


decrypted_text = ''
for i in range(0, len(text), 2):
char1, char2 = text[i], text[i + 1]
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
row1, col1 = find_position(matrix, char1)
row2, col2 = find_position(matrix, char2)
if row1 == row2:
decrypted_text += matrix[row1][(col1 - 1) % 5]
decrypted_text += matrix[row2][(col2 - 1) % 5]
elif col1 == col2:
decrypted_text += matrix[(row1 - 1) % 5][col1]
decrypted_text += matrix[(row2 - 1) % 5][col2]
else:
decrypted_text += matrix[row1][col2]
decrypted_text += matrix[row2][col1]
return decrypted_text

# Get inputs from user


key = input("Enter the key: ")
plain_text = input("Enter the text to be encrypted: ")

# Generate Playfair matrix


matrix = generate_playfair_matrix(key)

# Encrypt the text


encrypted_text = playfair_encrypt(matrix, plain_text)
print(f"Encrypted: {encrypted_text}")

# Decrypt the text


decrypted_text = playfair_decrypt(matrix, encrypted_text)
print(f"Decrypted: {decrypted_text}")

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-2
2. Implement the following Substitution Techniques
a) Hill Cipher
b) Vigenere Cipher
c) One-Time pad

2a) Hill Cipher Program


AIM: Python program to implement Hill Cipher substitution Technique
import numpy as np

def mod_inverse(matrix, modulus):


"""Find the modular inverse of a matrix under a given modulus."""
det = int(np.round(np.linalg.det(matrix))) % modulus
det_inv = pow(det, -1, modulus)
matrix_modulus_inv = (
det_inv * np.round(det * np.linalg.inv(matrix)).astype(int) % modulus
)
return matrix_modulus_inv % modulus

def create_matrix_of_integers_from_string(string, n):


"""Create a matrix of integers from the given string."""
numbers = [ord(char) - ord('A') for char in string]
while len(numbers) % n != 0:
numbers.append(ord('X') - ord('A')) # Padding with 'X' if necessary
matrix = []
for i in range(0, len(numbers), n):
matrix.append(numbers[i:i + n])

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
return np.array(matrix)

def hill_encrypt(plain_text, key_matrix):


"""Encrypt the plaintext using the Hill cipher with the given key matrix."""
n = key_matrix.shape[0]
plain_matrix = create_matrix_of_integers_from_string(plain_text, n)
cipher_matrix = np.dot(plain_matrix, key_matrix) % 26
cipher_text = ''.join(chr(int(num) + ord('A')) for num in cipher_matrix.flatten())
return cipher_text

def hill_decrypt(cipher_text, key_matrix):


"""Decrypt the ciphertext using the Hill cipher with the given key matrix."""
n = key_matrix.shape[0]
cipher_matrix = create_matrix_of_integers_from_string(cipher_text, n)
key_matrix_inv = mod_inverse(key_matrix, 26)
plain_matrix = np.dot(cipher_matrix, key_matrix_inv) % 26
plain_text = ''.join(chr(int(num) + ord('A')) for num in plain_matrix.flatten())
return plain_text

def main():
# Get inputs from user
plain_text = input("Enter the text to be encrypted (A-Z only): ").upper().replace(' ', '')
key = input("Enter the key matrix as a single string (e.g., 'GYBNQKURP' for a 3x3 matrix):
").upper()

# Determine the size of the key matrix


n = int(len(key)**0.5)
if n**2 != len(key):

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
print("Invalid key length. The length of the key string should be a perfect square.")
return

key_matrix = np.array([ord(char) - ord('A') for char in key]).reshape(n, n)

# Encrypt the text


encrypted_text = hill_encrypt(plain_text, key_matrix)
print(f"Encrypted: {encrypted_text}")

# Decrypt the text


decrypted_text = hill_decrypt(encrypted_text, key_matrix)
print(f"Decrypted: {decrypted_text}")

if __name__ == "__main__":
main()

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
2b) Vigenere Cipher Program
AIM: Python program to implement Vigenere Cipher substitution Technique
def generate_key(text, key):
"""Generates the key in a cyclic manner until its length matches the length of the text."""
key = list(key)
if len(text) == len(key):
return "".join(key)
else:
for i in range(len(text) - len(key)):
key.append(key[i % len(key)])
return "".join(key)

def vigenere_encrypt(plain_text, key):


"""Encrypts the plain text using the Vigenère cipher with the given key."""
cipher_text = []
key = generate_key(plain_text, key)
for i in range(len(plain_text)):
if plain_text[i].isalpha():
shift = (ord(plain_text[i].upper()) + ord(key[i].upper()) - 2 * ord('A')) % 26
encrypted_char = chr(shift + ord('A'))
if plain_text[i].islower():
encrypted_char = encrypted_char.lower()
cipher_text.append(encrypted_char)
else:
cipher_text.append(plain_text[i])
return "".join(cipher_text)

def vigenere_decrypt(cipher_text, key):


_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
"""Decrypts the cipher text using the Vigenère cipher with the given key."""
orig_text = []
key = generate_key(cipher_text, key)
for i in range(len(cipher_text)):
if cipher_text[i].isalpha():
shift = (ord(cipher_text[i].upper()) - ord(key[i].upper()) + 26) % 26
decrypted_char = chr(shift + ord('A'))
if cipher_text[i].islower():
decrypted_char = decrypted_char.lower()
orig_text.append(decrypted_char)
else:
orig_text.append(cipher_text[i])
return "".join(orig_text)

# Driver code
if __name__ == "__main__":
plain_text = input("Enter the text to be encrypted: ")
key = input("Enter the key: ")

# Encrypt the text


encrypted_text = vigenere_encrypt(plain_text, key)
print("Ciphertext:", encrypted_text)

# Decrypt the text


decrypted_text = vigenere_decrypt(encrypted_text, key)
print("Original/Decrypted Text:", decrypted_text)

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
2c) One-Time Pad Program
AIM: Python program to implement One-Time Pad substitution Technique
import random
import string

def generate_otp_key(length):
"""Generates a random key of specified length."""
return ''.join(random.choice(string.ascii_uppercase) for _ in range(length))

def otp_encrypt(plain_text, key):


"""Encrypts the plain text using the One-Time Pad cipher with the given key."""
encrypted_text = []
for i in range(len(plain_text)):
if plain_text[i].isalpha():
shift = (ord(plain_text[i].upper()) + ord(key[i])) % 26
encrypted_char = chr(shift + ord('A'))
if plain_text[i].islower():
encrypted_char = encrypted_char.lower()
encrypted_text.append(encrypted_char)
else:
encrypted_text.append(plain_text[i])
return ''.join(encrypted_text)

def otp_decrypt(encrypted_text, key):


"""Decrypts the encrypted text using the One-Time Pad cipher with the given key."""
decrypted_text = []
for i in range(len(encrypted_text)):
if encrypted_text[i].isalpha():
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
shift = (ord(encrypted_text[i].upper()) - ord(key[i]) + 26) % 26
decrypted_char = chr(shift + ord('A'))
if encrypted_text[i].islower():
decrypted_char = decrypted_char.lower()
decrypted_text.append(decrypted_char)
else:
decrypted_text.append(encrypted_text[i])
return ''.join(decrypted_text)

# Get inputs from user


plain_text = input("Enter the text to be encrypted: ")
key = generate_otp_key(len(plain_text))
print(f"Generated key: {key}")

# Encrypt the text


encrypted_text = otp_encrypt(plain_text, key)
print(f"Encrypted: {encrypted_text}")

# Decrypt the text


decrypted_text = otp_decrypt(encrypted_text, key)
print(f"Decrypted: {decrypted_text}")

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-3
3. Implement the following Transposition Techniques
a) Rail fence
b) Row & Columnar transposition

3a) Rail fence Program


AIM: Python program to implement Rail fence Transposition technique.
def encryptRailFence(text, key):
rail = [['\n' for i in range(len(text))]
for j in range(key)]
dir_down = False
row, col = 0, 0
for i in range(len(text)):
if (row == 0) or (row == key - 1):
dir_down = not dir_down
rail[row][col] = text[i]
col += 1
if dir_down:
row += 1
else:
row -= 1
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))

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
def decryptRailFence(cipher, key):
rail = [['\n' for i in range(len(cipher))]
for j in range(key)]

dir_down = None
row, col = 0, 0

for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False
rail[row][col] = '*'
col += 1
if dir_down:
row += 1
else:
row -= 1

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

result = []
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key-1:
dir_down = False
if (rail[row][col] != '*'):
result.append(rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return("".join(result))

if __name__ == "__main__":
print(encryptRailFence("Sumanth", 2))
print(encryptRailFence("Luffy ", 3))
print(encryptRailFence("KingoftheNorth",3))

print(decryptRailFence("Smnhuat", 3))
print(decryptRailFence("Lyuf f", 2))
print(decryptRailFence("KoetigfhNrhnto", 3))

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
3b) Row & Columnar Program
AIM: Python program to implement Row & Columnar Transposition technique.
import math
def encryptMessage(msg, key):
cipher = ""
k_indx = 0
msg_len = float(len(msg))
msg_lst = list(msg)
key_lst = sorted(list(key))
col = len(key)
row = int(math.ceil(msg_len / col))
fill_null = int((row * col) - msg_len)
msg_lst.extend('_' * fill_null)
matrix = [msg_lst[i: i + col] for i in range(0, len(msg_lst), col)]
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
def decryptMessage(cipher, key):
msg = ""
k_indx = 0
msg_indx = 0
msg_len = float(len(cipher))
msg_lst = list(cipher)
col = len(key)
row = int(math.ceil(msg_len / col))
key_lst = sorted(list(key))
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
dec_cipher = []
for _ in range(row):
dec_cipher += [[None] * col]
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
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
if __name__ == "__main__":
msg = input("Enter the message to encrypt: ")
key = input("Enter the encryption key: ")

cipher = encryptMessage(msg, key)


print("Encrypted Message: {}".format(cipher))
decrypted_msg = decryptMessage(cipher, key)
print("Decrypted Message: {}".format(decrypted_msg))
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-4
4. Implement the following Symmetric Key algorithms
a) DES
b) AES

4a) DES Program


AIM: Python program to implement DES technique.
from Crypto.Cipher import DES
import hashlib
import base32hex
password = "Wonderful"
salt = b'\x28\xAB\xBC\xCD\xDE\xEF\x00\x33'
key = password.encode('utf-8') + salt
m = hashlib.md5()
m.update(key)
key = m.digest()
dk, iv = key[:8], key[8:]
crypter = DES.new(dk, DES.MODE_CBC, iv)
plain_text = "Life is beautiful"
print("The plain text is:", plain_text)
pad_length = 8 - (len(plain_text) % 8)
plain_text += chr(pad_length) * pad_length
ciphertext = crypter.encrypt(plain_text.encode('utf-8'))
encode_string = base32hex.b32encode(ciphertext)
print("The encoded string is:", encode_string)

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
4b) AES Program
AIM: Python program to implement AES technique.
from Crypto.Cipher import AES
import hashlib
import base32hex

password = "Parvathi"
salt = b'\x28\xAB\xBC\xCD\xDE\xEF\x00\x33'

key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 1000)


dk, iv = key[:16], key[16:] # AES-128, so key is 16 bytes, IV is also 16 bytes

crypter = AES.new(dk, AES.MODE_CBC, iv)

plain_text = "Life is beautiful"


print("The plain text is:", plain_text)

pad_length = 16 - (len(plain_text) % 16)


plain_text += chr(pad_length) * pad_length
ciphertext = crypter.encrypt(plain_text.encode('utf-8'))

encode_string = base32hex.b32encode(ciphertext)
print("The encoded string is:", encode_string)

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-5
5. Implement the RC4 Stream cipher
AIM: Pyhton program to implement RC4 Stream cipher.
def KSA(key):
key_length = len(key)
S = list(range(256))
j=0
for i in range(256):
j = (j + S[i] + key[i % key_length]) % 256
S[i], S[j] = S[j], S[i] # Swap
return S

def PRGA(S):
i=0
j=0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i] # Swap
K = S[(S[i] + S[j]) % 256]
yield K

def RC4(key, plaintext):


S = KSA(key)
keystream = PRGA(S)
ciphertext = ''
for char in plaintext:
ciphertext += chr(ord(char) ^ next(keystream))
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
return ciphertext

# Example usage:
key = input("Enter the encryption key: ")
plaintext = input("Enter the plaintext: ")

encrypted_text = RC4(list(map(ord, key)), plaintext)


print("Encrypted:", encrypted_text)

decrypted_text = RC4(list(map(ord, key)), encrypted_text)


print("Decrypted:",decrypted_text)

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-6
6. Implement the following Asymmetric Key algorithms
a) RSA
b) Diffie-Hellman Key Exchange
6a) RSA Program
AIM: Pyhton program to implement RSA technique.
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64

# Generate key pair


key = RSA.generate(2048)

# Get public and private keys


public_key = key.publickey()
private_key = key
# Encrypt message
cipher = PKCS1_OAEP.new(public_key)
encrypted = cipher.encrypt(b"Hello, world!")
# Encode encrypted message using base64
encrypted_base64 = base64.b64encode(encrypted)
# Decrypt message
cipher = PKCS1_OAEP.new(private_key)
decrypted = cipher.decrypt(encrypted)
print("Original:", "Hello, world!")
print("Encrypted:", encrypted_base64)
print("Decrypted:", decrypted.decode())

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
6b) Diffie-Hellman Key Exchange Program
AIM: Pyhton program to implement Diffie-Hellman Key Exchange technique.
def generate_shared_secret(p, g, private_key):
shared_secret = (g ** private_key) % p
return shared_secret
p = int(input("Enter the prime number (p): "))
g = int(input("Enter the base (g): "))
private_key_A = int(input("Enter Alice's private key: "))
private_key_B = int(input("Enter Bob's private key: "))
shared_secret_A = generate_shared_secret(p, g, private_key_A)
shared_secret_B = generate_shared_secret(p, g, private_key_B)
print("Alice's shared secret:", shared_secret_A)
print("Bob's shared secret:", shared_secret_B)
# Verifying the shared secret
if shared_secret_A == shared_secret_B:
print("Shared secrets match! Secure connection established.")
else:
print("Shared secrets do not match! Connection compromised.")

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-7
7. Implement the following MAC / Hash function Cryptography algorithms
a) SHA-512
7a) SHA-512 Program
AIM: Pyhton program to implement SHA-512
import hashlib
def sha512_hash(text):
# Create a new sha512 hash object
sha512 = hashlib.sha512()
# Encode the input text to bytes, then update the hash object with it
sha512.update(text.encode('utf-8'))
# Get the hexadecimal representation of the digest
return sha512.hexdigest()
# Driver code
if __name__ == "__main__":
# Take input from user
input_text = input("Enter the text to hash: ")
# Get the SHA-512 hash of the input text
hash_result = sha512_hash(input_text)
# Print the resulting hash
print(f"SHA-512 hash of '{input_text}' is: {hash_result}")

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-8
8. Implement the following MAC / Hash function Cryptography algorithms
a) HMAC
8a) HMAC Program
AIM: Pyhton program to implement HMAC
import hmac
import hashlib
import secrets
def generate_key(length=32):
return secrets.token_hex(length)
def create_hmac(message, key):
hmac_obj = hmac.new(key.encode(), message.encode(), hashlib.sha256)
return hmac_obj.hexdigest()
def verify_hmac(message, key, received_hmac):
hmac_obj = hmac.new(key.encode(), message.encode(), hashlib.sha256)
return hmac.compare_digest(hmac_obj.hexdigest(), received_hmac)
# Driver code
if __name__ == "__main__":
message = input("Enter the message: ")
key = generate_key()
print(f"Generated Key: {key}")
hmac_result = create_hmac(message, key)
print(f"HMAC: {hmac_result}")
received_hmac = input("Enter the received HMAC for verification: ")
if verify_hmac(message, key, received_hmac):
print("HMAC verification successful.")
else:
print("HMAC verification failed.")
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
Week-9
9. Implement the signature scheme named Digital Signature Standard
AIM: Pyhton program to implement Digital Signature Standard
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
from cryptography.hazmat.primitives import serialization
# Function to generate DSA key pair
def generate_dsa_keys():
private_key = dsa.generate_private_key(key_size=2048)
public_key = private_key.public_key()
return private_key, public_key

# Function to sign a message


def sign_message(private_key, message):
message_bytes = message.encode()
signature = private_key.sign(
message_bytes,
hashes.SHA256()
)
return signature
# Function to verify a signature
def verify_signature(public_key, message, signature):
message_bytes = message.encode()
try:
public_key.verify(
signature,
message_bytes,
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
hashes.SHA256()
)
return True
except Exception as e:
print(f"Verification failed: {e}")
return False
# Function to serialize keys for storage
def serialize_keys(private_key, public_key):
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return private_pem, public_pem
# Function to deserialize keys from storage
def deserialize_keys(private_pem, public_pem):
private_key = serialization.load_pem_private_key(private_pem, password=None)
public_key = serialization.load_pem_public_key(public_pem)
return private_key, public_key
# Driver code
if __name__ == "__main__":
# Generate DSA keys
private_key, public_key = generate_dsa_keys()
# Serialize keys
_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
INFORMATION SECURITY LAB DATE:
PAGE NO:
_____________________________________________________________________________________________
private_pem, public_pem = serialize_keys(private_key, public_key)
# Deserialize keys
private_key, public_key = deserialize_keys(private_pem, public_pem)
# Take a message from the user
message = input("Enter the message to sign: ")
# Sign the message
signature = sign_message(private_key, message)
print(f"Signature: {signature.hex()}")
# Verify the signature
if verify_signature(public_key, message, signature):
print("Signature verification successful.")
else:
print("Signature verification failed.")

_______________________________________________________________________________________________
Department of CSE BV Raju Institute of Technology III Year II Sem
Date:
Information Security Lab Page No:

Week 10
10. Analyze the IP packet using Wireshark and observe the AH & ESP
protocols
Aim: To analyze the IP packet using Wireshark and observe the AH & ESP
protocols
Wireshark is a free, open-source software application for capturing and analyzing network
packets. Wireshark can help users glean valuable insights about the network’s activity and
identify issues or threats by capturing and analyzing these packets.

Capturing data packets on Wireshark


When you open Wireshark, you see a screen showing you a list of all the network connections
you can monitor. You also have a capture filter field to only capture the network traffic you
want to see.

You can select one or more of the network interfaces using shift+left-click. Once select the
network interface, you can start the capture, and there are several ways to do that.
Click the first button on the toolbar, titled “Start capturing packets.”

Department of CSE BV Raju Institute of Technology III Year II Sem


Date:
Information Security Lab Page No:

You can select the menu item Capture -> Start.

During the capture, Wireshark will show you the packets captured in real-time.

Department of CSE BV Raju Institute of Technology III Year II Sem


Date:
Information Security Lab Page No:

Once you have captured all the packets needed, use the same buttons or menu options to
stop the capture as you did to begin.

Best practice dictates stopping Wireshark’s packet capture before analysis.

Analyzing data packets on Wireshark


Wireshark shows you three different panes for inspecting packet data. The Packet List, the top
pane, lists all the packets in the capture. When you click on a packet, the other two panes
change to show you the details about the selected packet. You can also tell if the packet is part
of a conversation. Here are details about each column in the top pane:

 No.: This is the number order of the packet captured. The bracket indicates that this
packet is part of a conversation.
 Time: This column shows how long after you started the capture this particular packet
was captured. You can change this value in the Settings menu to display a different
option.
 Source: This is the address of the system that sent the packet.
 Destination: This is the address of the packet destination.
 Protocol: This is the type of packet. For example: TCP, DNS, DHCPv6, or ARP.
 Length: This column shows you the packet’s length, measured in bytes.
 Info: This column shows you more information about the packet contents, which will
vary depending on the type of packet.

Department of CSE BV Raju Institute of Technology III Year II Sem


Date:
Information Security Lab Page No:

Packet Details, the middle pane, shows you as much readable information about the packet
as possible, depending on the packet type. You can right-click and create filters based on the
highlighted text in this field.
The bottom pane, Packet Bytes, displays the packet exactly as it was captured in hexadecimal.

When looking at a packet that is part of a conversation, you can right-click the packet and
select Follow to see only the packets that are part of that conversation.
 In the display filter bar on the screen, enter TCP and apply the filter.

 From analyzing the menu in the menu bar select display filters or from capture
select capture filters and then TCP only and ok.

 In the display filter bar on the screen, enter ESP and apply the filter.

Department of CSE BV Raju Institute of Technology III Year II Sem


Date:
Information Security Lab Page No:

Department of CSE BV Raju Institute of Technology III Year II Sem

You might also like