我有一个包含2048位BigInteger编号的密钥。我想把它分成固定数量为64位的字,然后计算所有这些字的异或;任何人都可以帮我实现这个java吗?
示例:
大号(关键): 11380312415897726212538720767584623938377542218843650885786488543557849920563944820657401556147072220807050423844611527817088743264179887246035449031879964033048917437051768727745163996083995699396309860629605332639267450328379289961205789359923142431676348109877819086396004913235006262427231898532203764657706261780748597526471127787542155628754978941021278802504747939847153450812209928520258539639347968927907337576400038705453704498741239631581573919339705649004208586949422810873621196157474272177586468236634536851618181572350294408509526514361027546939234421045026063811415872877733865949984217287267027217419
输出(奇偶校验和:) 10249015871569703692
这是我实施的方法,但它无法正常工作:
/**
* *
* Receives a 2048 bits key and applies a word by word XOR to yield a 64 bit
* integer at the end.
*
* @param key 2048 bit integer form part A1 DH Key Exchange Protocol
* @return A 64 bit integer
*/
public static BigInteger parityWordChecksum(BigInteger key) {
LongBuffer buffer = ByteBuffer.wrap(key.toByteArray()).asLongBuffer();
long xor = 0;
while (buffer.hasRemaining()) {
xor ^= buffer.get();
}
return BigInteger.valueOf(xor);
}
答案 0 :(得分:2)
您的代码大多是正确的,但是,long
已签名,但您的预期输出假定它是无符号的。您可以通过将BigInteger.valueOf
替换为相应的BigInteger
构造函数(并进行一些按摩以从byte
值获取long
数组)来轻松解决此问题,如下所示:< / p>
public static BigInteger parityWordChecksum(BigInteger key) {
LongBuffer buffer = ByteBuffer.wrap(key.toByteArray()).asLongBuffer();
long xor = 0;
while (buffer.hasRemaining()) {
xor ^= buffer.get();
}
ByteBuffer result = ByteBuffer.allocate(8);
result.putLong(xor);
return new BigInteger(1, result.array()); // Signum 1 for unsigned
}
输出:
10249015871569703692
答案 1 :(得分:2)
如果你想在你的方法中只使用BigInteger
(而不是长),你可以这样做:
public static BigInteger parityWordChecksum(final BigInteger key) {
BigInteger result = new BigInteger("0");
BigInteger mask = BigInteger.ZERO;
for (int i = 0; i < 64; i++) {
mask = mask.setBit(i);
}
for (int i = 0; i < 2048; i += 64) {
result = result.xor(key.shiftRight(i).and(mask));
}
return result;
}