· 2 years ago · Dec 24, 2022, 02:00 PM
1import sqlite3
2import hashlib
3
4# Connect to the database
5conn = sqlite3.connect("password_database.db")
6cursor = conn.cursor()
7
8# Create a table to store the passwords
9cursor.execute("CREATE TABLE IF NOT EXISTS passwords (service text, username text, password text)")
10
11# Function to store a new password
12def store_password(service, username, password):
13 # Hash the password using a secure hashing algorithm such as SHA-256
14 hashed_password = hashlib.sha256(password.encode()).hexdigest()
15 # Insert the hashed password into the database
16 cursor.execute("INSERT INTO passwords VALUES (?, ?, ?)", (service, username, hashed_password))
17 # Commit the changes to the database
18 conn.commit()
19
20# Function to retrieve a password
21def get_password(service, username):
22 # Retrieve the hashed password from the database
23 cursor.execute("SELECT password FROM passwords WHERE service=? AND username=?", (service, username))
24 result = cursor.fetchone()
25 if result:
26 # Return the hashed password
27 return result[0]
28 else:
29 return None
30
31# Example usage: store a new password
32store_password("example.com", "user123", "p@ssw0rd")
33
34# Example usage: retrieve a password
35password = get_password("example.com", "user123")
36if password:
37 print("The password for example.com is:", password)
38else:
39 print("No password was found for example.com")
40
41# Close the database connection
42conn.close()
43