2014-10-28 65 views
0

我在JAVA中定義了一個md5函數,並使用PHP:md5()函數進行編碼,但輸出的結果不同。PHP md5與JAVA 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

您沒有通過您的sourceStringMessageDigest.digest(byte[])功能,因此您只能得到空輸入的摘要。我想你想要的東西一樣,

byte[] bytes = md.digest(sourceString.getBytes("UTF-8")); 
+0

我的錯......你說得對。 – HornedReaper 2014-10-28 03:14:01

0
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; 
} 
+0

PHP的md5()函數以十六進制形式返回md5散列。 如果你想在java中獲得md5 hash作爲字符串,你可以這樣寫 – 2017-04-19 04:40:46