📄 rsa.java
字号:
import java.math.BigInteger;
public class RSA {
public static void main(String args[])
{
int n = 65531;//
int e = 17;//(e,n)公钥
int d = 1;//(d,n)私钥
int p = 1;//素数1
int q = 1;//素数2
long begin = System.currentTimeMillis();
RSA rsa = new RSA();
if(args.length>2)
{
try
{
//通过控制台赋值
n = Integer.parseInt(args[0]);
e = Integer.parseInt(args[1]);
}
catch(Exception ex)
{
System.out.println("输入的必须是数字!");
}
}
for(int i=1;;i++)
{
if(rsa.isss(i))
{
for(int j=1;;j++)
{
if(rsa.isss(j))
{
if(i*j == n)
{
p = i;
q = j;
break;
}else if(i*j >n)
break;
}
}
if((p!=1)&&(q!=1))
break;
if(i>n/2)
{
System.out.println("没有得到答案!");
return;
}
}
}
System.out.println("n = " + n);
System.out.println("p = " + p);
System.out.println("q = " + q);
System.out.println("p*q = " + p*q);
int eulerValue = (p-1)*(q-1);//欧拉值
for(int i=1;i<n/2;i++)
{
if(e*i%eulerValue == 1)
{
d = i;
break;
}
}
System.out.println("e = " + e);
System.out.println("d = " + d);
System.out.println("公钥(e,n): ("+e+","+n+")");
System.out.println("私钥(d,n): ("+d+","+n+")");
BigInteger nB = new BigInteger(String.valueOf(n).getBytes());
BigInteger eB = new BigInteger(String.valueOf(e).getBytes());
BigInteger dB = new BigInteger(String.valueOf(d).getBytes());
System.out.println("nB= "+nB);
System.out.println("eB= "+eB);
System.out.println("dB= "+dB);
/*
* 加密与解密
* 参照Skey_RSA.java,Enc_RSA.java,Dec_RSA.java
* 调试时按这个顺序执行
*/
BigInteger m = null;
String s = "Hello world";
byte ptext[]=s.getBytes();
m=new BigInteger(ptext);
System.out.println("m= "+m);
BigInteger c=m.modPow(eB,nB); //加密
//String str = "71761D5F9D9C32B936AE92DBD0F39D9C8549AA5CAA22DE8FAA5CAC403F021543B8993AA178C93C5C";
//BigInteger c = new BigInteger(str.getBytes());
m=c.modPow(dB,nB);//解密
System.out.println("m= "+m);
String s1 = new String(m.toByteArray());
System.out.println("解密后明文为:" + s1);
long end = System.currentTimeMillis();
System.out.println("消耗的时间为:" + (end-begin)/1000 + "s");
}
public boolean isss(int i)
{//求素数
int j;
for(j=2;j<=i/2;j++)
{
if (i%j==0)
{
return false;
}
}
return true;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -