pom:
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSAUtil {
public static void main(String[] args) {
Map<String, String> keyPair = RSAUtil.generateKeyPair();
String publicKey = keyPair.get("publicKey");
String privateKey = keyPair.get("privateKey");
String string = "啦啦啦11";
String encrypt = RSAUtil.encrypt(string, publicKey);
String decryptedString = RSAUtil.decrypt(encrypt, privateKey);
System.out.println("publicKey:"+publicKey);
System.out.println("privateKey:"+privateKey);
System.out.println("string:"+string);
System.out.println("decryptedString:"+decryptedString);
}
/**
* 生成秘钥对
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<String, String> generateKeyPair(){
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyPairGen.initialize(1024,new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
String publicKey = new String(Base64.encodeBase64(rsaPublicKey.getEncoded()));
String privateKey = new String(Base64.encodeBase64((rsaPrivateKey.getEncoded())));
Map<String, String> keyMap = new HashMap<>();
keyMap.put("publicKey", publicKey);
keyMap.put("privateKey", privateKey);
return keyMap;
}
/**
* 加密
* @param string
* @param publicKey
* @return
* @throws Exception
*/
public static String encrypt(String string, String publicKey){
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = null;
try {
pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = null;
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return Base64.encodeBase64String(cipher.doFinal(string.getBytes("UTF-8")));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
*
* @param string
* @param privateKey
* @return
* @throws Exception
*/
public static String decrypt(String string, String privateKey){
try {
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
return new String(cipher.doFinal(Base64.decodeBase64(string)));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}