對於一個更通用的解決方案,如果你沒有可用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位數的十六進制字符串(並追加這些字符串)。
問候!
通常,您在十六進制中顯示sha1散列。 [Commons Codec](https://commons.apache.org/proper/commons-codec/)有一個十六進制編碼器。 –
可能相關,可能重複:http://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java由此產生的'隨機二進制'的散列函數否則*不是一個有用的文本/字符串值。 – user2864740