From 71b723c056cd67d4aa5a975f48ebc499bf6fed53 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 3 Jan 2024 12:01:58 +0800 Subject: [PATCH] fix memory leak --- .../apache/httpclient/util/PemUtil.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/main/java/com/wechat/pay/contrib/apache/httpclient/util/PemUtil.java b/src/main/java/com/wechat/pay/contrib/apache/httpclient/util/PemUtil.java index 4921875..79c5c2f 100644 --- a/src/main/java/com/wechat/pay/contrib/apache/httpclient/util/PemUtil.java +++ b/src/main/java/com/wechat/pay/contrib/apache/httpclient/util/PemUtil.java @@ -38,6 +38,9 @@ public static PrivateKey loadPrivateKey(String privateKey) { } public static PrivateKey loadPrivateKey(InputStream inputStream) { + if(inputStream == null){ + throw new IllegalArgumentException("无效文件流"); + } ByteArrayOutputStream os = new ByteArrayOutputStream(2048); byte[] buffer = new byte[1024]; String privateKey; @@ -48,11 +51,21 @@ public static PrivateKey loadPrivateKey(InputStream inputStream) { privateKey = os.toString("UTF-8"); } catch (IOException e) { throw new IllegalArgumentException("无效的密钥", e); + }finally { + try { + inputStream.close(); + os.close(); + } catch (IOException e) { + // ignore + } } return loadPrivateKey(privateKey); } public static X509Certificate loadCertificate(InputStream inputStream) { + if(inputStream == null){ + throw new IllegalArgumentException("无效文件流"); + } try { CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream); @@ -64,6 +77,12 @@ public static X509Certificate loadCertificate(InputStream inputStream) { throw new RuntimeException("证书尚未生效", e); } catch (CertificateException e) { throw new RuntimeException("无效的证书", e); + }finally { + try { + inputStream.close(); + } catch (IOException e) { + // ignore + } } }