在用户管理系统中使用哈希算法对用户密码进行加密处理
python
import hashlib
users = []
# 用户类,包含基本信息
class User:
def __init__(self, name, password, email=None):
self.name = name
self.password = self._encrypt_password(password) # 加密密码
self.email = email # 可选的电子邮件字段
def _encrypt_password(self, password):
# 使用SHA-256哈希函数对密码进行加密
sha256 = hashlib.sha256()
sha256.update(password.encode('utf-8'))
return sha256.hexdigest()
def __str__(self):
return f"User(Name: {self.name}, Password: {self.password}, Email: {self.email})"
# 用户管理系统
class UserManager:
def __init__(self):
self.users = []
def add_user(self, user):
self.users.append(user)
print(f"User {user.name} added successfully.")
def get_user(self, name):
for user in self.users:
if user.name == name:
return user
return None
def list_users(self):
for user in self.users:
print(user)
user_manager = UserManager()
# 添加用户
user1 = User('张三', 'password123')
user2 = User('李四', 'lisi963')
user_manager.add_user(user1)
user_manager.add_user(user2)
# 列出所有用户
print("List of users:")
user_manager.list_users()
# 根据用户名获取用户信息
lisi = user_manager.get_user('李四')
if lisi:
print(lisi)