import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger; //不可变的任意精度的整数。
import java.util.Random;
public class rsa {
private static final BigInteger temp = null;
private BigInteger p;
private BigInteger q;
private BigInteger n;
private BigInteger t;
private BigInteger e;
private BigInteger d;
BigInteger s=new BigInteger("1");
public void getpq() throws IOException{
Random rand=new Random();
System.out.println("请输入随机数的位数");
BufferedReader stdi=new BufferedReader(new InputStreamReader(System.in));
String st=stdi.readLine();
int length=Integer.parseInt(st);
System.out.println(length);
this.p= temp.probablePrime(length,rand);
this.q=temp.probablePrime(length,rand);
System.out.println("大素数p的值为:"+p);
System.out.println("大素数q的值为:"+q);
this.n=p.multiply(q);
this.t=(p.subtract(s)).multiply(q.subtract(s));
}
public void geted() throws IOException{
System.out.println("请输入随机数e,作为加密密钥,要求0<e<t,gcd(e,t)=1");
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String str=stdin.readLine();
this.e=new BigInteger(str);
System.out.println("加密密钥为:"+e);
(this.d)=e.modInverse(t);
System.out.println("解密密钥为:"+d);
}
/** 加密方法 */
public void jiami() throws IOException{
System.out.println("请输入明文:");
BufferedReader stdi=new BufferedReader(new InputStreamReader(System.in));
//读取明文
String str=stdi.readLine();
BigInteger P=new BigInteger(str);
BigInteger C=P.modPow(e, n);
System.out.println("得到的密文是:"+C);
}
/**解密方法 */
public void jiemi() throws IOException{
System.out.println("请输入密文:");
BufferedReader stdi=new BufferedReader(new InputStreamReader(System.in));
//读取密文
String str=stdi.readLine();
BigInteger C=new BigInteger(str);
BigInteger P=C.modPow(d, n);
System.out.println("得到的名文是:"+P);
}
public static void main(String[] args) throws IOException {
rsa rs=new rsa();
rs.getpq();
rs.geted();
rs.jiami();
rs.jiemi();
}
}
以上是代码,运行结果如下:
请输入随机数的位数
3
3
大素数p的值为:5
大素数q的值为:5
请输入随机数e,作为加密密钥,要求0<e<t,gcd(e,t)=1
1
加密密钥为:1
解密密钥为:1
请输入明文:
zeqiang
Exception in thread "main" java.lang.NumberFormatException: For input string: "zeqiang"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.math.BigInteger.<init>(Unknown Source)
at java.math.BigInteger.<init>(Unknown Source)
at rsa.jiami(rsa.java:48)
at rsa.main(rsa.java:67)
这是我在网上看到的代码,请问this.p= temp.probablePrime(length,rand);
this.q=temp.probablePrime(length,rand); 是什么意思?
新手上路,大神指点!