java rsa 加解密

时间:2021-07-14 21:38:15

参考 http://blog.csdn.net/a394268045/article/details/52232120

package rsa;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom; /**
* Created by Administrator on 2018/3/12.
*/
public class Main {
public static void main(String[] args) throws Exception {
String source = "hhh测试";
String cryptograph = encrypt(source);
System.out.println("生成的密文-->" + cryptograph); String target = decrypt(cryptograph);
System.out.println("解密密文-->" + target);
} public static void generateKeyPair() throws Exception {
SecureRandom sr = new SecureRandom(); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(512, sr); KeyPair kp = kpg.generateKeyPair(); Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate(); ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream("e:/publicKey.keystore"));
ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream("e:/privateKey.keystore"));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey); oos1.close();
oos2.close();
} public static String encrypt(String source) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:/publicKey.keystore"));
Key key = (Key) ois.readObject();
ois.close(); Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] b = source.getBytes("utf-8"); byte[] b1 = cipher.doFinal(b);
// return Base64.encodeBase64String(b1);
return Hex.encodeHexString(b1);
} public static String decrypt(String cryptograph) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:/privateKey.keystore"));
Key key = (Key) ois.readObject(); Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key); // byte[] b1 = Base64.decodeBase64(cryptograph);
//
// byte[] b = cipher.doFinal(b1);
//
// return new String(b, "utf-8"); byte[] b1 = Hex.decodeHex(cryptograph); byte[] b = cipher.doFinal(b1); return new String(b, "utf-8");
}
}