以下是一个简单的基于命令行界面的密码管理器实现,使用 Python 3 和 SQLite3 数据库。
import sqlite3
import hashlib
# 创建数据库连接
conn = sqlite3.connect('passwords.db')
c = conn.cursor()
# 创建表格
c.execute('''CREATE TABLE IF NOT EXISTS passwords
(id INTEGER PRIMARY KEY AUTOINCREMENT,
website TEXT NOT NULL,
username TEXT NOT NULL,
password_hash TEXT NOT NULL)''')
# 常量
SALT = 'my-password-salt'
# 函数:计算 SHA256 哈希值
def compute_hash(password):
m = hashlib.sha256()
m.update(SALT.encode())
m.update(password.encode())
return m.hexdigest()
# 函数:添加密码
def add_password(website, username, password):
password_hash = compute_hash(password)
c.execute("INSERT INTO passwords (website, username, password_hash) VALUES (?, ?, ?)", (website, username, password_hash))
conn.commit()
# 函数:获取密码
def get_password(website):
c.execute("SELECT password_hash FROM passwords WHERE website=?", (website,))
result = c.fetchone()
if result:
return result[0]
else:
return None
# 函数:列出所有网站名称
def list_websites():
c.execute("SELECT website FROM passwords")
result = c.fetchall()
if result:
for row in result:
print(row[0])
else:
print('No passwords found.')
# 命令行界面
while True:
command = input('Enter a command (add, get, list, or quit): ')
if command == 'add':
website = input('Enter the website name: ')
username = input('Enter the username: ')
password = input('Enter the password: ')
add_password(website, username, password)
print('Password added.')
elif command == 'get':
website = input('Enter the website name: ')
password_hash = get_password(website)
if password_hash:
print('The password is:', password_hash)
else:
print('No password found.')
elif command == 'list':
list_websites()
elif command == 'quit':
break
else:
print('Invalid command.')
该密码管理器使用 SQLite3 数据库来存储密码信息,计算 SHA256 哈希值来加密密码。用户可以使用命令行界面来添加、获取和列出密码。请注意,这是一个简单的示例实现,实际应用中可能需要添加更多的特性和安全性逻辑。