when I doing the signature encoding I meet a stranger problem:
When I want to rebuild a byte array, it always failed with :
//digest is the original byte array
String messageHex = bytesToHex(digest);
byte[] hexRestore = messageHex.getBytes();
assert Arrays.equals(digest, hexRestore); //false!
String utf8Digest = new String(digest, "UTF8");
byte[] utf8Restore = utf8Digest.getBytes("UTF8");
assert Arrays.equals(digest, utf8Restore); //false!
Then I use big Integer:
BigInteger messageBig = new BigInteger(digest);
byte[] bigRestore = messageBig.toByteArray();
assert Arrays.equals(digest, bigRestore)); //true!
Then it works, I don't know why, c
Don't use either of these approaches. Either convert into hex directly (not using BigInteger
) or use base64. BigInteger
will faithfully reproduce numbers , but it's not meant to be a general purpose binary-to-hex converter. In particular, it will lose leading zeroes, because they're insignificant when treating the data as an integer . (If you know the expected length you could always format it to that, but why bother? Just treat the data as arbitrary data instead of as a number.)
Definitely don't try to "decode" the byte array as if it's UTF-8-encoded text - it isn't.
There are plenty of questions on Stack Overflow about converting byte arrays to hex or base64 . (Those are just links to two examples... search for more.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.