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

无框架下如何在Java中校验bcrypt加密的数据库密码

登录程序适配bcrypt密码验证的代码修改方案

现有代码核心问题

当前代码直接用明文密码匹配数据库中存储的bcrypt加密值,这完全无效——bcrypt是单向哈希算法,无法通过明文直接匹配加密字符串,必须用专门的验证方法对比。同时代码存在语法错误(未完成的变量声明、未定义变量、错误对象引用),需要一并修正。

具体修改步骤

  1. 修正基础语法错误

    • 删除未完成的String pass声明;
    • 修正对象引用:将objectMenu.setVisible(true);改为object.setVisible(true);(实例化的对象是object);
    • 移除原代码中无效的空BCrypt.checkpw()调用。
  2. 调整数据库查询逻辑
    不再同时匹配用户名和密码,改为仅根据用户名查询对应的bcrypt加密密码——我们需要拿到加密值后再做验证,而非直接匹配。SQL语句修改为:

    select PasswordLogin from user where UserLogin = ?;
    
  3. 实现bcrypt验证逻辑
    查询到用户的加密密码后,调用BCrypt.checkpw()方法,传入用户输入的明文密码和数据库返回的加密密码,判断验证结果。

修改后的完整代码

import org.mindrot.jbcrypt.BCrypt; // 确保导入jBCrypt库
import javax.swing.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class CLogin {

    public void validateUser(JTextField user, JPasswordField password) {
        try {
            ResultSet rs = null;
            PreparedStatement ps = null;
            
            Classes.CConexion connectionObject = new Classes.CConexion(); // 修正变量拼写错误

            // 修改SQL:仅查询对应用户名的加密密码
            String query = "select PasswordLogin from user where UserLogin = ?;";
            ps = connectionObject.setConnection().prepareStatement(query);
            
            String contra = String.valueOf(password.getPassword());
            ps.setString(1, user.getText());
            
            rs = ps.executeQuery();
            
            if (rs.next()) {
                // 从数据库获取加密后的密码
                String storedHashedPassword = rs.getString("PasswordLogin");
                // 用bcrypt验证明文密码和加密密码是否匹配
                if (BCrypt.checkpw(contra, storedHashedPassword)) {
                    JOptionPane.showMessageDialog(null, "User is Correct");
                    FromMenu object = new FromMenu();
                    object.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "User is INCORRECT, TRY AGAIN");
                }
            } else {
                JOptionPane.showMessageDialog(null, "User is INCORRECT, TRY AGAIN");
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "ERROR: " + e.toString());
        }
    }
}

额外注意事项

  • 确保项目引入jBCrypt库:如果用Maven,可在pom.xml中添加依赖:
    <dependency>
        <groupId>org.mindrot</groupId>
        <artifactId>jbcrypt</artifactId>
        <version>0.4</version>
    </dependency>
    
  • 原代码中Classes.CConexionConnectionObject存在拼写错误,修正为Classes.CConexion connectionObject,确保数据库连接能正常初始化。

内容的提问来源于stack exchange,提问作者julio cesar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:37:21