使用Java原生库的加解密工具类时,随着加解密次数的增加,应用内存持续升高,并且无法通过GC进行内存回收,最终导致OOM
罪魁祸首就是BouncyCastleProvider这个对象
下面是网上博客中常见的rsa加解密实现
public static byte[] decryptByPrivateKeyMobile(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
// 与Android对接时 一定要指定RSA/ECB/PKCS1Padding和Provider Android的jdk和sun的jdk默认算法类型不同
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
其中一行代码很常见,构建Cipher时,传入一个新的BouncyCastleProvider实例,也就意味着,每进行一次加解密,都要创建BouncyCastleProvider。
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
源码跟踪:
// 该方法中有个操作 javax.crypto.Cipher#getInstance(java.lang.String, java.security.Provider)
Exception var9 = JceSecurity.getVerificationResult(var1);
// 进入JceSecurity.getVerificationResult继续跟踪
static synchronized Exception getVerificationResult(Provider var0) {
Object var1 = verificationResults.get(var0);
if (var1 == PROVIDER_VERIFIED) {
return null;
} else if (var1 != null) {
return (Exception)var1;
} else if (verifyingProviders.get(var0) != null) {
return new NoSuchProviderException("Recursion during verification");
} else {
Exception var3;
try {
verifyingProviders.put(var0, Boolean.FALSE);
URL var2 = getCodeBase(var0.getClass());
verifyProviderJar(var2);
// 这一行就是罪魁祸首
verificationResults.put(var0, PROVIDER_VERIFIED);
var3 = null;
return var3;
} catch (Exception var7) {
verificationResults.put(var0, var7);
var3 = var7;
} finally {
verifyingProviders.remove(var0);
}
return var3;
}
}
// 查看javax.crypto.JceSecurity#verifyingProviders的定义
private static final Map<Provider, Object> verifyingProviders = new IdentityHashMap();
// verifyingProviders 可以看到该类是一个静态类,也就意味着该map会常驻在堆区的old分区,并且oldGC也无法进行回收
将BouncyCastleProvider做成单例的,只初始化一次BouncyCastleProvider对象。
https://blog.csdn.net/dweizhao/article/details/73480762 使用jdk的命令行工具 完整的分析了从发现cpu飙升,到发现gc频繁,到发现内存无法释放的原因
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
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;
/**
*
* RSA公钥/私钥/签名工具包
*
*
* 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
*
*
* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
*
*
* @author huxyc
* @date 2019/4/26 13:59
* @since 1.0.6
*/
public class RSAUtils {
/**
* 加密算法RSA
*/
private static final String KEY_ALGORITHM = "RSA";
private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
/**
* 签名算法
*/
private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* 获取公钥的key
*/
private static final String PUBLIC_KEY = "RSAPublicKey";
/**
* 获取私钥的key
*/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 此对象不可以每次重复创建 会造成oom
* 全局都是用一个单例对象
*/
private static BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
/**
*
* 生成密钥对(公钥和私钥)
*
*
* @return Map
* @throws Exception Exception
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
*
* 用私钥对信息生成数字签名
*
*
* @param data 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return 数字签名
* @throws Exception Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64.encodeBase64String(signature.sign());
}
/**
*
* 校验数字签名
*
*
* @param data 已加密数据
* @param publicKey 公钥(BASE64编码)
* @param sign 数字签名
* @return true if the signature was verified, false if not.
* @throws Exception Exception
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64.decodeBase64(sign));
}
/**
*
* 私钥解密
*
*
* @param encryptedData 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return 解密后的数据
* @throws Exception Exception
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
* Android端的加解密 需要指定BouncyCastleProvider
* 并配上算法的Padding类型
*
* 私钥解密
*
*
* @param encryptedData 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return 解密后的数据
* @throws Exception Exception
*/
public static byte[] decryptByPrivateKeyMobile(byte[] encryptedData, String privateKey)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
// 与Android对接时 一定要指定RSA/ECB/PKCS1Padding和Provider Android的jdk和sun的jdk默认算法类型不同
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, bouncyCastleProvider);
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
*
* 公钥解密
*
*
* @param encryptedData 已加密数据
* @param publicKey 公钥(BASE64编码)
* @return 解密后的数据
* @throws Exception Exception
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
*
* 公钥加密
*
*
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
* @return 加密后的数据
* @throws Exception Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* Android端的加解密 需要指定BouncyCastleProvider
* 并配上算法的Padding类型
*
* 公钥加密
*
*
* @param data 源数据
* @param publicKey 公钥(BASE64编码)
* @return 加密后的数据
* @throws Exception Exception
*/
public static byte[] encryptByPublicKeyMobile(byte[] data, String publicKey)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
// 与Android对接时 一定要指定RSA/ECB/PKCS1Padding和Provider Android的jdk和sun的jdk默认算法类型不同
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, bouncyCastleProvider);
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
*
* 私钥加密
*
*
* @param data 源数据
* @param privateKey 私钥(BASE64编码)
* @return 加密后的数据
* @throws Exception Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
*
* 获取私钥
*
*
* @param keyMap 密钥对
* @return base64后的PrivateKey
*/
public static String getPrivateKey(Map<String, Object> keyMap) {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64.encodeBase64String(key.getEncoded());
}
/**
*
* 获取公钥
*
*
* @param keyMap 密钥对
* @return base64后的PublicKey
*/
public static String getPublicKey(Map<String, Object> keyMap) {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64.encodeBase64String(key.getEncoded());
}
/****** 测试方法********/
private static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFa/ViCvW8Dk2HEYfkOsCjJUZYXM3c7uYwqljAcsKCMMyK+TY2cACV8XU+u2MmlMj2LijcZ0FPPUUG59Z9VAhrciT8a1n2ejbI2et9pizIE8OsEPyigenmUqwqXd61Y2m+928w0UMngQ2QK2Vh5bHhoGL0QbJfnRYdpqq9x++V4wIDAQAB";
private static String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIVr9WIK9bwOTYcRh+Q6wKMlRlhczdzu5jCqWMBywoIwzIr5NjZwAJXxdT67YyaUyPYuKNxnQU89RQbn1n1UCGtyJPxrWfZ6NsjZ632mLMgTw6wQ/KKB6eZSrCpd3rVjab73bzDRQyeBDZArZWHlseGgYvRBsl+dFh2mqr3H75XjAgMBAAECgYBIAtjSLfArq9yURhX+TOekJn4tOwmxcQ+0vHxigo4RDp2XdKKaByGJzGTnkuQU8sD0fj13mBNb3UngTEksI6rW6iBJDy15Q28JP71gIQcHRBdkK1ezaHyC6eA35/6/pjuebLtftdH7kD5X3kUkOTIZCvC21JHuHcVeSAXoO93NwQJBANEvfpZU9R9NiVWUmbS59rPDXRD1Q0tnKrC3BjAFx/g32uCIm8n4Pt2gcJ5fNYGG654r2rMiq0J8xUBUl8ET94sCQQCjR9vOUFuGrjcZ/TS5Q4Mo8vYExwa99zrZJDqr2FnbNKLr9KX79gxCUOWPiRCVOGgBC2b8xDMJ8xaWa5G8H+YJAkAclu4pI7FgttsnPCkJv0TNas0EbVDmNFJsVodc9t1OumuKtoD8SJZm+e+KZZ7NdiArvPil9P4NFzpqQWWAOPdjAkAJ/4NxHbCNDavoFn4c/gpQ/peb8UfzZ+kdlL9W+HeAGbgENMXZKNbVVLjJ0j3GtV6A+d7DiYwKhu0SJuIUn+tpAkAwtKoTM1s7k4v/kElOiDWg7tbvEQAwNu9y5NIrH7f7udNxhnIcxWTtd1qSBkeYbCjyfjDI42JVhASB4p9oCscc";
static {
// try {
// Map keyMap = RSAUtils.genKeyPair();
// publicKey = RSAUtils.getPublicKey(keyMap);
// privateKey = RSAUtils.getPrivateKey(keyMap);
// System.err.println("公钥: \n\r" + publicKey);
// System.err.println("私钥: \n\r" + privateKey);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
}
public static void main(String[] args) throws Exception {
// Thread.sleep(1000);
// test();
// testSign();
// testHttpSign();
// testSignForApp();
}
// static void test() throws Exception {
//
// System.err.println("公钥加密——私钥解密");
// String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";
// System.out.println("\r加密前文字:\r\n" + source);
// byte[] data = source.getBytes();
// byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
// System.out.println("加密后文字:\r\n" + new String(encodedData));
// byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
// String target = new String(decodedData);
// System.out.println("解密后文字: \r\n" + target);
//
// }
//
// static void test2() throws Exception {
//
// System.err.println("公钥加密——私钥解密");
// String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";
// System.out.println("\r加密前文字:\r\n" + source);
// byte[] data = source.getBytes();
// byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
// System.out.println("加密后文字:\r\n" + new String(encodedData));
// byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
// String target = new String(decodedData);
// System.out.println("解密后文字: \r\n" + target);
//
// }
//
// static void testSign() throws Exception {
// System.err.println("私钥加密——公钥解密");
// String source = "这是一行测试RSA数字签名的无意义文字";
// System.out.println("原文字:\r\n" + source);
// byte[] data = source.getBytes();
// byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
// System.out.println("加密后:\r\n" + new String(encodedData));
// byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
// String target = new String(decodedData);
// System.out.println("解密后: \r\n" + target);
// System.err.println("私钥签名——公钥验证签名");
// String sign = RSAUtils.sign(encodedData, privateKey);
// System.err.println("签名:\r" + sign);
// boolean status = RSAUtils.verify(encodedData, publicKey, sign);
// System.err.println("验证结果:\r" + status);
//
// }
//
// static void testSignForApp() throws Exception {
// // 简单签名
// String jsonStr = "{\"params\":{\"merchantCode\":\"2000\",\"requestNo\":\"IY2210625768227087369\",\"queryType\":\"PRETRANSACTION\"}}";
// String timeStampStr = System.currentTimeMillis() + "";
// String appid = "123";
//
// // 模拟数据md5
// String md5 = Md5Util.md5(jsonStr + timeStampStr + appid);
//
// // 使用私钥加密
// String sign = RSAUtils.sign(md5.getBytes(), privateKey);
//
// // 使用公钥验证
// boolean verify = RSAUtils.verify(md5.getBytes(), publicKey, sign);
// System.err.println("验证结果(预期通过):" + verify);
//
// boolean verify2 = RSAUtils.verify(("changedByHack" + md5).getBytes(), publicKey, sign);
// System.err.println("验证结果(预期不通过):" + verify2);
// }
//
// static void testHttpSign() throws Exception {
// String param = "id=1&name=张三";
// byte[] encodedData = RSAUtils.encryptByPrivateKey(param.getBytes(), privateKey);
// System.out.println("加密后:" + encodedData);
//
// byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
// System.out.println("解密后:" + new String(decodedData));
//
// String sign = RSAUtils.sign(encodedData, privateKey);
// System.err.println("签名:" + sign);
//
// boolean status = RSAUtils.verify(encodedData, publicKey, sign);
// System.err.println("签名验证结果:" + status);
// }
}