Rsa的java实现

本文通过一个具体的Java程序实例,详细介绍了如何实现RSA加密过程。程序运行结果验证了其正确性,展示了RSA加密的有效性。
摘要由CSDN通过智能技术生成

/**
 * 主要用于计算超大整数超大次幂然后对超大的整数取模。
 * 我在网上查询到这个算法叫做"蒙哥马利算法"。
 */

class Exponentiation {

    /**
     * 超大整数超大次幂然后对超大的整数取模
     (base ^ exponent) mod n
     * @param base
     * @param exponent
     * @param n
     * @return
     */
    public BigInteger expMode(BigInteger base, BigInteger exponent, BigInteger n){
        char[] binaryArray = new StringBuilder(exponent.toString(2)).reverse().toString().toCharArray() ;
        int r = binaryArray.length ;
        List<BigInteger> baseArray = new ArrayList<BigInteger>() ;

        BigInteger preBase = base ;
        baseArray.add(preBase);
        for(int i = 0 ; i < r - 1 ; i ++){
            BigInteger nextBase = preBase.multiply(preBase).mod(n) ;
            baseArray.add(nextBase) ;
            preBase = nextBase ;
        }
        BigInteger a_w_b = this.multi(baseArray.toArray(new BigInteger[baseArray.size()]), binaryArray, n) ;
        return a_w_b.mod(n) ;
    }


    private BigInteger multi(BigInteger[] array, char[] bin_array, BigInteger n){
        BigInteger result = BigInteger.ONE ;
        for(int index = 0 ; index < array.length ; index ++){
            BigInteger a = array[index] ;
            if(bin_array[index] == '0'){
                continue ;
            }
            result = result.multiply(a) ;
            result = result.mod(n) ;
        }
        return result ;
    }

}

/**
 * 求最大公约数
 *
 */
class GCD {
    /**
     * <p>辗转相除法求最大公约数
     * @param a
     * @param b
     * @return
     */
    public BigInteger gcd(BigInteger a, BigInteger b){
        if(b.equals(BigInteger.ZERO)){
            return a ;
        }else{
            return gcd(b, a.mod(b)) ;
        }
    }
    /**
     * <p>扩展欧几里得算法:
     * <p>求ax + by = 1中的x与y的整数解(a,b互质)
     * @param a
     * @param b
     * @return
     */
    public BigInteger[] extGcd(BigInteger a, BigInteger b){
        if(b.equals(BigInteger.ZERO)){
            BigInteger x1 = BigInteger.ONE ;
            BigInteger y1 = BigInteger.ZERO ;
            BigInteger x = x1 ;
            BigInteger y = y1 ;
            BigInteger r = a ;
            BigInteger[] result = {r, x, y} ;
            return result ;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值