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

指定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;
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM