该程序只能应用于小一点的两个素数,只是验证RSA算法。
import java.util.Scanner;
public class AddSra {
/**
* RSA加密算法。对消息m=25进行加密,生成密文c,并解密。
*/
public static void main(String[] args) {
long m,n;
long M,N,a,e,c,z,d;
System.out.print("请输入两个素数: ");
Scanner scan = new Scanner(System.in);
m = scan.nextLong();//假设m = 5
n = scan.nextLong();//假设n = 7
a = 25;
N = m * n;
M = (m-1)*(n-1);
e = 5;//假设3
z = gcd(M,e);
d = getSecret(M,e);
c = addSra(a,e,N);
System.out.println("公钥为("+N+","+e+")");
System.out.println("私钥为"+d);
System.out.println("对消息a="+a+"进行加密,生成密文c:" + c);
System.out.println("对密文c进行解密为:" + decode(c,d,N));
}
public static long gcd(long x,long y){
if(y == 0){
return x;
}
return gcd(y,x%y);
}
public static long getSecret(long i,long j){
for(int d0=1;;d0++){
if( ( ((j*d0 - 1) % i) == 0) ){
return d0;
}
d0++;
}
}
public static long addSra(long x,long y,long z0){
return (long)(Math.pow(x, y) % z0);
}
public static long decode(long x,long y, long z0){
return (long)(Math.pow(x, y) % z0);
}
}