import java.util.Random;
public class RSA {
/*
* p与q为素数,n=p*q,t=(p-1)*(q-1),e与t互质,e*d % t=1,公钥(n,e);私钥(n,d)
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int p,q,e,d;
long n,t;
p = createRndPrime();
q = createRndPrime();//随机生成两个长质数
n = p * q;
t = (p-1) * (q-1);
System.out.println("n:"+n);
e = createPrime(t); //e与t互质
System.out.println("e:"+e);
d = create_d(e, t);//求d
System.out.println("d:"+d);
System.out.print("公钥:("+n+","+e+")");
System.out.print("私钥:("+n+","+d+")");
}
static boolean isPrime(int a){
for(int i=2; i<=Math.sqrt(a); i++){
if(a%i == 0){
return false;//不为质数
}
}
return true;//为质数
}
static int createRndPrime(){
Random random = new Random();
int p;
do{
p = random.nextInt();//随机生成质数
}while(!isPrime(p));
return p;
}
static int createPrime(long t){ //随机生成一个与t互质的数e
Random random = new Random();
boolean flag = false;
int e;
do{
e = random.nextInt();
if(e<1 || e>t){
flag = true;
}else if(t % e == 0){
flag = true;
}
}while(flag);
return e;
// for(int i=2; i<t; i++){
// if(t%i != 0){
// return i;
// }
// }
// return 0;
}
static int create_d(long e,long t){//求d
for(int d=1; ; d++){
if( (e*d) % t ==1 ){
return d;
}
}
}
}
结果:
思想:随机生成两个素数p、q, n=p*q, t =(p-1)*(q-1),选一个数e, e与 t 互为质数,计算d,使d满足 e*d%t=1,公钥为(n,e),私钥为(n,d)