From b9becb5c8e797f202ed0e566e752bd7a91e599e1 Mon Sep 17 00:00:00 2001 From: Robert Turner <33302790+rturner-edjuster@users.noreply.github.com> Date: Thu, 15 Jul 2021 20:08:00 -0400 Subject: [PATCH] core: correcting a minor resource releasing issue This change adds a traditional try/finally block around readers and streams to control the closing of those objects when the method has completed rather than relying on the GC to deal with them. This issue was flagged by an analysis tool via binary analysis of the grpc-core package as part of a dependency from another project. --- .../java/io/grpc/util/CertificateUtils.java | 44 ++++++++++++------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/core/src/main/java/io/grpc/util/CertificateUtils.java b/core/src/main/java/io/grpc/util/CertificateUtils.java index 980862d383..e8bbc90cb3 100644 --- a/core/src/main/java/io/grpc/util/CertificateUtils.java +++ b/core/src/main/java/io/grpc/util/CertificateUtils.java @@ -65,24 +65,36 @@ public final class CertificateUtils { public static PrivateKey getPrivateKey(InputStream inputStream) throws UnsupportedEncodingException, IOException, NoSuchAlgorithmException, InvalidKeySpecException { - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); - String line; - while ((line = reader.readLine()) != null) { - if ("-----BEGIN PRIVATE KEY-----".equals(line)) { - break; + InputStreamReader isr = null; + BufferedReader reader = null; + try { + isr = new InputStreamReader(inputStream, "UTF-8"); + reader = new BufferedReader(isr); + String line; + while ((line = reader.readLine()) != null) { + if ("-----BEGIN PRIVATE KEY-----".equals(line)) { + break; + } + } + StringBuilder keyContent = new StringBuilder(); + while ((line = reader.readLine()) != null) { + if ("-----END PRIVATE KEY-----".equals(line)) { + break; + } + keyContent.append(line); + } + byte[] decodedKeyBytes = BaseEncoding.base64().decode(keyContent.toString()); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKeyBytes); + return keyFactory.generatePrivate(keySpec); + } finally { + if (null != reader) { + reader.close(); + } + if (null != isr) { + isr.close(); } } - StringBuilder keyContent = new StringBuilder(); - while ((line = reader.readLine()) != null) { - if ("-----END PRIVATE KEY-----".equals(line)) { - break; - } - keyContent.append(line); - } - byte[] decodedKeyBytes = BaseEncoding.base64().decode(keyContent.toString()); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKeyBytes); - return keyFactory.generatePrivate(keySpec); } }