我正在使用Java Eclipse并将密码散列到MySQL数据库中。创建新用户时,我将密码哈希,然后将其存储到数据库中。当用户登录时,我将密码哈希,然后将其与数据库上的密码进行比较。但是,我在两个地方打印哈希密码,虽然我在两个实例中输入相同的原始密码,但哈希值不同。这是我的哈希函数:
// hash the password to store in database
String hashed_password = passwordField.toString();
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
md.update(hashed_password.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Digest(in hex format):: " + sb.toString());
// end of hashing
这是我的比较:
String query = "select * from user where username=? and password=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, userNameTextField.getText() );
//pst.setString(2 , passwordField.getText() );
pst.setString(2 , sb.toString() );
username = userNameTextField.getText();
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()){
count++;
}
if(count == 1){
//JOptionPane.showMessageDialog(null, "Username and password is correct");
listener.userLoggedIn(new UserAccount());