2014-08-28 124 views
1

我在Android上,所以它只是java,我有相同的輸入字符串,但每次獲得不同的值。我錯過了什麼?由於MD5爲相同的輸入返回不同的值

private String getShortenedKey(String key) { 
     String shortenedKey=null; 
     MessageDigest md = null; 
     LogUtils.LOGD(HASH_ALGO, "before key: "+ System.currentTimeMillis()); 
     try { 
      md = MessageDigest.getInstance("MD5"); 
     } catch (NoSuchAlgorithmException e) { 
      e.printStackTrace(); 
      shortenedKey = key; 
     } 
     LogUtils.LOGD(HASH_ALGO, "after key: "+ System.currentTimeMillis()); 

     md.update(key.getBytes()); 
     byte[] shortenedBytes = md.digest(); 
     shortenedKey = String.valueOf(shortenedBytes); 
     return shortenedKey; 
    } 

輸入字符串:

{"config":{"wp":"(1.000000,1.000000,1.000000,1.000000)","v":"8","unit":"auto","ef":true,"ws":1,"tt":0,"cs":1},"items":[{"startTime":1409180400,"id":"[email protected]_1409180400","class":"event","endTime":1409209200,"location":{"lng":151.20785,"lat":-33.85926},"priority":0},{"startTime":1409148000,"id":"[email protected]_1409148000","class":"event","endTime":1409234340,"location":{"lng":151.18089,"lat":-33.89153},"priority":0}]} 

更新:這麼多有效的答覆,謝謝。我選擇最容易改變的那個。乾杯。

回答

0

檢查修改後的版本。 你可以使用base64編碼的字節

private String getShortenedKey(String key) { 
    String shortenedKey=null; 
    MessageDigest md = null; 
    LogUtils.LOGD(HASH_ALGO, "before key: "+ System.currentTimeMillis()); 
    try { 
     md = MessageDigest.getInstance("MD5"); 

     md.update(key.getBytes()); 
     byte[] shortenedBytes = md.digest(); 
     shortenedKey = Base64.encodeToString(shortenedBytes, Base64.NO_WRAP); 
    } catch (NoSuchAlgorithmException e) { 
     e.printStackTrace(); 
     shortenedKey = key; 
    } 
    LogUtils.LOGD(HASH_ALGO, "after key: "+ System.currentTimeMillis()); 

    return shortenedKey; 
} 
1

此行

shortenedKey = String.valueOf(shortenedBytes); 

不是做你的想法。

爲了獲得數組內字節值的字符串表示,您需要實現一個小的實用程序方法。

此外,如果對MessageDigest.getInstance("MD5");的調用曾經拋出NoSuchAlgorithmException,則您的程序將在此稍後崩潰md.update(key.getBytes());,並帶有NullPointerException

+0

由於使用Base64編碼,我已經跟蹤'NoSuchAlgorithmException'和使用原始密鑰如果出現這種情況。 – 2014-08-28 13:53:53

1

由於@Henry解釋他的回答這個問題,String.valueOf(shortenedBytes)必須改變。

替換此;

shortenedKey = String.valueOf(shortenedBytes); 

to this;

shortenedKey = new String(Base64.encode(shortenedBytes)) 

您可以從Bouncycastle

Download the jar

相關問題