import java.io.*;//输入输出
import java.util.*;//Scanner,Random
import java.math.*;//bigintger
public class Rsa{
public static void main(String[] args) {
int num1=0,num2=0,e=0,p=1;//num1,num2两个素数,e公匙,p明文
while(true){
Scanner cin = new Scanner(System.in);
System.out.println("请输入两个素数");
num1=cin.nextInt();//输入两个数
num2=cin.nextInt();
System.out.println("请输入原文");
p =cin.nextInt();
System.out.println("密文:"+doEcryption(p,num1,num2));
System.out.println("原文:"+doDecryption(p,num1,num2));
}
}
public static BigInteger doEcryption(int p,int first,int second){
int n=0,d=0,n1,size=0,e=0;//n就是n=p*q,d密匙,c密文。n1欧拉值,e密匙
int [] arr=new int[100];//素数数组
BigInteger c = BigInteger.valueOf(1);//c密文
BigInteger p1 = BigInteger.valueOf(p);//p1是p(明文)的BigInteger版
n1=(first-1)*(second-1);//欧拉值
n=first*second;
BigInteger n2 = BigInteger.valueOf(n);//n2是n的BigInteger版
boolean isPrime;
//是素数,写入数组
for (int i = 2; i < n1; i++) {
isPrime = true;
for (int j = 2; j < i; j++) {
//若能除尽,则不为素数
if ((i % j) == 0) {
isPrime = false;
break;
}
}
//如果是素数,则写入数组
if (isPrime) {
arr[size]=i;
size++;//数组地址加一
}
}
/*for(int k=1;k
System.out.print(arr[k]+" 0 ");*/
Random random = new Random();//随机数
int s = random.nextInt(size-1);//生成0-size-1之间数
e=arr[s];//取素数赋值给e
System.out.println("加密密匙{"+e+" "+n+"}");
n=first*second;//n
for(int i=0;i
c=c.multiply(p1);//p1明文
c=c.mod(n2);//加密算法c=p^e%n
return c;
}
public static BigInteger doDecryption(int p,int first,int second){
int n=0,d=0, i=1,n1;//n就是n=p*q,d密匙,i变量。n1欧拉值
n1=(first-1)*(second-1);//欧拉值
boolean flag=true;//判断5*d=96*x+1中x要用
BigInteger p1 = BigInteger.valueOf(p);//int p(明文) 赋值BigInteger p1
n=first*second;//n
BigInteger n2 = new BigInteger("" + n);//n赋值n2 int强转BigInteger
BigInteger c = BigInteger.valueOf(1);//密文c初始化1
while(flag)//找5*d=96*x+1中的x
{
if((96*i+1)%5==0)
{
d=(96*i+1)/5;//5*d=96*x+1公式算d
flag=false;
}
else
i++;
}
System.out.println("解密密匙{"+d+" "+n+"}");
for( i=0;i
{
p1=p1.multiply(c);//p=c^d
}
p1=p1.mod(n2);//解密公式p=c^d%n
return p1;
}
}