密钥交换算法DH,计算密钥值越界解决方式

2021-05-22  本文已影响0人  展翅高飞鹏程万里
public class DH {
    private int priKey;
    private static int dhP = 99991;
    private static int dhG = 5;

    public DH() {
        Random random = new Random();
        priKey = random.nextInt(10);
        System.out.println("DH 生成的私钥为 " + priKey);
    }

  /**
   * 获取DH算法的公钥
   */
    public int getPubKey() {
        return startPow(dhG, priKey).divideAndRemainder(new BigInteger(String.valueOf(dhP)))[1].intValue();
    }

  /**
  * 获取DH算法的共享密钥
  */
    public int getCommonKey(int pubKeyS) {
        //此处的divideAndRemainder 计算两个BigInteger之间的相除,获得由数组构成的商和余数
        return startPow(pubKeyS, priKey).divideAndRemainder(new BigInteger(String.valueOf(dhP)))[1].intValue();
    }

   /**
    * 计算幂次方。因为计算整数的幂次方可造成最终的数值超过Int最大的范围,导致计算错误。所以此处使用BigInteger来计算幂次方
    */
    private BigInteger startPow(int a, int b) {
        if (b == 0) {
            return new BigInteger(String.valueOf(1));
        } else {
            return pow(new BigInteger(String.valueOf(a)),b);
        }
    }

    private BigInteger pow(BigInteger a, int b) {
        if (b != 1)
           //multiply 代表乘法。此处使用递归计算a的b次方幂
            return a.multiply(pow(a, b - 1));
        else
            return a;
    }


}
上一篇 下一篇

猜你喜欢

热点阅读