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.
This commit is contained in:
Robert Turner 2021-07-15 20:08:00 -04:00 committed by GitHub
parent 9ed444ea2a
commit b9becb5c8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 28 additions and 16 deletions

View File

@ -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);
}
}