package com.sf.test;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSAUtil {
private static Map<Integer, String> KEY_MAP = new HashMap<>();
private static String PRIVATE_KEY_STR;
private static String PUBLIC_KEY_STR;
static {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
String privateKeyStr = new String(Base64.encodeBase64(privateKey.getEncoded()));
String publicKeyStr = new String(Base64.encodeBase64(publicKey.getEncoded()));
KEY_MAP.put(0, privateKeyStr);
KEY_MAP.put(1, publicKeyStr);
PRIVATE_KEY_STR = KEY_MAP.get(0);
PUBLIC_KEY_STR = KEY_MAP.get(1);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static String encrypt(String str, String publicKeyStr) throws Exception {
byte[] decoded = Base64.decodeBase64(publicKeyStr);
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
return outStr;
}
public static String decrypt(String str, String privateKeyStr) throws Exception {
byte[] inputBytes = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
byte[] decoded = Base64.decodeBase64(privateKeyStr);
PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
String outStr = new String(cipher.doFinal(inputBytes));
return outStr;
}
public static String encrypt(String str) throws Exception {
return encrypt(str, PUBLIC_KEY_STR);
}
public static String decrypt(String str) throws Exception {
return decrypt(str, PRIVATE_KEY_STR);
}
public static void main(String[] args) {
try {
String str = "Whenever I looked back, time blocked my path to retreat.";
String encryptedStr = RSAUtil.encrypt(str);
System.out.println(encryptedStr);
System.out.println(decrypt(encryptedStr));
} catch (Exception e) {
e.printStackTrace();
}
}
}