再次祝大家有美好的一天。当用户注册其详细信息时,密码将被哈希处理,然后存储在数据库中。当我尝试登录时,收到错误提示“密码错误”。我正在使用 hashlib
这是注册时对密码进行哈希处理并存储在数据库中的代码
def register():
name = name_entry.get()
surname = surname_entry.get()
email = email_entry_register.get()
password = password_entry_register.get()
# Hash the password using SHA-256
hash_password = hashlib.sha256(password.encode()).hexdigest()
# Insert the user data into the database
cursor.execute("INSERT INTO employee_data (employee_id, employee_name, employee_surname, employee_email, employee_password) VALUES (?, ?, ?, ?, CONVERT(varbinary,?))", (employee_id, name, surname, email, hash_password))
connection.commit()
这是登录时的代码
def login():
email = email_entry.get()
entered_password = password_entry_register.get()
# Extract the stored hashed password from the result
hash_password = result[4]
# Hash the entered password using SHA-256
entered_password_hash = hashlib.sha256(entered_password.encode()).hexdigest()
# Check if the password is correct
if entered_password != hash_password:
messagebox.showerror("Error", "Incorrect password.")
return
我读过一些论坛,但没有一个真正适用于我的代码
代码中的问题在于登录过程中输入的密码与存储的密码哈希的比较。您将原始的、未散列输入的密码与数据库中存储的散列密码进行比较,这总是会导致不匹配。这是您的登录功能中存在问题的特定部分:
# Incorrect comparison in your login function
if entered_password != hash_password:
messagebox.showerror("Error", "Incorrect password.")
return
要解决此问题,您应该将输入密码的哈希版本与存储的哈希进行比较。这是更正后的比较:
# Hash the entered password
entered_password_hash = hashlib.sha256(entered_password.encode()).hexdigest()
# Correct comparison
if entered_password_hash != hash_password:
messagebox.showerror("Error", "Incorrect password.")
return
但是,关于 SHA-256:它非常适合一般哈希,但不是密码安全的首选。问题是,它真的很快,这听起来不错,但实际上让黑客更容易使用暴力方法破解密码。这不是我们想要的。
输入bcrypt。这是密码保护变得更好的地方。 bcrypt 向每个密码添加一些随机位(即“加盐”),使它们都是唯一的。另外,它故意更慢地散列密码。这种缓慢是一个优点,因为它使得暴力攻击更难实现。因此,为了保证密码安全,bcrypt 绝对是最佳选择