/**
* 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();
}
}
简易RSA加密算法的java实现
最新推荐文章于 2024-07-25 11:27:30 发布