[英]How to convert byte[] to String in Java?
有一些特殊的风俗,但没有帮助我。 我想将byte[]
从org.apache.commons.codec.digest.HmacUtils
转换为String。 这段代码产生了一些奇怪的输出:
final String value = "value";
final String key = "key";
byte[] bytes = HmacUtils.hmacSha1(key, value);
String s = new String(bytes);
我究竟做错了什么?
尝试使用:
String st = HmacUtils.hmacSha1Hex(key, value);
首先, hmacSha1
的结果将产生一个摘要,而不是一个清晰的String
。 此外,您可能需要指定一种编码格式,例如
String s = new String(bytes, "US-ASCII");
要么
String s = new String(bytes, "UTF-8");
对于更通用的解决方案,如果您没有可用的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();
解释您的问题:您正在使用哈希函数。 因此,哈希通常是一个字节数组,应该看起来非常随机。
如果使用新的String(bytes),则尝试从这些字节创建一个字符串。 但是Java会尝试将字节转换为字符。
例如:字节65(十六进制0x41)成为字母“ A”。 66(hex 0x42)字母'B',依此类推。 某些数字无法转换为可读字符。 这就是为什么您会看到诸如``。
因此,新字符串(新字节[] {0x41、0x42、0x43})将变为“ ABC”。
您还需要其他东西:您希望将每个字节转换为2位十六进制字符串(并附加这些字符串)。
问候!
您可能需要一种编码格式。 在这里查看此链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.