package com.oguerreiro.resilient.config;

import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class CertificateLoader {

  public static X509Certificate loadCertificate(String filePath) throws Exception {
    CertificateFactory factory = CertificateFactory
        .getInstance(
            "X.509");
    try (FileInputStream fis = new FileInputStream(filePath)) {
      return (X509Certificate) factory
          .generateCertificate(
              fis);
    }
  }

  public static PrivateKey loadPrivateKey(String filePath) throws Exception {
    byte[] keyBytes = java.nio.file.Files
        .readAllBytes(
            java.nio.file.Paths
                .get(
                    filePath));
    String keyPEM = new String(keyBytes)
        .replace(
            "-----BEGIN PRIVATE KEY-----",
            "")
        .replace(
            "-----END PRIVATE KEY-----",
            "")
        .replaceAll(
            "\\s",
            "");
    byte[] decodedKey = Base64
        .getDecoder()
        .decode(
            keyPEM);

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
    KeyFactory keyFactory = KeyFactory
        .getInstance(
            "RSA");
    return keyFactory
        .generatePrivate(
            keySpec);
  }
}
