byte数组和正数BigInteger之间的相互转换

旧代码数组

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不是正数范围,在密码学计算中,都要求是正数dom

指定byte数组为正数BigIntegercode

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;
    }
相关文章
相关标签/搜索