Skip to content

Commit b9becb5

Browse files
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.
1 parent 9ed444e commit b9becb5

1 file changed

Lines changed: 27 additions & 15 deletions

File tree

core/src/main/java/io/grpc/util/CertificateUtils.java

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,24 +65,36 @@ public static X509Certificate[] getX509Certificates(InputStream inputStream)
6565
public static PrivateKey getPrivateKey(InputStream inputStream)
6666
throws UnsupportedEncodingException, IOException, NoSuchAlgorithmException,
6767
InvalidKeySpecException {
68-
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
69-
String line;
70-
while ((line = reader.readLine()) != null) {
71-
if ("-----BEGIN PRIVATE KEY-----".equals(line)) {
72-
break;
68+
InputStreamReader isr = null;
69+
BufferedReader reader = null;
70+
try {
71+
isr = new InputStreamReader(inputStream, "UTF-8");
72+
reader = new BufferedReader(isr);
73+
String line;
74+
while ((line = reader.readLine()) != null) {
75+
if ("-----BEGIN PRIVATE KEY-----".equals(line)) {
76+
break;
77+
}
7378
}
74-
}
75-
StringBuilder keyContent = new StringBuilder();
76-
while ((line = reader.readLine()) != null) {
77-
if ("-----END PRIVATE KEY-----".equals(line)) {
78-
break;
79+
StringBuilder keyContent = new StringBuilder();
80+
while ((line = reader.readLine()) != null) {
81+
if ("-----END PRIVATE KEY-----".equals(line)) {
82+
break;
83+
}
84+
keyContent.append(line);
85+
}
86+
byte[] decodedKeyBytes = BaseEncoding.base64().decode(keyContent.toString());
87+
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
88+
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKeyBytes);
89+
return keyFactory.generatePrivate(keySpec);
90+
} finally {
91+
if (null != reader) {
92+
reader.close();
93+
}
94+
if (null != isr) {
95+
isr.close();
7996
}
80-
keyContent.append(line);
8197
}
82-
byte[] decodedKeyBytes = BaseEncoding.base64().decode(keyContent.toString());
83-
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
84-
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKeyBytes);
85-
return keyFactory.generatePrivate(keySpec);
8698
}
8799
}
88100

0 commit comments

Comments
 (0)