Java 中的 MD5 散列?

Hash with MD5 in Java?

我正在创建一个程序,它将获取登录名和密码的用户输出并对这些变量(登录名和密码)进行哈希处理。

当我对登录的输出进行哈希处理时它有效,但是当我尝试对密码的输出进行哈希处理时它不起作用。

代码:

String login;
String password;


login = JOptionPane.showInputDialog("Login : ");
password = JOptionPane.showInputDialog("Password : ");

MessageDigest m; 


try 
{ 
m = MessageDigest.getInstance("MD5");
m.update(login.getBytes(),0,login.length()); 
m.update(password.getBytes(),0,password.length());
BigInteger login1 = new BigInteger(1, m.digest()); 
BigInteger password1 = new BigInteger(1, m.digest());

login = String.format("%12X", login1); 
password = String.format("%12X", password1); 

JOptionPane.showMessageDialog(null,"Login : " + login + 
                "\nPassword : " + password);

//System.out.println("login : "+ login); 
//System.out.println("password : " + password);
} 

输出:

login : E9CA9D798BA364DFF16C738D03AF6668
password : D41D8CD98F00B204E9800998ECF8427E

变量登录正常,但是密码在哈希时总是得到相同的结果,我想让变量密码在哈希时总是得到一些不同的结果。

PS : 抱歉英语不好,不是我的母语。

正如评论中所指出的,您在没有重置的情况下调用了两次摘要。您需要在下次使用前重置摘要。

try
{
    m = MessageDigest.getInstance("MD5");
    m.update(login.getBytes(), 0, login.length());
    BigInteger login1 = new BigInteger(1, m.digest());
    login = String.format("%12X", login1);

    m.reset(); // <---- Reset before doing the password
    m.update(password.getBytes(), 0, password.length());
    BigInteger password1 = new BigInteger(1, m.digest());
    password = String.format("%12X", password1);

    System.out.println(login);
    System.out.println(password);
}

我猜您是从 Web 元素中检索密码,而不是直接提取字符串进行哈希处理。 D41D8CD98F00B204E9800998ECF8427E 是 "nothing"(零长度字符流)的 md5sum。通常在 html(html5) 中,密码字段足够智能,不会泄露数据,这可能就是您在 return 中得到空字符串的原因。希望这有帮助