我创建了在java中验证用户身份的函数.我使用SHA1加密数据,然后将其存储在MySQL中.然后我创建了参数查询来从MySQL数据库传递数据.但是我在该查询行中出错了.在我更改数据库中的SHA1值后,我删除了查询中的SHA1字.真的没有任何错误.但我想从数据库中获取并检查SHA1加密数据.如何将数据库SHA1加密数据传递到我的查询中.请有人帮我解决我的问题.
public boolean authenticate(String username, String password){
Connection newConnection = null;
ResultSet newRst = null;
boolean flag = false; //return value which determines whether logged in or not
String SqlString = "SELECT * FROM user"
+ " WHERE username=? AND password=SHA1(?)"; //Error line when use SHA1()
String Username = username;
String Password = password;
String CheckUsername;
String CheckPassword;
List<String> ParametersDefined =
Arrays.asList(Username, Password);
List<String> ParametersNames = Arrays.asList("username", "password");
List<String> ParameterDataType =
Arrays.asList("String", "String");
DatabaseHandling newData = new DatabaseHandling();
try {
newConnection = newData.DataConnection();// creating the connection
newRst = newData.DataReadArg(newConnection, SqlString,
ParametersDefined, ParametersNames, ParameterDataType);
//check whether one row or more
int RowCount = 0; // to find the row count
while (newRst.next()) {
//checking whether we are getting right row
System.out.println("this is " + newRst.getString(2));
RowCount++;
}
//if the Row count is one then it check
if (RowCount == 1) {
newRst.first();
CheckUsername = newRst.getString("username");
CheckPassword = newRst.getString("password");
if ((username.equals(CheckUsername))
&& password.equals(CheckPassword)) {
userRoleId = newRst.getInt("userRoleId");
System.out.println("role = " + userRoleId);
flag = true;
}
}
} catch (Exception e) {
System.out.println("Error" + e.getMessage());
flag = false;
}
return flag;
}
工作线……
String SqlString = "SELECT * FROM user"
+ " WHERE username=? AND password=?"; //Without SHA1 String. It's working without any errors.
解决方法:
您需要更改从数据库中获取用户数据的方法.
而不是“SELECT * FROM user WHERE username =?和密码=? “
只需使用“SELECT * FROM user WHERE username =?”.
仅基于用户名获取用户.用户数据可用后,使用数据库值验证加密密码.
这样您可以隔离以下验证 –
>用户通过使用“username”的唯一值存在于系统中.
>如果用户存在,请验证密码.
交叉验证用户凭据是非常重要的业务逻辑,它必须位于业务层(您的Java服务)中,不应跨数据库传播.