2015-09-26 24 views
1

有一些SO排隊,但沒有幫助我。我想將byte[]org.apache.commons.codec.digest.HmacUtils轉換爲String。此代碼產生一些奇怪的輸出:如何將byte []轉換爲Java中的String?

final String value = "value"; 
final String key = "key"; 
byte[] bytes = HmacUtils.hmacSha1(key, value); 
String s = new String(bytes); 

我在做什麼錯?

+1

通常,您在十六進制中顯示sha1散列。 [Commons Codec](https://commons.apache.org/proper/commons-codec/)有一個十六進制編碼器。 –

+0

可能相關,可能重複:http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java由此產生的'隨機二進制'的散列函數否則*不是一個有用的文本/字符串值。 – user2864740

回答

2

嘗試使用:

String st = HmacUtils.hmacSha1Hex(key, value); 
1

首先,hmacSha1的結果會產生一個摘要,而不是一個明確的String。此外,你可能需要指定的編碼格式,例如

String s = new String(bytes, "US-ASCII"); 

String s = new String(bytes, "UTF-8"); 
+0

那麼,我仍然得到一個奇怪的輸出(「WD:L#P F8 」d f/3「),它不符合這個測試應用程序 - http://www.freeformatter.com/ HMAC-generator.html。 – Artegon

+0

@ user1315357混淆是問題/預期輸出沒有明確指定。 – user2864740

1

對於一個更通用的解決方案,如果你沒有可用HmacUtils:

// Prepare a buffer for the string 
StringBuilder builder = new StringBuilder(bytes.length*2); 
// Iterate through all bytes in the array 
for(byte b : bytes) { 
    // Convert them into a hex string 
    builder.append(String.format("%02x",b)); 
    // builder.append(String.format("%02x",b).toUpperCase()); // for upper case characters 
} 
// Done 
String s = builder.toString(); 

來解釋你的問題: 你是使用散列函數。所以散列通常是一個字節數組,應該看起來很隨機。

如果您使用新的字符串(字節),您嘗試從這些字節創建一個字符串。但Java會嘗試將字節轉換爲字符。

例如:字節65(十六進制0x41)變成字母'A'。 66(十六進制0x42)字母'B'等。有些數字不能轉換爲可讀的字符。這就是爲什麼你看到像' '這樣的奇怪人物。

因此,新字符串(新字節[] {0x41,0x42,0x43})將變成'ABC'。

你想要的東西:你想要每個字節轉換成一個2位數的十六進制字符串(並追加這些字符串)。

問候!

相關問題