<commit_before>/**
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * 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.fabric8.kubernetes.client.internal;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
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.security.spec.RSAPrivateCrtKeySpec;
import okio.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CertUtils {

  private static final Logger LOG = LoggerFactory.getLogger(CertUtils.class);

  public static InputStream getInputStreamFromDataOrFile(String data, String file) throws FileNotFoundException {
    if (data != null) {
      byte[] bytes = null;
      ByteString decoded = ByteString.decodeBase64(data);
      if (decoded != null) {
          bytes = decoded.toByteArray();
      } else {
          bytes = data.getBytes();
      }

      return new ByteArrayInputStream(bytes);
    }
    if (file != null) {
      return new FileInputStream(file);
    }
    return null;
  }

  public static KeyStore createTrustStore(String caCertData, String caCertFile) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) {
      return createTrustStore(pemInputStream);
    }
  }

  public static KeyStore createTrustStore(InputStream pemInputStream) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    KeyStore trustStore = KeyStore.getInstance("JKS");
    loadDefaultKeyStoreFiles(trustStore);

    while (pemInputStream.available() > 0) {
      CertificateFactory certFactory = CertificateFactory.getInstance("X509");
      X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);

      String alias = cert.getSubjectX500Principal().getName();
      trustStore.setCertificateEntry(alias, cert);
    }
    return trustStore;
  }

  public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
      CertificateFactory certFactory = CertificateFactory.getInstance("X509");
      X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

      byte[] keyBytes = decodePem(keyInputStream);

      PrivateKey privateKey;

      KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
      try {
        // First let's try PKCS8
        privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
      } catch (InvalidKeySpecException e) {
        // Otherwise try PKCS8
        RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes);
        privateKey = keyFactory.generatePrivate(keySpec);
      }

      KeyStore keyStore = KeyStore.getInstance("JKS");
      loadDefaultKeyStoreFiles(keyStore);

      String alias = cert.getSubjectX500Principal().getName();
      keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[]{cert});

      return keyStore;
  }

  private static void loadDefaultKeyStoreFiles(KeyStore keyStore)
    throws CertificateException, NoSuchAlgorithmException, IOException {
    File defaultKeyStore = new File(System.getProperty("user.home"), ".keystore");
    File javaKeyStore =
      new File(System.getProperty("java.home"), "lib" + File.separator + "security" + File.separator + "cacerts");
    char[] defaultPassphrase = "<PASSWORD>".toCharArray();

    boolean loaded = false;
    String notLoadedMessage = "There is a problem with reading default keystore file %s with the default passphrase %s "
      + "- the keystore file won't be loaded. The reason is: %s";

    try {
      // try to load ~/.keystore
      loaded = loadKeyStoreFile(keyStore, defaultKeyStore, defaultPassphrase);
    } catch (Exception e) {
      LOG.info(notLoadedMessage, defaultKeyStore.getAbsolutePath(), defaultPassphrase, e.getMessage());
    }
    if (!loaded) {
      try {
        // if ~/.keystore cannot be loaded, then try to load jre/lib/security/cacerts
        loaded = loadKeyStoreFile(keyStore, javaKeyStore, defaultPassphrase);
      } catch (Exception e) {
        LOG.info(notLoadedMessage, javaKeyStore.getAbsolutePath(), defaultPassphrase, e.getMessage());
      }
    }
    if (!loaded){
      // if none of the keystore files cannot be loaded, then create an empty keyStore instance
      keyStore.load(null);
    }
  }
<commit_msg>Differentiate between default keystore and truststore files<commit_after>/**
 * Copyright (C) 2015 Red Hat, Inc.
 *
 * 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.fabric8.kubernetes.client.internal;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
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.security.spec.RSAPrivateCrtKeySpec;
import okio.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CertUtils {

  private static final Logger LOG = LoggerFactory.getLogger(CertUtils.class);

  public static InputStream getInputStreamFromDataOrFile(String data, String file) throws FileNotFoundException {
    if (data != null) {
      byte[] bytes = null;
      ByteString decoded = ByteString.decodeBase64(data);
      if (decoded != null) {
          bytes = decoded.toByteArray();
      } else {
          bytes = data.getBytes();
      }

      return new ByteArrayInputStream(bytes);
    }
    if (file != null) {
      return new FileInputStream(file);
    }
    return null;
  }

  public static KeyStore createTrustStore(String caCertData, String caCertFile) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) {
      return createTrustStore(pemInputStream);
    }
  }

  public static KeyStore createTrustStore(InputStream pemInputStream) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    KeyStore trustStore = KeyStore.getInstance("JKS");
    loadDefaultTrustStoreFile(trustStore);

    while (pemInputStream.available() > 0) {
      CertificateFactory certFactory = CertificateFactory.getInstance("X509");
      X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);

      String alias = cert.getSubjectX500Principal().getName();
      trustStore.setCertificateEntry(alias, cert);
    }
    return trustStore;
  }

  public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
      CertificateFactory certFactory = CertificateFactory.getInstance("X509");
      X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

      byte[] keyBytes = decodePem(keyInputStream);

      PrivateKey privateKey;

      KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo);
      try {
        // First let's try PKCS8
        privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
      } catch (InvalidKeySpecException e) {
        // Otherwise try PKCS8
        RSAPrivateCrtKeySpec keySpec = PKCS1Util.decodePKCS1(keyBytes);
        privateKey = keyFactory.generatePrivate(keySpec);
      }

      KeyStore keyStore = KeyStore.getInstance("JKS");
      loadDefaultKeyStoreFile(keyStore);

      String alias = cert.getSubjectX500Principal().getName();
      keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[]{cert});

      return keyStore;
  }

  private static void loadDefaultTrustStoreFile(KeyStore keyStore)
    throws CertificateException, NoSuchAlgorithmException, IOException {

    File javaKeyStore =
      new File(System.getProperty("java.home"), "lib" + File.separator + "security" + File.separator + "cacerts");
    char[] defaultPassphrase = "<PASSWORD>".toCharArray();

    if (!loadDefaultKeyStoreFiles(keyStore, javaKeyStore, defaultPassphrase)) {
      keyStore.load(null);
    }
  }

  private static void loadDefaultKeyStoreFile(KeyStore keyStore)
    throws CertificateException, NoSuchAlgorithmException, IOException {

    File defaultKeyStore = new File(System.getProperty("user.home"), ".keystore");
    char[] defaultPassphrase = "<PASSWORD>".toCharArray();

    if (!loadDefaultKeyStoreFiles(keyStore, defaultKeyStore, defaultPassphrase)) {
      keyStore.load(null);
    }
  }

  private static boolean loadDefaultKeyStoreFiles(KeyStore keyStore, File fileToLoad, char[] passphrase)
    throws CertificateException, NoSuchAlgorithmException, IOException {

    String notLoadedMessage = "There is a problem with reading default keystore file %s with the default passphrase %s "
      + "- the keystore file won't be loaded. The reason is: %s";

    try {
      return loadKeyStoreFile(keyStore, fileToLoad, passphrase);
    } catch (Exception e) {
      LOG.info(notLoadedMessage, fileToLoad, passphrase, e.getMessage());
      return false;
    }
  }

{'fraction_non_alphanumeric': 0.08803710510195152, 'fraction_numerical': 0.008226131093025292, 'mean_word_length': 4.370300751879699, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6893149', 'n_tokens_mistral': 3102, 'n_tokens_neox': 2959, 'n_words': 812}