我的transaction_login方法是否在Java上错误地实现了预备语句?我不知道什么时候会出现SQLExceptions。

问题描述 投票:0回答:1

5月12日下午1:30更新:我把我的代码编辑了很多,但是测试用例还是不能运行。我不知道该从哪里开始,因为测试用例一开始就很简单。我不知道该从哪里下手,因为测试用例一开始就很简单,如果能了解哪里出了问题就好了。

login接收用户名和密码,并检查该用户是否存在于数据库中,密码是否匹配。要计算哈希值,请修改上面的代码。在一个会话中(也就是你的程序的一个实例),只有一个用户应该被登录。一个好的做法是每个测试用例都以一个登录请求开始。确保在程序终止时将用户注销。为了保持简单,你可以在程序中使用一个本地变量来跟踪一个用户的登录状态。如果第二次尝试登录,请返回 "User already logged in"。


  public String transaction_login(String username, String password) {
    if (LOGGED_IN == 0) {
      try {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, HASH_STRENGTH, KEY_LENGTH);
        SecretKeyFactory factory = null;
        byte[] hash = null;
        try {
          factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
          hash = factory.generateSecret(spec).getEncoded();
        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
          throw new IllegalStateException();
        }
        /* RUNNING SQL QUERY*/
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(USER_ACCESS);
        while (rs.next()) {
          String result_username = rs.getString("username");
          byte[] result_hash = rs.getByte("hashVal");
          if (result_username.equalsIgnoreCase(username) && Arrays.equals(result_hash, hash)) {
              LOGGED_IN++;
              return "Logged in as " + username + "\n";
          }
        }
        rs.close();
        return "Login failed\n";
      } catch (SQLException se) {
        se.printStackTrace();
        se.getErrorCode();
      } finally {
        checkDanglingTransaction();
      }
    } else {
      return "User already logged in\n";
    }
  }

java mysql azure hash prepared-statement
1个回答
0
投票

你的语句部分需要修正,以解决多个问题。

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(USER_ACCESS); // SELECT * FROM User
while (rs.next()) {
    String result_username = rs.getString("username");
    byte[] result_password = rs.getBytes("password"); // not single byte
    if (result_username.equalsIgnoreCase(username) && Arrays.equals(result_password, hash)) {
        LOGGED_IN++;  
        return "Logged in as " + username + "\n";
    } // do not return here, check for other users!
}
rs.close();
return "Login failed\n";
© www.soinside.com 2019 - 2024. All rights reserved.