signature changes

2019-03-05 04:49发布

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);

or

String my_string = my_array.toString();

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.

I mean for example my_string changes when I do my_string.getBytes().toString() or my_array changes after (new String(my_array)).getBytes()

Thanks.

3条回答
可以哭但决不认输i
2楼-- · 2019-03-05 05:02

(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.

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);
查看更多
我只想做你的唯一
3楼-- · 2019-03-05 05:08

You have to encode byte array into Base64. You may also use methods - printBase64Binary() and parseBase64Binary() of javax.xml.bind.DatatypeConverter to encode or decode Base64.

查看更多
Animai°情兽
4楼-- · 2019-03-05 05:27

Both new String() and getBytes() implicitly use the platform default encoding and are overloaded to allow you to specify the encoding (which should almost always be done). Apparently your platform default encoding cannot represent all the byte values in your array.

But wanting to convert bytes to String and back is almost always the wrong thing to do in the first place. What exactly does this "signature" contain, and what is this "other side" you think you have to convert it to String for?

查看更多
登录 后发表回答