美文网首页
密钥交换算法DH,计算密钥值越界解决方式

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

作者: 展翅高飞鹏程万里 | 来源:发表于2021-05-22 09: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;
    }


}

相关文章

网友评论

      本文标题:密钥交换算法DH,计算密钥值越界解决方式

      本文链接:https://www.haomeiwen.com/subject/iidnjltx.html