用 bigInteger 和其他方法重建字節數組 (Rebuild byte array with bigInteger and other method)


問題描述

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

(by HavenJon Skeet)

參考文件

  1. Rebuild byte array with bigInteger and other method (CC BY‑SA 2.5/3.0/4.0)

#bytearray #java #biginteger #encoding






相關問題

更改創建 XML 閱讀器時使用的 XmlDictionaryReaderQuotas 對象的 MaxArrayLength 屬性 (Changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader)

將文件讀入 4 個字節的 ByteArrays (Read file into ByteArrays of 4 bytes)

使用套接字 (C#) 進行文件傳輸 - 接收到的文件不包含完整數據 (File transfer using sockets (C#) - received file doesn't contain full data)

將 Java 字節讀取器轉換為 InputStream (Converting a Java byte reader to an InputStream)

用 bigInteger 和其他方法重建字節數組 (Rebuild byte array with bigInteger and other method)

如何將字節數組作為參數發送到 HTML.Action? (How to send byte array as paramater to HTML.Action?)

如何將存儲在字節數組中的圖像加載到 WebView? (How to load an image stored in a byte array to WebView?)

我希望將畫布保存為 mySql blob 字段中的 blob (I am looking to save a canvas as a blob in mySql blob field)

將字節數組的部分轉換為整數值 (Converting sections of byte arrays to integer values)

從內存中釋放 jni 引用 (Freeing jni references from memory)

為什麼 JPGEncoded bytearray 從 AS3 發送到 AMFPHP 會導致圖像無效? (Why is JPGEncoded bytearray sent from AS3 to AMFPHP resulting in an invalid image?)

Java:字節到浮點數/整數 (Java: Bytes to floats / ints)







留言討論