0

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

Haven
  • 7,808
  • 5
  • 25
  • 37

1 Answers1

2

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

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I tried the hex method from your post as well, but it doesn't work either, and I also wondering why... I also add the code into the question – Haven Nov 19 '15 at 08:12
  • @Haven: You're calling `String.getBytes`. That's *not* how you convert hex back to a byte array. You're getting the representation of that text in the default encoding... – Jon Skeet Nov 19 '15 at 08:15