//非对称秘钥生成
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Skey_RSA
{
public static void main(String args[])throws Exception
{
KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp=kpg.genKeyPair();
PublicKey pbkey=kp.getPublic();
PrivateKey prkey=kp.getPrivate();
FileOutputStream f1=new FileOutputStream("Skey_RSA_pub.dat");
ObjectOutputStream b1=new ObjectOutputStream(f1);
b1.writeObject(pbkey);
FileOutputStream f2=new FileOutputStream("Skey_RSA_priv.dat");
ObjectOutputStream b2=new ObjectOutputStream(f2);
b2.writeObject(prkey);
}
}
//非对称加密
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
import java.io.*;
public class Enc_RSA
{
public static void main (String args[])throws Exception{
String s="Hello World!";
FileInputStream f=new FileInputStream("Skey_RSA_pub.dat");
ObjectInputStream b=new ObjectInputStream(f);
RSAPublicKey pbk=(RSAPublicKey)b.readObject();
BigInteger e=pbk.getPublicExponent();
BigInteger n=pbk.getModulus();
System.out.println("e="+e);
System.out.println("n="+n);
byte ptext[]=s.getBytes("UTF8");
BigInteger m=new BigInteger(ptext);
BigInteger c=m.modPow(e,n);
System.out.println("c="+c);
String cs=c.toString();
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Enc_RSA.dat")));
out.write(cs,0,cs.length());
out.close();
}
}
//非对称解密
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
import java.io.*;
public class Dec_RSA{
public static void main (String args[])throws Exception{
BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream("Enc_RSA.dat")));
String ctext=in.readLine();
BigInteger c=new BigInteger(ctext);
FileInputStream f=new FileInputStream("Skey_RSA_priv.dat");
ObjectInputStream b=new ObjectInputStream(f);
RSAPrivateKey prk=(RSAPrivateKey)b.readObject();
BigInteger d=prk.getPrivateExponent();
BigInteger n=prk.getModulus();
System.out.println("d="+d);
System.out.println("n="+n);
BigInteger m=c.modPow(d,n);
System.out.println("m="+m);
byte[] mt=m.toByteArray();
System.out.println("PlainText is");
for(int i=0;i<mt.length;i++)
{
System.out.print((char)mt[i]);
}
}
}