create a password and store it in a file in python

Here's a sample code to generate a secure password using Python's cryptography library and store it in a file.

main.py
import string
import random
import hashlib

# generate a secure password with at least one uppercase, one lowercase, 
# one digit, and one special character
def generate_password(length=12):
    """Generate a random password"""
    special_chars = "!@#$%^&*()_-=+`~[]{}|;:,<>/?" # use your own set of special chars
    chars = string.ascii_letters + string.digits + special_chars
    password = ''.join(random.choice(chars) for _ in range(length))
    return password

# hash the password using sha256
def hash_password(password):
    """Return the SHA-256 hash of the given password"""
    salt = b'mysalt'  # use your own salt
    return hashlib.sha256(salt + password.encode()).hexdigest()

# write the hashed password to a file
def save_password(password_hash):
    """Save the password hash to a file"""
    with open("password.txt", "w") as f:
        f.write(password_hash)

# test the functions
password = generate_password()
password_hash = hash_password(password)
save_password(password_hash)
print(f"Password saved in file: {password}")
1048 chars
31 lines

The above code generates a random password, hashes it using SHA-256, and then saves the hashed password in a file named "password.txt". You can change the length of the password, the set of special characters, and the salt value to suit your needs.

gistlibby LogSnag