我正在使用 BigInteger,并使用我的函式將 256 位的 BigInteger 寫入檔案(有 64 個這樣的數字)
public static byte[] toHH2(BigInteger n) {
byte[] b = new byte[256];
for(int i = 0; i < 256; i =8) {
b[i] = (byte) (n.longValue() >> (248 - i) & 0xff);
}
return b;
}
然后我需要讀取這個 256 位數字并將其寫入一個變數。但由于某種原因,我最終得到最多 64 位數字,而我需要 256,如何解決錯誤?
var dataSignatureInt = bytesToIntArray(Files.readAllBytes(Path.of("C:\\Users\\User\\IdeaProjects\\CryptoLab1\\src\\crypto\\DigitalSignatureGOST.png")));
for(int i = 0; i < file.length; i =256) { //file lenght = 16384
BigInteger value = BigInteger.valueOf(dataSignatureInt[i]);
for(int j = 0; j < 256; j ) {
System.out.println("i = " i " j = " j);
value = BigInteger.valueOf((value.longValue() << 8) | dataSignatureInt[i j]);
}
uj5u.com熱心網友回復:
256 位是 32 位元組,但不知何故你每位元組做一點。
public static byte[] toHH2(BigInteger n) {
byte[] b = n.toByteArray(); /// <= 32 bytes in big endian order!
return Arrays.copyOf(b, 32 - b.length);
if (b.length < 32) {
byte[] b2 = new byte[256];
System.arraycopy(b, 0, b2, 32 - b.length, b.length);
if (b[0] < 0) { // Do sign extension, if most significant byte negative.
for (int j = 0; j < 32 - b.length; j) {
b2[j] = -1;
}
}
b = b2;
}
return b;
}
為了方便,我填充了它。不需要,但它表明最高有效位元組位于位元組的索引 0 處。
// Now several such 32 byte arrays are stored in the file.
var dataSignatureInt = Files.readAllBytes(Path.of(
"C:\\Users\\User\\IdeaProjects\\CryptoLab1\\src\\crypto\\DigitalSignatureGOST.png"));
int numberCount = dataSignatureInt.length / 32;
BigInteger[] numbers = new BigInteger[numberCount];
要將一個大位元組陣列拆分為 32 個位元組的子陣列,該類ByteBuffer是理想的。
ByteBuffer buf = ByteBuffer.wrap(dataSignatureInt);
byte[] bytes = new byte[32];
for (int i = 0; i < numberCount; i) {
buf.get(bytes);
numbers[i] = new BigInteger(bytes);
}
最后但同樣重要的是,如果您對單個位感興趣,您可以考慮使用BitSet而不是。BigInteger
BitSet bitSet = new BitSet(256);
byte[] shortenedBytes = bitSet.toByteArray();
bitSet = BitSet.valueOf(shortenedBytes);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/535394.html
標籤:爪哇
