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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.