RSAUtils.java
public final class RSAUtils {
/** 安全服务提供者 */
private static final Provider PROVIDER = new BouncyCastleProvider();
/** 密钥大小 */
private static final int KEY_SIZE = 2048;
private static List<KeyPair> keys = new ArrayList<KeyPair>();
private static int MAX_KEYS = 500;//最大公钥数量
/**
* 不可实例化
*/
private RSAUtils() {
}
/**
* 生成密钥对
*
* @return 密钥对
*/
private static KeyPair getNewKeyPair() {
try {
//密钥生成器
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", PROVIDER);
//初始化密钥生成器
keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
//返回生成的密钥
return keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public static KeyPair generateKeyPair() {
//若达到最大公钥数量,从当前公钥库返回一个,否则生成新公钥并返回
if(keys.size()>MAX_KEYS){
return keys.get((int)(System.currentTimeMillis()%keys.size()));
}else{
// keys.get(-1);
KeyPair key = getNewKeyPair();
keys.add(key);
//System.out.println("生成密钥成功,当前密钥库"+keys.size());
return key;
}
}
/**
* 加密
*
* @param publicKey
* 公钥
* @param data
* 数据
* @return 加密后的数据
*/
public static byte[] encrypt(PublicKey publicKey, byte[] data) {
Assert.notNull(publicKey);
Assert.notNull(data);
try {
//RSA密码器实例
Cipher cipher = Cipher.getInstance("RSA", PROVIDER);
//初始化密码器为加密模式
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 解密
*
* @param privateKey
* 私钥
* @param data
* 数据
* @return 解密后的数据
*/
public static byte[] decrypt(PrivateKey privateKey, byte[] data) {
Assert.notNull(privateKey);
Assert.notNull(data);
try {
//生成密码器实例(填充模式)
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER);
//初始化密码器为加密模式
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
} catch (Exception e) {
return null;
}
}
}
RSAServiceImpl.java
@Service("rsaServiceImpl")
public class RSAServiceImpl implements RSAService {
/** "私钥"参数名称 */
private static final String PRIVATE_KEY_ATTRIBUTE_NAME = "privateKey";
@Transactional(readOnly = true)
public RSAPublicKey generateKey(HttpServletRequest request) {
Assert.notNull(request);
//生成密钥
KeyPair keyPair = RSAUtils.generateKeyPair();
//获取公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//获取私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//私钥设置在Session中
HttpSession session = request.getSession();
session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);
//公钥返回前端页面,并用其对明文进行加密
return publicKey;
}
@Transactional(readOnly = true)
public String decryptParameter(String name, HttpServletRequest request) {
Assert.notNull(request);
if (name != null) {
//获取Session中的私钥
HttpSession session = request.getSession();
RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute(PRIVATE_KEY_ATTRIBUTE_NAME);
//获取密文
String parameter = request.getParameter(name);
if (privateKey != null && StringUtils.isNotEmpty(parameter)) {
//用密钥对密文进行解密
return RSAUtils.decrypt(privateKey, parameter);
}
}
return null;
}
}