简易RSA加密算法的java实现

/**
 * author:梁宸
 */
import java.util.Scanner; //键盘扫描类
public class Main {


    static class Rsa{
        //公开&&私有密钥中的n
        private int n;
        //公开密钥中的e
        private int e;
        //私有密钥中的d;
        private int d;
        //密文C
        private int c;
        //明文M
        private int m;
        Scanner input = new Scanner(System.in);
        //设置公开密钥与私有密钥
        public void sheZhiMY(){
            System.out.println("请输入两个素数p与q,系统将自动生成公开密钥与私有密钥");
            int p=input.nextInt();
            int q=input.nextInt();
            //生成n
            this.n = p*q;
            //生成e
            for(int i=2;i<(q-1)*(p-1);i++){
                int g = Match.maxDivisor(i,(q-1)*(p-1));
                if(g==1){
                    this.e = i;
                    break;
                }
            }
            //私有密钥生成
            for(int i=1; ;i++){

                int temp = Match.ramainder(this.e*i,(q-1)*(p-1));
                if(temp==1){
                    this.d=i;
                    break;
                }
            }
            System.out.println("公有密钥为("+this.e+","+this.n+");私有密钥为("+this.d+","+this.n+").");

        }
        //加密
        public void jiaMi(){
            System.out.println("请输入要加密的明文");
            this.m = input.nextInt();
            this.c = Match.ramainder((int)Math.pow( this.m, this.e),this.n);

            System.out.println("加密后的密文为"+this.c);
        }
        //解密
        public void jieMi(){
            System.out.println("请输入要解密的密文");
            this.c = input.nextInt();
            this.m = Match.ramainder((int)Math.pow(this.c,this.d),this.n);

            System.out.println("解密后的明文为"+this.m);
        }




    }



    //求余数和最大公约数的数学工具
    static class Match{
        //求最大公约数
        public static int maxDivisor(int a, int b){
            int n = a;
            int m = b;
            int r = 0;
            while(m!=0){
                r = n%m;
                n = m;
                m = r;
            }
            return n;
        }
        //求余
        public static int ramainder(int dividend, int dividor) {
            return dividend - dividend / dividor * dividor;
        }
    }

    public static void main(String[] args) {
        Rsa rsa = new Rsa();
        rsa.sheZhiMY();
        rsa.jiaMi();
        rsa.jieMi();

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值