本文目录导读:

我来为你介绍几种Python中安全的密码加密存储方法。
使用bcrypt(推荐)
import bcrypt
class PasswordHasher:
@staticmethod
def hash_password(password: str) -> bytes:
"""加密密码"""
# 生成随机盐值并加密
salt = bcrypt.gensalt(rounds=12) # rounds越高越安全,但越慢
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed
@staticmethod
def verify_password(password: str, hashed_password: bytes) -> bool:
"""验证密码"""
return bcrypt.checkpw(password.encode('utf-8'), hashed_password)
@staticmethod
def is_strong_password(password: str) -> bool:
"""检查密码强度"""
if len(password) < 8:
return False
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(not c.isalnum() for c in password)
return has_upper and has_lower and has_digit and has_special
# 使用示例
def main():
hasher = PasswordHasher()
# 用户注册
password = "MySecureP@ss123"
# 检查密码强度
if not hasher.is_strong_password(password):
print("密码强度不足")
return
# 加密存储
hashed_password = hasher.hash_password(password)
print(f"加密后的密码: {hashed_password}")
# 用户登录验证
input_password = "MySecureP@ss123"
if hasher.verify_password(input_password, hashed_password):
print("密码验证成功!")
else:
print("密码错误")
if __name__ == "__main__":
# 安装: pip install bcrypt
main()
使用hashlib + SALT(标准库)
import hashlib
import os
import secrets
class PasswordManager:
SALT_LENGTH = 32
@staticmethod
def generate_salt() -> str:
"""生成随机盐值"""
return secrets.token_hex(PasswordManager.SALT_LENGTH)
@staticmethod
def hash_password(password: str, salt: str) -> str:
"""使用PBKDF2算法加密密码"""
# 使用100,000次迭代
key = hashlib.pbkdf2_hmac(
'sha256', # 哈希算法
password.encode('utf-8'),
salt.encode('utf-8'),
100000, # 迭代次数
dklen=32 # 密钥长度
)
return key.hex()
@staticmethod
def store_password(password: str) -> dict:
"""存储密码(返回盐值和哈希值)"""
salt = PasswordManager.generate_salt()
hashed_password = PasswordManager.hash_password(password, salt)
return {
'salt': salt,
'hash': hashed_password
}
@staticmethod
def verify_password(password: str, salt: str, stored_hash: str) -> bool:
"""验证密码"""
computed_hash = PasswordManager.hash_password(password, salt)
return computed_hash == stored_hash
# 使用示例
def main():
manager = PasswordManager()
# 用户注册
password = "SecureP@ss123!"
# 存储密码(保存到数据库)
stored_data = manager.store_password(password)
print(f"存储的盐值: {stored_data['salt']}")
print(f"存储的哈希值: {stored_data['hash']}")
# 用户登录验证
input_password = "SecureP@ss123!"
if manager.verify_password(input_password, stored_data['salt'], stored_data['hash']):
print("密码验证成功!")
else:
print("密码错误")
if __name__ == "__main__":
main()
完整的用户密码管理系统
import bcrypt
import json
import os
from datetime import datetime
from typing import Optional, Dict
class UserPasswordSystem:
def __init__(self, db_file: str = "users.json"):
self.db_file = db_file
self.users = self._load_users()
def _load_users(self) -> Dict:
"""加载用户数据"""
if os.path.exists(self.db_file):
with open(self.db_file, 'r') as f:
return json.load(f)
return {}
def _save_users(self):
"""保存用户数据"""
with open(self.db_file, 'w') as f:
json.dump(self.users, f, indent=2)
def register_user(self, username: str, password: str) -> bool:
"""注册新用户"""
if username in self.users:
print("用户名已存在")
return False
# 检查密码强度
if len(password) < 8:
print("密码长度至少8位")
return False
# 加密密码
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
# 存储用户信息
self.users[username] = {
'password': hashed_password.decode('utf-8'),
'created_at': datetime.now().isoformat(),
'last_login': None,
'login_attempts': 0
}
self._save_users()
print(f"用户 {username} 注册成功")
return True
def login_user(self, username: str, password: str) -> bool:
"""用户登录"""
if username not in self.users:
print("用户名不存在")
return False
user = self.users[username]
# 检查登录尝试次数(防止暴力破解)
if user['login_attempts'] >= 5:
print("账户已被锁定,请稍后再试")
return False
# 验证密码
stored_password = user['password'].encode('utf-8')
if bcrypt.checkpw(password.encode('utf-8'), stored_password):
# 登录成功,重置尝试次数
user['login_attempts'] = 0
user['last_login'] = datetime.now().isoformat()
self._save_users()
print(f"用户 {username} 登录成功")
return True
else:
# 登录失败,增加尝试次数
user['login_attempts'] += 1
self._save_users()
print(f"密码错误,剩余尝试次数: {5 - user['login_attempts']}")
return False
def change_password(self, username: str, old_password: str, new_password: str) -> bool:
"""修改密码"""
if username not in self.users:
print("用户名不存在")
return False
# 验证旧密码
stored_password = self.users[username]['password'].encode('utf-8')
if not bcrypt.checkpw(old_password.encode('utf-8'), stored_password):
print("旧密码错误")
return False
# 检查新旧密码不同
if old_password == new_password:
print("新密码不能与旧密码相同")
return False
# 加密新密码
salt = bcrypt.gensalt()
new_hashed = bcrypt.hashpw(new_password.encode('utf-8'), salt)
# 更新密码
self.users[username]['password'] = new_hashed.decode('utf-8')
self.users[username]['password_changed_at'] = datetime.now().isoformat()
self._save_users()
print("密码修改成功")
return True
def delete_user(self, username: str, password: str) -> bool:
"""删除用户"""
if username not in self.users:
print("用户名不存在")
return False
# 验证密码
stored_password = self.users[username]['password'].encode('utf-8')
if not bcrypt.checkpw(password.encode('utf-8'), stored_password):
print("密码错误")
return False
# 删除用户
del self.users[username]
self._save_users()
print(f"用户 {username} 已删除")
return True
# 使用示例
def main():
system = UserPasswordSystem()
print("=" * 50)
print("用户密码管理系统")
print("=" * 50)
while True:
print("\n1. 注册")
print("2. 登录")
print("3. 修改密码")
print("4. 删除用户")
print("5. 退出")
choice = input("\n请选择操作: ")
if choice == '1':
username = input("用户名: ")
password = input("密码: ")
system.register_user(username, password)
elif choice == '2':
username = input("用户名: ")
password = input("密码: ")
system.login_user(username, password)
elif choice == '3':
username = input("用户名: ")
old_password = input("旧密码: ")
new_password = input("新密码: ")
system.change_password(username, old_password, new_password)
elif choice == '4':
username = input("用户名: ")
password = input("密码: ")
system.delete_user(username, password)
elif choice == '5':
print("再见!")
break
else:
print("无效选择")
if __name__ == "__main__":
# 安装: pip install bcrypt
main()
安装依赖
# 安装bcrypt(推荐) pip install bcrypt # 或者使用标准库方式(无需安装) # 只需要Python标准库
安全建议
- 使用强哈希算法:推荐使用bcrypt、PBKDF2或Argon2
- 添加随机盐值:每个密码使用不同的盐值
- 足够的迭代次数:增加计算复杂度
- 密码强度要求:长度、复杂度检查
- 错误尝试限制:防止暴力破解
- 安全传输:使用HTTPS传输密码
- 定期更新:定期要求用户更新密码
这样就能安全地存储和验证用户密码了。