简体   繁体   English

如何在Java中将byte []转换为String?

[英]How to convert byte[] to String in Java?

There are some SO quetions but no helped me. 有一些特殊的风俗,但没有帮助我。 I would like to convert byte[] from org.apache.commons.codec.digest.HmacUtils to String. 我想将byte[]org.apache.commons.codec.digest.HmacUtils转换为String。 This code produces some weird output: 这段代码产生了一些奇怪的输出:

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

What am I doing wrong? 我究竟做错了什么?

尝试使用:

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

First, the result of hmacSha1 would produce a digest, not not a clear String . 首先, hmacSha1的结果将产生一个摘要,而不是一个清晰的String Besides, you may have to specify an encoding format, for example 此外,您可能需要指定一种编码格式,例如

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

or 要么

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

For a more general solution, if you don't have HmacUtils available: 对于更通用的解决方案,如果您没有可用的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();

To explain your problem: You are using a hash function. 解释您的问题:您正在使用哈希函数。 So a hash is usually an array of bytes which should look quite random. 因此,哈希通常是一个字节数组,应该看起来非常随机。

If you use new String(bytes) you try to create a string from these bytes. 如果使用新的String(bytes),则尝试从这些字节创建一个字符串。 But Java will try to convert the bytes to characters. 但是Java会尝试将字节转换为字符。

For example: The byte 65 (hex 0x41) becomes the letter 'A'. 例如:字节65(十六进制0x41)成为字母“ A”。 66 (hex 0x42) the letter 'B' and so on. 66(hex 0x42)字母'B',依此类推。 Some numbers can't be converted into readable characters. 某些数字无法转换为可读字符。 Thats why you see strange characters like ' '. 这就是为什么您会看到诸如``。

So new String(new byte[]{0x41, 0x42, 0x43}) will become 'ABC'. 因此,新字符串(新字节[] {0x41、0x42、0x43})将变为“ ABC”。

You want something else: You want each byte converted into a 2 digit hex String (and append these strings). 您还需要其他东西:您希望将每个字节转换为2位十六进制字符串(并附加这些字符串)。

Greetings! 问候!

You may need to have an encoding format. 您可能需要一种编码格式。 Check out this link here. 在这里查看此链接。

UTF-8 byte[] to String UTF-8字节[]转换为字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM