// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.athenz.impl;

import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.ExtensionsGenerator;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.bouncycastle.util.io.pem.PemObject;

import javax.security.auth.x500.X500Principal;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

/**
 * @author bjorncs
 */
class CryptoUtils {

    private CryptoUtils() {}

    static KeyPair createKeyPair() {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            return kpg.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    static PKCS10CertificationRequest createCSR(String identityDomain,
                                                String identityService,
                                                String dnsSuffix,
                                                String providerUniqueId,
                                                KeyPair keyPair) {
        try {
            // Add SAN dnsname <service>.<domain-with-dashes>.<provider-dnsname-suffix>
            // and SAN dnsname <provider-unique-instance-id>.instanceid.athenz.<provider-dnsname-suffix>
            GeneralNames subjectAltNames = new GeneralNames(new GeneralName[]{
                    new GeneralName(GeneralName.dNSName, String.format("%s.%s.%s",
                                                                       identityService,
                                                                       identityDomain.replace(".", "-"),
                                                                       dnsSuffix)),
                    new GeneralName(GeneralName.dNSName, String.format("%s.instanceid.athenz.%s",
                                                                       providerUniqueId,
                                                                       dnsSuffix))
            });

            ExtensionsGenerator extGen = new ExtensionsGenerator();
            extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);

            X500Principal subject = new X500Principal(
                    String.format("CN=%s.%s", identityDomain, identityService));

            PKCS10CertificationRequestBuilder requestBuilder =
                    new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic());
            requestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
            return requestBuilder.build(new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()));
        } catch (OperatorCreationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static String toPem(PKCS10CertificationRequest csr) {
        try (StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
            pemWriter.writeObject(new PemObject("CERTIFICATE REQUEST", csr.getEncoded()));
            pemWriter.flush();
            return stringWriter.toString();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static X509Certificate parseCertificate(String pemEncodedCertificate) {
        try (PEMParser parser = new PEMParser(new StringReader(pemEncodedCertificate))) {
            Object pemObject = parser.readObject();
            if (!(pemObject instanceof X509Certificate)) {
                throw new IllegalArgumentException("Expeceted X509Certificate instance, got " + pemObject);
            }
            return (X509Certificate) pemObject;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

@@ -412,16 +412,192 @@
 lNames;%0A
+import org.bouncycastle.cert.X509CertificateHolder;%0Aimport org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;%0Aimport org.bouncycastle.jce.provider.BouncyCastleProvider;%0A
 import o
@@ -1330,32 +1330,80 @@
 rithmException;%0A
+import java.security.cert.CertificateException;%0A
 import java.secu
@@ -1478,16 +1478,114 @@
 tils %7B%0A%0A
+    private static final BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();%0A%0A
     priv
@@ -4705,10 +4705,8 @@
  if 
-(!
 (pem
@@ -4739,17 +4739,16 @@
 ificate)
-)
  %7B%0A     
@@ -4762,150 +4762,405 @@
     
-throw new IllegalArgumentException(%22Expeceted X509Certificate instance, got %22 + pemObject);%0A            %7D%0A            return (X509Certificate)
+return (X509Certificate) pemObject;%0A            %7D%0A            if (pemObject instanceof X509CertificateHolder) %7B%0A                return new JcaX509CertificateConverter()%0A                        .setProvider(bouncyCastleProvider)%0A                        .getCertificate((X509CertificateHolder) pemObject);%0A            %7D%0A            throw new IllegalArgumentException(%22Invalid type of PEM object: %22 +
  pem
@@ -5157,32 +5157,33 @@
 t: %22 + pemObject
+)
 ;%0A        %7D catc
@@ -5241,32 +5241,118 @@
 IOException(e);%0A
+        %7D catch (CertificateException e) %7B%0A            throw new RuntimeException(e);%0A
         %7D%0A    %7D%0A

Handle X509CertificateHolder instances when parsing certificate PEM