引用 this question 了解背景。
当给定的字符串为英语时,在 Java 和 PHP 中使用 SHA-256 等算法进行散列会产生相同的结果,但是当输入的语言不是英语时,如何使两种语言产生相同的结果(例如例如中文)?
Java
public static String encodePassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes("UTF-8")); //I've tried messing around with the encoding
String result = "";
for(int i : hash) {
result += String.format("%02x", 0xff & i);
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
PHP
对于 PHP,我使用 hash
函数:
hash("sha256", $password);
输出(输入为国)
Java
编码设置为 UTF-8:d1566afa505af0f03b9156d0a9a518a25c2d4568b095ef4ee2dca7fcbb6c29c9
编码设置为 iso-8859-1:8a8de823d5ed3e12746a62ef169bcf372be0ca44f0a1236abc35df05d96928e1
PHP
e1c8436bc8529d791d58c74fefa160dfd678ca8db8f879b8392a42be84f78db3
最佳答案
这可能会有所帮助。
public static String SHA(String text)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("SHA-256");
byte[] md5 = new byte[64];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5 = md.digest();
return convertedToHex(md5);
}
关于java - 无论语言如何,都在 Java/PHP 中散列字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18732710/