package com.oguerreiro.resilient.security.saml2;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
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;

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

@Component
public class Saml2CredentialLoader {

  private final ResourceLoader resourceLoader;

  public Saml2CredentialLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader;
  }

  public X509Certificate loadCertificate(String location) throws Exception {
    Resource resource = resourceLoader.getResource(location);
    try (InputStream is = resource.getInputStream()) {
      CertificateFactory factory = CertificateFactory.getInstance("X.509");
      return (X509Certificate) factory.generateCertificate(is);
    }
  }

  public PrivateKey loadPrivateKey(String location) throws Exception {
    Resource resource = resourceLoader.getResource(location);
    String key = new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
    key = key.replaceAll("-----BEGIN (.*)-----", "").replaceAll("-----END (.*)-----", "").replaceAll("\\s", "");

    byte[] decoded = Base64.getDecoder().decode(key);
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
    return KeyFactory.getInstance("RSA").generatePrivate(spec);
  }
}
