import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Date;
public class RSA {
private BigInteger p,q,n,d;
private BigInteger e=new BigInteger("65537");
private static BigInteger y;
private static BigInteger x;
private void getPrime(int length){
SecureRandom random=new SecureRandom();
random.setSeed(new Date().getTime());
while((p=BigInteger.probablePrime(length, random)).isProbablePrime(1)==false)
{
continue;
}
while((q=BigInteger.probablePrime(length, random)).isProbablePrime(1)==false)
{
continue;
}
}
public static BigInteger e_gcd(BigInteger a,BigInteger b){
if(b.intValue()==0){
x=new BigInteger("1");
y=new BigInteger("0");
return a;
}
BigInteger ans=e_gcd(b, a.mod(b));
BigInteger tmp=x;
x=y;
y=tmp.subtract(a.divide(b).multiply(y));
// System.out.println("tmp= "+tmp);
// System.out.println("gcd a="+a+" gcd b="+b+" gcd x="+x+" gcd y="+y);
// //System.out.println("gcd y="+y);
//
return ans;
}
BigInteger cald(BigInteger e,BigInteger n){
BigInteger gcd=e_gcd(e, n);
if(BigInteger.ONE.mod(gcd).intValue()!=0)
return new BigInteger("-1");
x.multiply(BigInteger.ONE.divide(gcd));
n=n.abs();
BigInteger ans=x.mod(n);
if(ans.compareTo(BigInteger.ZERO)<0)
ans.add(n);
return ans;
}
public BigInteger getp(){
return p;
}
public BigInteger getq(){
return q;
}
public BigInteger getn(){
return n;
}
public BigInteger gete(){
return e;
}
public BigInteger getd(){
return d;
}
public RSA(int length){
getPrime(length/2);
n=p.multiply(q);
d=cald(e, n);
//System.out.println("test : "+e.multiply(d).mod(n));
}
public RSA() {
getPrime(128);
n=p.multiply(q);
//d=cald(e, n);
BigInteger tmp=p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
d=e.modPow(tmp.subtract(BigInteger.ONE),n );
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RSA rsa=new RSA(20);
System.out.println("P= " +rsa.getp());
System.out.println("Q= " +rsa.getq());
System.out.println("E= " +rsa.gete());
System.out.println("N= " +rsa.getn());
System.out.println("D= " +rsa.getd());
BigInteger test=new BigInteger("100");
System.out.println("test:"+rsa.gete().multiply(rsa.getd()).mod(rsa.getn()));
BigInteger testc=test.modPow(rsa.getd(),rsa.getn());
testc=testc.modPow(rsa.gete(),rsa.getn());
boolean flag =testc.equals(test);
System.out.println(flag);
}
}
代码如上,e*d=1(mod n)成立了,为何在加解密之后不一致呢??