You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

登录验证失败且不同密码哈希值异常的技术问题求助

登录验证失败与哈希值异常问题排查及修复

问题现象

  • 用户注册时密码哈希后存入SQLite数据库,但登录时输入正确密码却提示验证失败
  • 注册页面输入不同密码,生成的哈希值高度相似

错误根源分析

核心问题出在注册模块的哈希逻辑错误:
原注册代码中错误调用了self.password.get(),但实际注册页面的密码输入框是password1和password2,这里误用了不存在的self.password对象,导致哈希的是空字符串或固定值——这就是不同密码生成相似哈希、登录时匹配失败的直接原因。

此外登录模块的while True循环完全冗余,无论结果如何都会立即break,没有实际作用。

修复后的代码

注册模块修复版

def check_sign_up(self):
    conn = sqlite3.connect("userdata.db")
    cur = conn.cursor()
    
    # 先获取所有输入值,提升可读性
    username = self.username.get()
    password_input = self.password1.get()
    confirm_password = self.password2.get()
    email = self.email.get()
    
    # 完善字段校验逻辑
    if confirm_password == password_input and username != "" and email != "":
        # 正确获取密码输入并哈希
        hashed_password = hashlib.sha256(password_input.encode()).hexdigest()
        cur.execute("INSERT INTO userdata (username, password, Email) VALUES (?,?,?)",
                    (username, hashed_password, email))
        conn.commit()
        messagebox.showinfo("SUCCESS", "Thank you for Joining the Light Technologies")
    else:
        messagebox.showerror("E R R O R", "All fields are required !!")
    
    conn.close()  # 关闭数据库连接,避免资源泄漏

登录模块优化版

def handle_connection(self):
    username = self.username.get()
    password_input = self.password.get()
    hashed_password = hashlib.sha256(password_input.encode()).hexdigest()
    
    conn = sqlite3.connect("userdata.db")
    cur = conn.cursor()
    
    cur.execute("SELECT * FROM userdata WHERE username = ? AND password = ?", (username, hashed_password))
    
    if cur.fetchall():
        messagebox.showinfo("Login Successful !")
    else:
        messagebox.showerror("Login Failed !", "Wrong password or username !\n Please try again !")
    
    conn.close()

额外优化建议

  • 添加盐值(Salt)增强安全性:直接哈希密码容易被彩虹表破解,建议生成随机盐值后再哈希,存储时将盐值与哈希值一起存入数据库:
    import os
    # 生成16字节随机盐值
    salt = os.urandom(16)
    # 盐值+明文密码后哈希
    hashed_password = hashlib.sha256(salt + password_input.encode()).hexdigest()
    
  • 使用with语句管理数据库连接:自动处理连接的打开与关闭,避免遗漏:
    with sqlite3.connect("userdata.db") as conn:
        cur = conn.cursor()
        # 执行SQL操作
    
  • 实现真正的登录重试逻辑:原代码中max_attempts和attempts变量未实际使用,可根据需求添加重试计数与锁定逻辑。

内容的提问来源于stack exchange,提问作者Man of Light

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 15:16:07