Priyanshu Practical File
Priyanshu Practical File
Practical Submission
Section : B
Question Mentioned in Practical List :
1. Write a program to perform encryption and decryption using Caesar cipher
(substitutional cipher).
3. Write a Python program that defines a function and takes a password string
string.
4. Write a Python program that reads a file containing a list of usernames and
password to see if it has been leaked in a data breach. You can use the "Have
result = ''
if mode == 'decrypt':
shift = -shift
if char.isalpha():
% 26 )+ start)
else:
shifted_char = char
if mode == 'decrypt':
else:
result += shifted_char
return result
def menu():
while True:
print("1. Encrypt")
print("2. Decrypt")
print("3. Exit")
if choice == '1':
'encrypt')
print("Encrypted:", encrypted_text)
'decrypt')
print("Decrypted:", decrypted_text)
break
else:
if __name__ == "__main__":
menu()
How the Caesar Cipher Works
Applications:
Limitations:
● It is not secure for modern use since the shift key can be
brute-forced (only 25 possible shifts).
Q. 2. Write a program to perform encryption and decryption using Rail
range(depth)]
dir_down = False
row, col = 0, 0
for i in range(len(text)):
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':
result.append(rail[i][j])
return "".join(result)
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)):
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] != '*':
result.append(rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return "".join(result)
if __name__ == "__main__":
while True:
print("\nMenu:")
print("3. Exit")
choice = input("Enter your choice : ")
if choice == '1':
encrypt: ")
of rails): "))
cipher_text = encrypt_rail_fence(message,
depth)
decrypt: ")
of rails): "))
decrypted_text =
decrypt_rail_fence(cipher_text, depth)
print(f"Decrypted Message:
{decrypted_text}")
elif choice == '3':
print("Exiting...")
break
else:
1. Encryption:
o The plaintext is written in a zigzag pattern using the number
of rows specified by the key.
o The characters are then read row by row to form the
encrypted text.
2. Decryption:
o Reconstructs the zigzag pattern by marking the path and
filling in the characters row by row.
o Reads the characters in a zigzag pattern to retrieve the
original plaintext.
Applications:
Limitations:
as a hexadecimal string.
import rsa
def generateHash(input):
msgInBinary = input.encode('utf-8')
def main():
while True:
print("\nMenu:")
print("2. Exit")
if choice == '1':
')
output = generateHash(user_input)
print('Generated Hash: ', output)
output.hex())
print('Length of Hex :
',len(output.hex()))
break
else:
if __name__ == "__main__":
main()
Applications
1.Password Storage:
2.Data Integrity:
checks each password to see if it has been leaked in a data breach. You
leaked.
import hashlib
import requests
def hash_password(password):
sha1_hash =
hashlib.sha1(password.encode()).hexdigest().upper()
return sha1_hash
def check_password_pwned(hash_prefix):
url =
f'https://api.pwnedpasswords.com/range/{hash_prefix}'
response = requests.get(url)
return response.text
def check_credentials(file_name):
username, password =
line.strip().split(',')
sha1_hash = hash_password(password)
prefix = sha1_hash[:5]
suffix = sha1_hash[5:]
response = check_password_pwned(prefix)
if suffix in response:
been leaked!')
else:
safe.')
check_credentials('credential.txt')
2. Password Checking:
o The program calculates the SHA-1 hash of the password and
splits it into:
▪ Prefix: First 5 characters sent to the API.
o If the suffix is found, the password has been leaked, and its
breach count is returned.
3. Output:
o The program prints whether each password is safe or has
been leaked, along with the breach count.
Security Note
items = file.read().splitlines()
item.isalnum()]
def generate_password(password_length):
password = ''
password += random.choice(words).capitalize()
password += random.choice(words).lower()
password += random.choice(numbers)
password += random.choice(special_chars)
word = random.choice(words)
number = random.choice(numbers)
special_char = random.choice(special_chars)
excess_length = len(password) -
password_length
password = password[:-excess_length]
return password
def menu():
while True:
print("\nMenu:")
print("2. Exit")
if choice == '1':
while True:
try:
password_length = int(input("Enter
break
else:
except ValueError:
password =
generate_password(password_length)
if another != 'yes':
break
elif choice == '2':
print("Exiting...")
break
else:
if __name__ == "__main__":
menu()
Explanation
● You can:
Security Tip
reduces security.
import itertools
import string
def bruteforce_attack(password):
chars = string.printable.strip()
attempts = 0
repeat=length):
attempts += 1
guess = ''.join(guess)
if guess == password:
if guess:
else:
attempts.")
Explanation
1. Password Length:
3. Real-World Applications:
o Demonstrating the vulnerability of weak or short passwords.
Security Note
document.
import rsa
def generate_keys():
document_bytes = document.encode('utf-8')
'SHA-256')
return signature
return {
'document': document,
'signature': signature
}
document_bytes = document.encode('utf-8')
try:
rsa.verify(document_bytes, signature,
public_key)
document is authentic.")
except rsa.VerificationError:
def main():
needs to be signed."
{sent_data['document']}")
verify_signature(sent_data['document'],
sent_data['signature'], public_key)
if __name__ == "__main__":
main()
Applications
1. Document Authenticity:
o Ensure the document was created by the intended sender.
2. Integrity:
o Confirm the document hasn't been tampered with during
transmission.
3. Non-Repudiation:
o Prevent the sender from denying their involvement.
Security Considerations
1. Key Protection:
o Private keys must be kept secure to prevent unauthorized
signing.
2. Key Size:
o Use at least 2048-bit RSA keys for strong security.
3. Certificate Authority:
o In real-world use, public keys are distributed with certificates
issued by trusted authorities.