我在JAVA中定义了一个md5函数并使用PHP:md5()函数进行编码,但它们会输出不同的结果。
我想我的JAVA功能有问题。
以下是代码:
public static String MD5Encode(String sourceString) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest();
StringBuffer bf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if ((bytes[i] & 0xff) < 0x10) {
bf.append("0");
}
bf.append(Long.toString(bytes[i] & 0xff, 16));
}
return bf.toString();
}
答案 0 :(得分:-1)
private static String MD5Encode(String sourceString) {
try {
byte[] bytesOfMessage = sourceString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
// byte array of md5 hash
byte[] md5 = md.digest(bytesOfMessage);
// we convert bytes to hex as php's md5() would do
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < md5.length; i++) {
stringBuffer.append(Integer.toString((md5[i] & 0xff) + 0x100,
16).substring(1));
}
return stringBuffer.toString();
} catch (Exception e) {
}
return null;
}