简体   繁体   English

登录时验证BCrypt哈希密码

[英]Verify BCrypt Hash password when Login

I am using net beans IDE to crate my Login form and the servlet. 我正在使用Net bean IDE来创建我的登录表单和servlet。 i used BCrypt hashing method to secure the password when it's storing in the database and it was successful. 当密码存储在数据库中并且成功时,我使用BCrypt哈希方法来保护密码。 but when I going to login it always says "Invalid Credentials" 但是当我登录时,它总是显示“ Invalid Credentials”

how can i solve this 我该如何解决

here is my CompanyLoging.jsp 这是我的CompanyLoging.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body style="background-color: #666666;">



<%
    Cookie[] cookies=request.getCookies();
    String email = "", password = "",rememberVal="";
    if (cookies != null) {
         for (Cookie cookie : cookies) {
           if(cookie.getName().equals("cookuser")) {
             email = cookie.getValue();
           }
           if(cookie.getName().equals("cookpass")){
             password = cookie.getValue();
           }
           if(cookie.getName().equals("cookrem")){
             rememberVal = cookie.getValue();
           }
        }
    }
%>

<div class="limiter">
    <div class="container-login100">
        <div class="wrap-login100">
                        <form class="login100-form validate-form" action="CompanyLogin" method="post">
                <span class="login100-form-title p-b-43">
                    Login to continue
                </span>


                <div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex@abc.xyz">
                                        <input class="input100" type="text" name="email" >
                    <span class="focus-input100"></span>
                    <span class="label-input100">Email</span>
                </div>


                <div class="wrap-input100 validate-input" data-validate="Password is required">
                    <input class="input100" type="password" name="pass" autocomplete="off">
                    <span class="focus-input100"></span>
                    <span class="label-input100">Password</span>
                </div>

                <div class="flex-sb-m w-full p-t-3 p-b-32">
                    <div class="contact100-form-checkbox">
                                                <label>Remember me?</label> 
                                                <input type="checkbox" name="remember_me" value="1" <%="1".equals(rememberVal.trim()) %>>
                    </div>

                    <div>
                        <a href="#" class="txt1">
                            Forgot Password?
                        </a>
                    </div>
                </div>


                <div class="container-login100-form-btn">
                    <button class="login100-form-btn">
                        Login
                    </button>
                </div>

                <div class="text-center p-t-46 p-b-20">
                    <span class="login100-form-btn2">
                                                or <a href="CompanyReg.jsp">sign up</a> 
                    </span>
                </div>


            </form>

            <div class="login100-more" style="background-image: url('resources/Company/CompanyLogin/images/bg-01.jpg');">
            </div>
        </div>
    </div>
</div>
</body>
</html>

here is my CompanyLog.java 这是我的CompanyLog.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("pass");
    String hashPass = BCrypt.hashpw(password, BCrypt.gensalt(12));

    try
    {
        connection = Connector.ConnectDb();
        PreparedStatement pst = connection.prepareStatement("SELECT * FROM Company WHERE Email= '"+email+"' AND Password='"+hashPass+"'");

        ResultSet rs = pst.executeQuery();
        if (rs.next())
        {
            if(request.getParameter("remember_me") != null)
            {
                String remember = request.getParameter("remember_me");
                Cookie cemail = new Cookie("cookuser", email.trim());
                Cookie cPassword = new Cookie("cookpass", password.trim());
                Cookie cRemember = new Cookie("cookrem", remember.trim());

                cemail.setMaxAge(60 * 60 * 24 * 15);//15 days
                cPassword.setMaxAge(60 * 60 * 24 * 15);
                cRemember.setMaxAge(60 * 60 * 24 * 15);

                response.addCookie(cemail);
                response.addCookie(cPassword);
                response.addCookie(cRemember);

            }

            HttpSession httpSession = request.getSession();
            httpSession.setAttribute("sessuser", email.trim());
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("CompanyDashboard.jsp");
            requestDispatcher.forward(request, response);
        }

        else
        {
            PrintWriter out=response.getWriter();
            out.println("<script type=\"text/javascript\">");
            out.println("alert('Invalid Credentials');");
            out.println("location='CompanyLogin.jsp';");
            out.println("</script>");
        }
    }

    catch (IOException | SQLException | ServletException e)
    {
        PrintWriter out=response.getWriter();
        out.println("Error : " + e);
    }
}

this is the way my database looks like 这就是我的数据库的样子

我的资料库

You don't have posted the registration-part of your application, but I suspect the issue is caused by the following line in your login-part: 您尚未发布应用程序的注册部分,但我怀疑问题是由登录部分中的以下行引起的:

String hashPass = BCrypt.hashpw(password, BCrypt.gensalt(12));

which creates the password-hash for a new salt. 这会为新的 salt创建密码哈希。 Of course, that doesn't match the password-hash created in your registration-part (and stored in the Password -field of your DB) since the salts differ even if the passwords match. 当然,这与在注册部分创建的密码哈希(并存储在数据库的“ Password字段中)不匹配,因为即使密码匹配,盐值也会有所不同。 Thus, instead of creating a new salt you have to use the salt already stored in your DB: 因此,不必创建新的盐,而必须使用已经存储在数据库中的盐:

String hashPass = BCrypt.hashpw(password, storedSalt);

In principle, the salt can be reconstructed from the stored BCrypt-hash (if you are interested in this, the format of the BCrypt -hash is in detail explained at How can bcrypt have built-in salts? and here ). 原则上,可以从存储的BCrypt-hash中重建盐(如果您对此感兴趣, BCrypt参阅bcrypt如何具有内置盐?此处详细说明BCrypt -hash的格式)。

However, there is an easier way (which is also the intended way): You can use the BCrypt#checkpw -method: 但是,有一种更简单的方法(这也是预期的方法):可以使用BCrypt#checkpw方法:

boolean isAuthenticated = BCrypt.checkpw(candidatePassword, passwordHash);

Here, candidatePassword is the password to check. 在这里, candidatePassword密码是要检查的密码。 passwordHash is the BCrypt -hash (stored in the Password -field of your DB). passwordHashBCrypt哈希(存储在数据库的Password字段中)。 If the passwords match the method returns true. 如果密码匹配,则该方法返回true。

If you use this approach you have to adapt your database-access accordingly, eg something like (not yet tested!): 如果使用这种方法,则必须相应地调整数据库访问权限,例如(尚未测试!):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("pass");

    try {
        connection = Connector.ConnectDb();
        PreparedStatement pst = connection.prepareStatement("SELECT * FROM Company WHERE Email= '"+email+"'");

        ResultSet rs = pst.executeQuery();
        while (rs.next()) {
            if (BCrypt.checkpw(password, rs.getString("Password"))) {
                ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM