旧代码
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
byte[] key = new byte[16];
random.nextBytes(key);
BigInteger bigInteger = new BigInteger(key);
System.out.println("old:" + Arrays.toString(key));
System.out.println(bigInteger);
System.out.println("new:" + Arrays.toString(bigInteger.toByteArray()));
}
虽然这段代码可以进行正常转换,但是BigInteger不是正数范围,在密码学计算中,都要求是正数
指定byte数组为正数BigInteger
BigInteger m = new BigInteger(1, bytesMessage);
正数BigInteger,会有符号位,去除第一个符号位0,还原得到原始数组
public static byte[] toByteArray(BigInteger bi) {
byte[] array = bi.toByteArray();
if (array[0] == 0) {
byte[] tmp = new byte[array.length - 1];
System.arraycopy(array, 1, tmp, 0, tmp.length);
array = tmp;
}