問題描述
用 bigInteger 和其他方法重建字節數組 (Rebuild byte array with bigInteger and other method)
當我在做簽名編碼時遇到一個奇怪的問題:
當我想重建一個字節數組時,它總是失敗:
//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!
然後我使用大整數:
BigInteger messageBig = new BigInteger(digest);
byte[] bigRestore = messageBig.toByteArray();
assert Arrays.equals(digest, bigRestore)); //true!
然後就可以了,不知道為什麼,c
參考解法
方法 1:
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.)