package com.chenyang.nse.bussiness.thkms.runner;

import com.chenyang.nse.bussiness.service.key.impl.KeyManagerServiceImpl;
import com.chenyang.nse.bussiness.thkms.model.ThKmsCert;
import com.chenyang.nse.bussiness.tools.spring.SpringUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Map;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

@Component
public class ThKmsCertRunner {
   protected Logger logger = LoggerFactory.getLogger(this.getClass());

   public void run(ApplicationArguments args) throws Exception {
      try {
         try {
            Map<String, String> map = ((KeyManagerServiceImpl)SpringUtil.getBean(KeyManagerServiceImpl.class)).showKeyParams("6");
            String keyPath = (String)map.get("keystoredir");
            keyPath = (keyPath.endsWith(File.separator) ? keyPath : keyPath + File.separator) + "sm2pri.pkcs8.der";
            InputStream is = new FileInputStream(keyPath);
            byte[] priBytes = StreamUtils.copyToByteArray(is);
            BouncyCastleProvider provider = new BouncyCastleProvider();
            KeyFactory keyFactory = KeyFactory.getInstance("EC", provider);
            KeySpec keySpec = new PKCS8EncodedKeySpec(priBytes);
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            this.logger.info(privateKey.toString());
            X509Certificate cert = null;
            String pubPath = (String)map.get("truststoredir");
            pubPath = (pubPath.endsWith(File.separator) ? pubPath : pubPath + File.separator) + "sm2pub.cer";
            InputStream in = new FileInputStream(pubPath);
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509", provider);
            cert = (X509Certificate)certFactory.generateCertificate(in);
            this.logger.info(cert.toString());
            byte[] certBytes = cert.getEncoded();
            String certB64 = Base64.getEncoder().encodeToString(certBytes);
            this.logger.info(certB64);
            ThKmsCert.init(privateKey, cert, certB64);
         } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
         }

      } finally {
         ;
      }
   }
}
