【问题标题】:Creating a random password generates a password with length 0: Blame JavaScript or Java Servlet?创建随机密码会生成长度为 0 的密码:怪 JavaScript 还是 Java Servlet?
【发布时间】:2012-12-04 01:29:26
【问题描述】:

当我的用户忘记密码时,他们会被发送到如下所示的页面。我在 JavaScript 中生成一个随机密码,对其进行加密,然后将纯文本和 md5 哈希发送到一个 Servlet。然后 Servlet 将密码通过电子邮件发送给用户,并将 md5 哈希存储在我的数据库中。这个过程大部分时间都可以正常工作。但是由于某种原因,在生成的密码长度为 0 的情况下经常会产生错误。

我单独测试了我的 JavaScript 代码并让它生成了数百个密码。没有长度为 0。那么这个错误来自哪里?

这是 HTML 表单:

//This method returns a randomly generated mathy password.
function randomPassword(theForm) {
  first = ["Euler", "Erdos", "Newton", "Eucl1d", "Gauss", "H1lb3rt", "Cantor",    "Bernoulli", "PascaL"];
  second = ["Const", "Number", "Theorem", "Prime", "Ratio", "Lemma", "Postulate", "Method", "Algorithm"];
  symbol = ["!","@","#","$","%","^","&","*","_","+","-","?"];
  a = Math.floor(Math.random() * first.length);
  b = Math.floor(Math.random() * second.length);
  n = Math.floor(Math.random() * 10);
  style = Math.floor(Math.random() * 3);  //0,1, or 2
  if(style==0)   password = first[a] + n + second[b];
  else if(style==1)  password = first[a] + second[b] + n;
  else password = first[a] + second[b] + symbol[n];
  theForm['newPass'].value = password;
  theForm['passwordLog'].value = "style="+style + "  a=" + a + ", b=" + b+ ", n=" + n;
  hashField = theForm['passHash'];
  hashField.value = hex_md5(password);
  theForm.submit();

}

<body>
    <h2>You can reset your password below.</h2>
    <form action="ResetPassword" method="post" > 
        Enter your e-mail address:
        <input type="text" name="eMail" id="eMail" size="20"/> <br />
        <input type="button" value="Reset Password" onclick="randomPassword(this.form);" />
        <input type="hidden" id="passHash" name="passHash" /> 
        <input type="hidden" id="newPass" name="newPass" /> 
        <input type="hidden" id="passwordLog" name="passwordLog" /> 
    </form><br/>
    <strong>Attention Coaches: If you are having trouble logging into this system,
please contact the scorekeeper: llaspina@bethpage.ws </strong>
</body>

这里是接收上述文件发送的表单数据的Servlet:

@WebServlet(name = "ResetPasswordServlet", urlPatterns = {"/ResetPassword"})
public class ResetPasswordServlet extends HttpServlet {  
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    ConnectionPool pool = ConnectionPool.getInstance();
    java.sql.Connection con = pool.getConnection();
    String emailAddress = request.getParameter("eMail");
    String newPass = request.getParameter("newPass");
    String passHash = request.getParameter("passHash");
    String log = request.getParameter("passwordLog");
    try {
        Coach coach = null;
        ArrayList<Coach> coachList = MathTeamDAO.getAllCoaches(con);
        for(Coach c : coachList) {
            if(c.email.equals(emailAddress) ) {
                coach = c;
                break;
            }
        }
        out.println("<html><head><title>Scorekeeper Reset Password Servlet</title></head>");
        out.println("<body>");
        out.println("<h1>Reset Password Servlet</h1>");
        if(coach==null) {
            out.println("Your email address was not found in our database.<br/>" +
            "Please contact the scorekeeper or the secretary to gain access to the sytem.");
        }
        else {
            if(newPass == null || newPass.length()<3) {
                out.print("An error occurred while generating a random password.  The randomly generated password came back as ");
                out.print(newPass);
                out.println(" Please try to <a href=\"resetPassword.html\">reset your password</a> again.");
                String errorMsg = "An error was encountered while attempting a password reset. ";
                if(newPass==null)
                    errorMsg += "null newPass generated.";
                else
                    errorMsg += " The newPass had length " + newPass.length() + " and =" + newPass;
                if(log!=null)
                    errorMsg += ("\n" + log);
                if(UtilityServlet.emailAnError(coach,errorMsg, this.getServletName() + " at " + this.getServletName()))
                    out.println("<br/>The scorekeeper was just informed of this error through email, so you do not need to report it.");
            }
            else {
                out.println("<h3>Check your email for your new password and directions for signing into the scorekeeper system.</h3>");
                out.print("Sending new password to " + coach.email + "<br/>");
                ChangePasswordServlet.changePassword(con, coach.schoolID, passHash);
                School herSchool = MathTeamDAO.getSchoolByCoach(con, coach);
                String emailServerMessage = ChangePasswordServlet.sendPasswordEmail(coach, herSchool.shortName, newPass);
                if(herSchool!=null) {
                    out.print("<br/>The username for " + herSchool.fullName);
                    out.print(" is <strong>");
                    out.print(herSchool.username);
                    out.println("</strong><br/>");
                }
                out.print(emailServerMessage);
            }
            out.flush();
        }
        out.println("<br/>Return to <a href=\"login.jsp\" >login page.</a>");
        out.println("</body></html>");
    } 
    catch(java.sql.SQLException utoh) {   }
    finally { 
        pool.freeConnection(con);
        out.close();
    }
} 

请注意,如果密码为空或太短,我会收到错误消息。这种情况经常发生,而且它们的长度总是 0。为什么?

【问题讨论】:

  • “我在 JavaScript 中生成一个随机密码,对其进行加密,然后将纯文本和 md5 哈希发送到 Servlet”——这听起来非常不安全(你的加密是什么?),如果你的实际算法是任何接近您的代码示例的东西,您正在生成非常不安全的密码。 (
  • 我知道这无助于解决您的问题 - 但是您是否有理由在客户端生成密码,然后将其发送到服务器?与简单地通知服务器用户需要重置密码并让它生成密码相比,这似乎不必要地复杂且可能不安全。 (即,黑客可以使用您的客户端加密将任何人的密码重置为他们自己选择的密码)。

标签: java javascript servlets passwords


【解决方案1】:

在这一行中间加上注释:

else //if(style==2)  password = first[a] + second[b] + symbol[n];

在大约三分之一的情况下,您将获得未定义的密码...

【讨论】:

  • 如果该 cmets 存在于代码中,那么它将始终未定义,因为最后一个 else 与 theForm['newPass'].value = password 匹配。所以密码只设置样式为2,但设置为未定义。在所有其他情况下,它都是空字符串,因为密码字段保持不变..
  • @GabyakaG.Petrioli:由于 OP 没有用 var 声明 password,因此在“正确”情况下,密码是否可以设置为该名称的一些随机不相关的全局变量?
  • 抱歉,代码拼写错误。我试图稍微压缩代码并重新格式化它,我注释掉了 else 子句。测试 JavaScript 代码时,它从未生成长度为 0 的密码。
【解决方案2】:
else //if(style==2)  password = first[a] + second[b] + symbol[n];
theForm['newPass'].value = password;

有了评论,else 现在影响了theForm['newPass'].value = password;,这意味着不会设置值,导致密码为空。

这就是为什么即使你只有一个语句也建议使用{}

【讨论】:

  • 当然,但是当我将代码粘贴到浏览器中并尝试对其进行压缩时,这只是一个错字(请参阅更新的代码)。如果这是问题所在,那么我会在直接测试 JavaScript 时看到它。其他想法?
猜你喜欢
  • 2022-09-23
  • 1970-01-01
  • 2020-05-11
  • 2010-09-08
  • 2017-11-04
  • 2022-01-25
  • 2012-11-06
相关资源
最近更新 更多