importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.OutputStreamWriter;importjava.math.BigInteger;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.NoSuchAlgorithmException;importjava.security.PrivateKey;importjava.security.PublicKey;importjava.security.SecureRandom;importjava.security.interfaces.RSAPrivateKey;importjava.security.interfaces.RSAPublicKey;publicclassRSA
{publicstaticvoidmain(String[] args)throwsNoSuchAlgorithmException, IOException, ClassNotFoundException
{
KeyPair pair=generateKeyPair();
PrivateKey privateKey=pair.getPrivate();
PublicKey publicKey=pair.getPublic();//Save Pirvate KeyFileOutputStream f1=newFileOutputStream("private.ppk");
ObjectOutputStream b1=newObjectOutputStream(f1);
b1.writeObject(privateKey);//Save Public KeyFileOutputStream f2=newFileOutputStream("public.ppk");
ObjectOutputStream b2=newObjectOutputStream(f2);
b2.writeObject(publicKey);
encrypt();
decrypt();
}publicstaticvoidencrypt()throwsIOException, ClassNotFoundException
{
String msg="Hello World!";
FileInputStream f=newFileInputStream("public.ppk");
ObjectInputStream b=newObjectInputStream(f);
RSAPublicKey pbk=(RSAPublicKey) b.readObject();//RSA算法是使用整数进行加密的,在RSA公钥中包含有两个整数信息:e和n。对于明文数字m,计算密文的公式是m的e次方再与n求模。BigInteger e=pbk.getPublicExponent();
BigInteger n=pbk.getModulus();//获取明文的大整数byteptext[]=msg.getBytes("utf-8");
BigInteger m=newBigInteger(ptext);//加密明文BigInteger c=m.modPow(e, n);//打印密文cSystem.out.println("c="+c);//将密文以字符串形式保存在文件中String cs=c.toString();
BufferedWriter out=newBufferedWriter(newOutputStreamWriter(newFileOutputStream("encrypt.dat"),"utf-8"));
out.write(cs,0, cs.length());
out.close();
}publicstaticvoiddecrypt()throwsIOException, ClassNotFoundException
{
BufferedReader in=newBufferedReader(newInputStreamReader(newFileInputStream("encrypt.dat"),"utf-8"));
String ctext=in.readLine();
BigInteger c=newBigInteger(ctext);//获取私钥FileInputStream f=newFileInputStream("private.ppk");
ObjectInputStream b=newObjectInputStream(f);
RSAPrivateKey prk=(RSAPrivateKey) b.readObject();//获取私钥的参数d,nBigInteger d=prk.getPrivateExponent();
BigInteger n=prk.getModulus();//解密明文BigInteger m=c.modPow(d, n);//计算明文对应的字符串并输出。byte[] mt=m.toByteArray();
System.out.println("PlainText is"+newString(mt,"utf-8"));
}publicstaticKeyPair generateKeyPair()throwsNoSuchAlgorithmException
{
KeyPairGenerator keyPairGen=KeyPairGenerator.getInstance("RSA");finalintKEY_SIZE=1024;
keyPairGen.initialize(KEY_SIZE,newSecureRandom());
KeyPair keyPair=keyPairGen.genKeyPair();returnkeyPair;
}
}