有人可以建议我如何将字节数组转换为字符串吗?此方法不起作用:
can anyone suggest me how to convert byte array to string? This method does not work:
byte [] my_array=....; String my_string = new String (my_array);或
String my_string = my_array.toString();我要做的是将签名转换为字符串,然后将其传递给另一面.但是当我使用上述方法和方法时,my_string.getBytes()签名会更改,然后无法验证.
What I want to do is to convert signature to string and pass it to so other side. But when I use method above and method then my_string.getBytes() signature changes and then fails to verify.
例如,我的意思是my_string在执行my_string.getBytes().toString()时发生更改 或(new String(my_array)).getBytes()
I mean for example my_string changes when I do my_string.getBytes().toString() or my_array changes after (new String(my_array)).getBytes()
谢谢.
推荐答案(您尚未明确说明,但我假设您的字节数组是某种加密签名.)
(You haven't stated so explicitly, but I'm assuming your byte array is a cryptographic signature of some kind.)
您在这里做错了两件事:
You're doing two things wrong here:
- 尝试直接从任意字节数组创建字符串:您的字节数组不表示编码的文本,所以请不要那样对待.
- 即使没有,您仍将使用平台默认编码,这几乎总是一个坏主意.
- Trying to create a string from an arbitrary byte array directly: your byte array does not represent encoded text, so don't treat it that way.
- Even if it did, you'd be using the platform default encoding, which is almost always a bad idea.
以可逆形式将任意二进制数据作为文本处理的最常见方法是使用 base64 .有一个公共领域的base64 Java库此处(还有许多其他免费选项):
The most common way of handling arbitrary binary data as text in a reversible form is to use base64. There's a public domain base64 Java library here (and plenty of other free options too):
byte[] signature = ...; String signatureBase64 = Base64.encode(signature); // Propagate signatureBase64 to the other side, then... byte[] signature = Base64.decode(signatureBase64);更多推荐
签名变更
发布评论