2 回答
TA贡献1906条经验 获得超10个赞
ISTM是避免BigInteger和异或直接在字节数组可以同时解决几个你的问题。在必要的地方有填充,你总是得到一个 32 字节的数组。
如果您确保顶部字节(由于大端字节序在索引 0 处)不相同,您将始终拥有 248-255 位值。
如果需要小端字节序,则索引 31 处的字节不得为 0 且不同。我假设了 big-endian,因为这也是 BigInteger 在您的原始代码中返回的内容。
public class test
{
public static void main(String[] args) throws Exception
{
SecureRandom random = new SecureRandom();
// make "left" operand
byte[] randomBytesLeft = new bytes[32];
random.nextBytes(randomBytesLeft);
// make "right" operand
byte[] randomBytesRight = new byte[32];
do
{
random.nextBytes(randomBytesRight);
} while (randomBytesRight[0] == randomBytesLeft[0]); // or [31] for little-endian
// "xor" both operands
byte[] key = new byte[32];
for (int i = 0; i < 32; i++)
{
key[i] = randomBytesLeft[i] ^ randomBytesRight[i];
}
// if you really need a BigInteger:
// BigInteger finalXor = new BigInteger(key);
System.out.println(key.length);
}
}
FWIW,在我看来,您可以完全省略xoring,只需执行以下操作:
byte[] key = new byte[32];
do
{
random.nextBytes(key);
} while (key[0] == 0); // or key[31] for little-endian
那可能同样好,更简单。
TA贡献1804条经验 获得超3个赞
填充 0 是一种选择,我找到了一种方法:
if(key.length != 32) {
byte[] finalKey= new byte[32];
byte a = Byte.parseByte("00000000", 2);
for(int i =0; i<key.length; i++)
finalKey[i] = key[i];
for (int i = key.length ; i<32 ; i++)
finalKey[i] = a;
key = finalKey;
}
它需要一个循环和另一个字节数组,因为出于某种原因,key[31] 抛出了一个 ArrayOutOfBound 异常,但它有效……如果有人可以改进它,请随时这样做。
编辑: OldCurmudgeon 的更好解决方案:
key = Arrays.copyOf(key, 32);
它会自动用 0 填充高位。
添加回答
举报