package com.msunhealth.common.utils.security;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtil {
public static String publicKey;
public static String privateKey;
public static void generateKey() {
// 1.初始化秘钥
KeyPairGenerator keyPairGenerator;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom sr = new SecureRandom(); // 随机数生成器
keyPairGenerator.initialize(512, sr); // 设置512位长的秘钥
KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 开始创建
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
// 进行转码
publicKey = Base64.encodeBase64String(rsaPublicKey.getEncoded());
// 进行转码
privateKey = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 公钥加密
* @param str
* @param publicKey
* @return
* @throws Exception
*/
public static String encrypt(String str, String publicKey) throws Exception {
//base64编码的公钥
byte[] decoded = java.util.Base64.getDecoder().decode(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = java.util.Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* 公钥加密
* @param publicKey
* @param plainTextData
* @return
* @throws Exception
*/
public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
if (publicKey == null) {
throw new Exception("加密公钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainTextData);
return base64ToStr(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
}
}
/**
* 私钥解密
* @param privateKey
* @param cipherData
* @return
* @throws Exception
*/
public static String decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) {
throw new Exception("解密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
return new String(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
throw new Exception("密文长度非法");
} catch (BadPaddingException e) {
e.printStackTrace();
throw new Exception("密文数据已损坏");
}
}
public static String base64ToStr(byte[] b) {
return javax.xml.bind.DatatypeConverter.printBase64Binary(b);
}
public static byte[] strToBase64(String str) {
return javax.xml.bind.DatatypeConverter.parseBase64Binary(str);
}
/**
* 根据公钥字符串加载公钥
* @param publicKeyStr
* @return
* @throws Exception
*/
public static RSAPublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
byte[] buffer = javax.xml.bind.DatatypeConverter.parseBase64Binary(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法", e);
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法", e);
} catch (NullPointerException e) {
throw new Exception("公钥数据为空", e);
}
}
/**
* 根据私钥字符串加载私钥
* @param privateKeyStr
* @return
* @throws Exception
*/
public static RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
try {
byte[] buffer = javax.xml.bind.DatatypeConverter.parseBase64Binary(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法", e);
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法", e);
} catch (NullPointerException e) {
throw new Exception("私钥数据为空", e);
}
}
public static void main(String[] args) throws Exception {
// 1.生成公钥和私钥密钥对
//MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALIMtsgAshbhZBatWJBjE2JG33YW/OgDWn18QvgPJRDjMGF7lDyLqgtvJ40kMGR8J1eGcQSv+HiK3MAalSyAKcsCAwEAAQ==
RSAUtil.generateKey();
System.out.println("私钥:" + RSAUtil.privateKey);
System.out.println("公钥:" + RSAUtil.publicKey);
String content = "{\"loginName\":\"test\",\"secret\":\"123456\"}";
System.out.println("加密前:"+content);
String encryptData=RSAUtil.encrypt(loadPublicKey(RSAUtil.publicKey),content.getBytes());
System.out.println("加密后:"+encryptData);
String decryptData=RSAUtil.decrypt(RSAUtil.loadPrivateKey(RSAUtil.privateKey),RSAUtil.strToBase64(encryptData));
System.out.println("解密后:"+decryptData);
}
}
评论0