package com.zzq.rsa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class RSAUtil {
/**
* @param args
*/
public static void main(String[] args) {
String s = "zhuzhiqiang";
createPublicPrivateKey();
encryption(s);
decrypt();
}
public static void createPublicPrivateKey() {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
PublicKey pbKey = kp.getPublic();
PrivateKey prKey = kp.getPrivate();
ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream("RSA_pub_key.dat"));
ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream("RSA_pri_key.dat"));
oos1.writeObject(pbKey);
oos2.writeObject(prKey);
oos1.close();
oos2.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("生成钥匙失败!");
}
}
public static void encryption(String content) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("RSA_pub_key.dat"));
RSAPublicKey pbk = (RSAPublicKey)ois.readObject();
BigInteger e = pbk.getPublicExponent();
BigInteger n = pbk.getModulus();
System.out.println("e=" + e);
System.out.println("n=" + n);
byte[] text = content.getBytes("UTF-8");
// System.out.println("text" + text.toString());
BigInteger m = new BigInteger(text);
System.out.println("text=" + m);
BigInteger c = m.modPow(e, n);
System.out.println("c=" + c);
String s = c.toString();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("enc_rsa.dat")));
bw.write(s, 0, s.length());
bw.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("加密失败!");
}
}
public static void decrypt() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("enc_rsa.dat")));
String text = br.readLine();
BigInteger c = new BigInteger(text);
br.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("RSA_pri_key.dat"));
RSAPrivateKey prk = (RSAPrivateKey)ois.readObject();
ois.close();
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(new String(mt, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("解密失败!");
}
}
}