2012-11-02 54 views
0

我正在使用以下代碼爲我的應用程序生成MD5哈希,它編碼了一些字符串值,然後通過我的Web服務將生成的哈希發送給了一些.Net代碼,該代碼讀取了我的MD5哈希並生成字符串的MD5他是從DB獲得,然後字符串比較它們MD5哈希生成問題

public static String getMD5Hash(String val) throws Exception { 
     byte[] bytes = val.getBytes(); 

     MessageDigest m = MessageDigest.getInstance("MD5"); 
     byte[] digest = m.digest(bytes); 
     String hash = new BigInteger(1, digest).toString(16); 
     System.out.println(hash.length()); 
     return hash; 
    } 

    public static void main(String[] asd) throws Exception{ 
     for(int i=0;i<10;i++){ 
      System.out.println(getMD5Hash(i+Math.pow(10, i)+""));//for testing 
      System.out.println(getMD5Hash(i+""));//for testing 
     } 
    } 

的問題是,因爲我從BigInteger的越來越變換散列和產生了一些時間哈希以0在這種情況下BIGINTEGER不啓動考慮0和另一方面.Net生成相同的字符串的散列時,它產生0,並以這種方式字符串比較返回false,例如 哈希碼我生成和發送 「102678D1922799CF9122B3F103975F1」 在.net中的散列哪裏是 「0102678D1922799CF9122B3F103975F1

也有一些時候,它生成的代碼像

.Net generates 0012678D1922799CF9122B3F103975F1 and java 12678D1922799CF9122B3F103975F1 

OR

0002678D1922799CF9122B3F103975F1 and 2678D1922799CF9122B3F103975F1 

我怎樣才能得到這個代碼中的所有0都在開始。 在此先感謝。

+0

使用Apache'Base64' - 參考線程 - http://stackoverflow.com/questions/469695/decode-base64-data-in-java – adatapost

+0

評論這個http://stackoverflow.com/questions/415953/generate-md5-hash-in-java – Chuidiang

+0

客戶端使用相同的.Net應用程序,所以我必須使用th是一個 – NoNaMe

回答

4

我不認爲有使用MessageDigest不僅僅是填充字符串是一個更好的辦法:

// ... 
StringBuilder builder = new StringBuilder(); 
for (int i = hash.length(); i < 64; i++) { 
    builder.append('0'); 
} 
builder.append(hash); 
return builder.toString(); 

...但你可以使用GuavaStrings.padStart()

// ... 
return Strings.padStart(hash, 64, '0'); 

...或者甚至使用Guava's hashing library,它返回與你的函數完全相同的字符串(我剛剛檢查過):

public static String getMD5Hash(String val) throws Exception { 
    return Hashing.md5().hashBytes(val.getBytes()).toString(); 
}