KESHAV MAHAVIDYALAYA
NAAC Accredited Grade ‘A’- Cycle 2
H-4-5 Zone, Sainik Vihar, Pitampura, Delhi -110034
(University of Delhi)
Name: Sumit Kumar
Roll No. : 16125
Course: BSC(H) Computer Science
Practical File
Table of Contents:
1. Write a program to perform encryption and decryption using Caesar
cipher (substitutional cipher).
2. Write a program to perform encryption and decryption using Rail
Fence Cipher (transpositional cipher)
3. Write a Python program that defines a function and takes a password
string as input and returns its SHA-256 hashed representation as a
hexadecimal string.
4. Write a Python program that reads a file containing a list of usernames
and passwords, one pair per line (separated by a comma). It checks each
password to see if it has been leaked in a data breach. You can use the
"Have I Been Pwned" API ([Link] to
check if a password has been leaked.
5. Write a Python program that generates a password using a random
combination of words from a dictionary file.
6. Write a Python program that simulates a brute-force attack on a
password by trying out all possible character combinations.
7. Demonstrate the usage/sending of a digitally signed document.
Q. 1. Write a program to perform encryption and decryption
using Caesar cipher (substitutional cipher)
def caesar_cipher(text, shift, mode):
result = ''
if mode == 'decrypt':
shift = -shift
for char in text:
if [Link]():
start = ord('a') if [Link]() else ord('A')
shifted_char = chr(((ord(char) - start + shift) %
26 )+ start)
else:
shifted_char = char
if mode == 'decrypt':
result = result + shifted_char
else:
result += shifted_char
return result
def menu():
while True:
print("Caeser Cipher Menu")
print("1. Encrypt")
print("2. Decrypt")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
text = input("Enter the text to encrypt: ")
shift = int(input("Enter the shift value: "))
encrypted_text = caesar_cipher(text, shift,
'encrypt')
print("Encrypted:", encrypted_text)
elif choice == '2':
text = input("Enter the text to decrypt: ")
shift = int(input("Enter the shift value: "))
decrypted_text = caesar_cipher(text, shift,
'decrypt')
print("Decrypted:", decrypted_text)
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
menu()
Q. 2. Write a program to perform encryption and decryption using
Rail Fence Cipher (transpositional cipher)
def encrypt_rail_fence(text, depth):
rail = [['\n' for i in range(len(text))] for j in
range(depth)]
dir_down = False
row, col = 0, 0
for i in range(len(text)):
if (row == 0) or (row == depth - 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(depth):
for j in range(len(text)):
if rail[i][j] != '\n':
[Link](rail[i][j])
return "".join(result)
def decrypt_rail_fence(cipher, depth):
rail = [['\n' for i in range(len(cipher))] for j in
range(depth)]
dir_down = None
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == depth - 1:
dir_down = False
rail[row][col] = '*'
col += 1
if dir_down:
row += 1
else:
row -= 1
index = 0
for i in range(depth):
for j in range(len(cipher)):
if rail[i][j] == '*' and index <
len(cipher):
rail[i][j] = cipher[index]
index += 1
result = []
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == depth-1:
dir_down = False
if rail[row][col] != '*':
[Link](rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return "".join(result)
if __name__ == "__main__":
while True:
print("\nMenu:")
print("1. Encrypt a message")
print("2. Decrypt a message")
print("3. Exit")
choice = input("Enter your choice : ")
if choice == '1':
message = input("Enter the message to
encrypt: ")
depth = int(input("Enter the depth (number
of rails): "))
cipher_text = encrypt_rail_fence(message,
depth)
print(f"Encrypted Message: {cipher_text}")
elif choice == '2':
cipher_text = input("Enter the message to
decrypt: ")
depth = int(input("Enter the depth (number
of rails): "))
decrypted_text =
decrypt_rail_fence(cipher_text, depth)
print(f"Decrypted Message:
{decrypted_text}")
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")
Q. 3. Write a Python program that defines a function and takes a
password string as input and returns its SHA-256 hashed
representation as a hexadecimal string.
import rsa
def generateHash(input):
msgInBinary = [Link]('utf-8')
return rsa.compute_hash(msgInBinary, 'SHA-256')
def main():
while True:
print("\nMenu:")
print("1. Generate Hash")
print("2. Exit")
choice = input("Enter your choice: ")
if choice == '1':
user_input = input('Enter the Password : ')
output = generateHash(user_input)
print('Generated Hash: ', output)
print('Generated Hash in Hexa: ',
[Link]())
print('Length of Hex :
',len([Link]()))
elif choice == '2':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Q. 4. Write a Python program that reads a file containing a list of
usernames and passwords, one pair per line (separated by a
comma). It checks each password to see if it has been leaked in a
data breach. You can use the "Have I Been Pwned" API
([Link] to check if a password has
been leaked.
import hashlib
import requests
def hash_password(password):
sha1_hash =
hashlib.sha1([Link]()).hexdigest().upper()
print("SHA1 Hash genarated : ",sha1_hash)
return sha1_hash
def check_password_pwned(hash_prefix):
url =
f'[Link]
response = [Link](url)
return [Link]
def check_credentials(file_name):
with open(file_name, 'r') as file:
for line in file:
username, password =
[Link]().split(',')
sha1_hash = hash_password(password)
prefix = sha1_hash[:5]
suffix = sha1_hash[5:]
response = check_password_pwned(prefix)
if suffix in response:
print(f'Password for {username} has
been leaked!')
else:
print(f'Password for {username} is
safe.')
check_credentials('[Link]')
Q. 5. Write a Python program that generates a password using a
random combination of words from a dictionary file.
import random
with open('[Link]', 'r') as file:
items = [Link]().splitlines()
words = [item for item in items if [Link]()]
numbers = [item for item in items if [Link]()]
special_chars = [item for item in items if not
[Link]()]
def generate_password(password_length):
password = ''
password += [Link](words).capitalize()
password += [Link](words).lower()
password += [Link](numbers)
password += [Link](special_chars)
while len(password) < password_length:
word = [Link](words)
number = [Link](numbers)
special_char = [Link](special_chars)
password += word + number + special_char
if len(password) > password_length:
excess_length = len(password) -
password_length
password = password[:-excess_length]
return password
def menu():
while True:
print("\nMenu:")
print("1. Generate a password")
print("2. Exit")
choice = input("Enter your choice (1/2): ")
if choice == '1':
while True:
try:
password_length = int(input("Enter
the desired password length (8-12): "))
if 8 <= password_length <= 12:
break
else:
print("Please enter a number
between 8 and 12.")
except ValueError:
print("Invalid input! Please enter
a number between 8 and 12.")
password =
generate_password(password_length)
print(f"Generated Password: {password}")
another = input("Would you like to generate
another password? (yes/no): ").lower()
if another != 'yes':
break
elif choice == '2':
print("Exiting...")
break
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
menu()
Q. 6. Write a Python program that simulates a brute-force
attack on a password by trying out all possible character
combinations.
import itertools
import string
def bruteforce_attack(password):
chars = [Link]()
attempts = 0
for length in range(1, len(password) + 1):
for guess in [Link](chars,
repeat=length):
attempts += 1
guess = ''.join(guess)
if guess == password:
return (attempts, guess)
return (attempts, None)
password = input("Input the password to crack: ")
attempts, guess = bruteforce_attack(password)
if guess:
print(f"Password cracked in {attempts} attempts.
The password is {guess}.")
else:
print(f"Password not cracked after {attempts}
attempts.")
Q. 7. Demonstrate the usage/sending of a digitally signed
document.
import rsa
def generate_keys():
(public_key, private_key) = [Link](2048) #
2048-bit key length
return public_key, private_key
def sign_document(document, private_key):
document_bytes = [Link]('utf-8')
signature = [Link](document_bytes, private_key,
'SHA-256')
return signature
def send_document(document, signature):
return {
'document': document,
'signature': signature
def verify_signature(document, signature, public_key):
document_bytes = [Link]('utf-8')
try:
[Link](document_bytes, signature,
public_key)
print("The signature is valid, and the document
is authentic.")
except [Link]:
print("The signature is invalid, or the
document has been tampered with.")
def main():
public_key, private_key = generate_keys()
document = "This is a confidential document that
needs to be signed."
signature = sign_document(document, private_key)
sent_data = send_document(document, signature)
print(f"Original Document:
{sent_data['document']}")
verify_signature(sent_data['document'],
sent_data['signature'], public_key)
if __name__ == "__main__":
main()