/*
 * Copyright 2021 The gRPC Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.grpc.util;

import com.google.common.io.BaseEncoding;
import io.grpc.ExperimentalApi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Collection;

/**
 * Contains certificate/key PEM file utility method(s).
 */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/8024")
public final class CertificateUtils {
  /**
   * Generates X509Certificate array from a PEM file.
   * The PEM file should contain one or more items in Base64 encoding, each with
   * plain-text headers and footers
   * (e.g. -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----).
   *
   * @param inputStream is a {@link InputStream} from the certificate files
   */
  public static X509Certificate[] getX509Certificates(InputStream inputStream)
      throws CertificateException {
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certs = factory.generateCertificates(inputStream);
    return certs.toArray(new X509Certificate[0]);
  }

  /**
   * Generates a {@link PrivateKey} from a PEM file.
   * The key should be PKCS #8 formatted.
   * The PEM file should contain one item in Base64 encoding, with plain-text headers and footers
   * (e.g. -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----).
   *
   * @param inputStream is a {@link InputStream} from the private key file
   */
  public static PrivateKey getPrivateKey(InputStream inputStream)
      throws UnsupportedEncodingException, IOException, NoSuchAlgorithmException,
      InvalidKeySpecException {
    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();
      }
    }
  }
}


@@ -2654,94 +2654,51 @@
     
-InputStreamReader isr = null;%0A    BufferedReader reader = null;%0A    try %7B%0A      isr = 
+BufferedReader reader = new BufferedReader(
 new 
@@ -2740,52 +2740,11 @@
 -8%22)
-;%0A      reader = new BufferedReader(isr
 );%0A
-  
     
@@ -2756,18 +2756,16 @@
 g line;%0A
-  
     whil
@@ -2797,34 +2797,32 @@
 e()) != null) %7B%0A
-  
       if (%22-----
@@ -2865,35 +2865,31 @@
 ) %7B%0A        
-  
 break;%0A
-  
       %7D%0A    
@@ -2884,30 +2884,26 @@
       %7D%0A    
-  %7D%0A  
+%7D%0A
     StringBu
@@ -2946,18 +2946,16 @@
 ();%0A    
-  
 while ((
@@ -2987,26 +2987,24 @@
  != null) %7B%0A
-  
       if (%22-
@@ -3049,26 +3049,24 @@
 ) %7B%0A        
- 
- 
 break;%0A     
@@ -3066,26 +3066,24 @@
 ;%0A      
-  
 %7D%0A      
   keyCon
@@ -3074,18 +3074,16 @@
 %7D%0A      
- 
- 
 keyConte
@@ -3103,26 +3103,22 @@
 e);%0A    
-  
 %7D%0A    
- 
- 
 byte%5B%5D d
@@ -3191,18 +3191,16 @@
 ));%0A    
-  
 KeyFacto
@@ -3250,18 +3250,16 @@
 %22);%0A    
- 
- 
 PKCS8Enc
@@ -3326,18 +3326,16 @@
 s);%0A    
-  
 return k
@@ -3374,144 +3374,8 @@
 c);%0A
-    %7D finally %7B%0A      if (null != reader) %7B%0A        reader.close();%0A      %7D%0A      if (null != isr) %7B%0A        isr.close();%0A      %7D%0A    %7D%0A
   %7D%0A

Revert "core: correcting a minor resource releasing issue"