对于一个更通用的解决方案,如果你没有可用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