RSA有关的算法:扩展Euclid GCD、模幂运算的反复平方

1.模幂运算的反复平方算法


/**
 *  @author: cuttle
 *  @Date: 2020/12/2 20:18
 *  @Description: 模幂运算的反复平方算法
 */
public class RSA_RS4ME {
    public static void main(String[]args){
        System.out.println("a = 2,b = 40,n = 13");
        System.out.println(rs4mode(2,40,13));
        System.out.println("a = 7,b = 10,n = 11");
        System.out.println(rs4mode(7,10,11));
    }
    public static int rs4mode(int a,int b,int n){
        int d = 1;
        int c = 0;
        String bs = Integer.toBinaryString(b);
        int k = bs.length();
        for(int i=0;i<k;i++){
            c *= 2;
            d = (d * d) % n;
            if (bs.charAt(i) == '1'){
                c += 1;
                d = (d * a) % n;
            }
        }
        return d;
    }
}

2.扩展Euclid GCD算法


/**
 *  @author: cuttle
 *  @Date: 2020/12/2 20:50
 *  @Description: 扩展的EuclidGCD算法
 */
public class RSA_ExtEuclidGCD {
    public static void main(String[]args){
        int a = 128;
        int b = 423;
        System.out.println("a = "+ a +",b = " + b);
        int[] temp = extEuclidGCD(a,b);
        System.out.println(temp[0] + " = " + temp[1] + " * " + a + " + " + temp[2] + " * " + b);
    }
    public static int[] extEuclidGCD(int a,int b){
        int ans;
        int[] result=new int[3];
        if(b==0)
        {
            result[0]=a;
            result[1]=1;
            result[2]=0;
            return result;
        }
        int [] temp = extEuclidGCD(b,a%b);
        ans = temp[0];
        result[0]=ans;
        result[1]=temp[2];
        result[2]=temp[1]-(a/b)*temp[2];
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值