Computer Security Lab 1
Computer Security Lab 1
def hash_password(password):
password_bytes = password.encode('utf-8')
hash_object = hashlib.sha256(password_bytes)
password_hash = hash_object.hexdigest()
return password_hash
hashed_password = hash_password(password)
1
Sample Output:
Input your password: A123$Loi
Your hashed password is:
859b848f7f4ebf5e0c47befe74b6cb27caf5ea6a63a566f7038e24f1d29ab131
Explanation
The function first encodes the password string as bytes using UTF-8 encoding and then creates
a SHA-256 hash object with the hashlib.sha256 method. It then passes the encoded password
bytes to this hash object by the update method. Finally, it gets the hexadecimal representation
of the hash using the hexdigest method.
In the main program, the user is prompted to input their password using the input method. The
hash_password function is then called with this password as the argument to generate its
hashed representation. The hashed password is then printed to the console using the print
method.
2
3
Generate Random Passwords of Specified Length
Write a Python program that defines a function to generate random passwords of a specified
length. The function takes an optional parameter length, which is set to 8 by default. If no
length is specified by the user, the password will have 8 characters.
Python Code:
import random
import string
def generate_password(length=8):
return password
if password_length_str:
password_length = int(password_length_str)
else:
password_length = 8
password = generate_password(password_length)
4
print(f"Generated password is: {password}")
Sample Output:
5
Function to Suggest Character Substitutions for Stronger Passwords
Write a Python function that takes a password as input and returns a list of common character
substitutions that could be used to create a stronger password.
Python Code:
def get_password_variants(password):
pass_variants = []
substitutions = {
'a': ['@', '4', 'A'],
'e': ['3', 'E'],
'i': ['1', '!', 'I'],
'o': ['0', 'O'],
's': ['$', '5', 'S'],
't': ['7', 'T'],
'z': ['2', 'Z']
}
for i in range(len(password)):
if password[i] in substitutions:
for sub in substitutions[password[i]]:
pass_variant = password[:i] + sub + password[i+1:]
pass_variants.append(pass_variant)
pass_variants.append(password + '!')
pass_variants.append(password + '123')
pass_variants.append(password + '@')
pass_variants.append(password + '#')
pass_variants.append(password + '$')
pass_variants.append(password + '%')
pass_variants.append(password + '&')
pass_variants.append(password + '*')
pass_variants.append(password + '-')
pass_variants.append(password + '_')
pass_variants.append(password + '=')
pass_variants.append(password + '+')
return pass_variants
password = input("Input your password: ")
result_variants = get_password_variants(password)
print(result_variants)
6
Output