我遇到了 MessageDigest 在不同计算机上返回不同哈希值的问题。
一台计算机在 Windows Vista 上运行 32 位 Java,另一台在 Mac OS 上运行 64 位 Java。我不确定是不是因为 MessageDigest 依赖于机器,或者我需要在某处明确指定字符编码,或者可能是其他原因。这是 代码:
public static boolean authenticate(String salt, String encryptedPassword,
char[] plainTextPassword ) throws NoSuchAlgorithmException {
// do I need to explcitly specify character encoding here? -->
String saltPlusPlainTextPassword = salt + new String(plainTextPassword);
MessageDigest sha = MessageDigest.getInstance("SHA-512");
// is this machine dependent? -->
sha.update(saltPlusPlainTextPassword.getBytes());
byte[] hashedByteArray = sha.digest();
// or... perhaps theres a translation problem here? -->
String hashed = new String(hashedByteArray);
return hashed.equals(encryptedPassword);
}
这段代码在这两台不同的机器上是否应该以不同的方式执行? 如果它像我写的那样依赖于机器,是否有另一种更便携的散列这些密码的方法?谢谢!
编辑::::::
这是我用来生成盐的代码:
public static String getSalt() {
int size = 16;
byte[] bytes = new byte[size];
new Random().nextBytes(bytes);
return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(bytes);
}
解决方案:::
感谢公认的解决方案,我能够修复我的代码:
public static boolean authenticate_(String salt, String encryptedPassword,
char[] plainTextPassword ) throws NoSuchAlgorithmException, UnsupportedEncodingException {
// This was ok
String saltPlusPlainTextPassword = salt + new String(plainTextPassword);
MessageDigest sha = MessageDigest.getInstance("SHA-512");
// must specify "UTF-8" encoding
sha.update(saltPlusPlainTextPassword.getBytes("UTF-8"));
byte[] hashedByteArray = sha.digest();
// Use Base64 encoding here -->
String hashed = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(hashedByteArray);
return hashed.equals(encryptedPassword);
}
最佳答案
编码给您带来了问题。首先在这里:
saltPlusPlainTextPassword.getBytes()
这将使用机器的默认编码。馊主意。将“UTF-8”指定为简单的解决方案。 (它保证存在。)
接下来这会导致问题:
String hashed = new String(hashedByteArray);
hashedByteArray
是任意二进制数据。要安全地将其转换为文本,请使用 base-64 编码或仅使用十六进制。同样,您当前使用的是默认编码,该编码因机器而异。 Java 中有大量用于 base64 编码的第 3 方库。
关于java - MessageDigest 在不同机器上的散列不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3077196/