package com.chenyang.nse.bussiness.thkms.service.impl;

import com.chenyang.nse.bussiness.service.key.KeyManagerService;
import com.chenyang.nse.bussiness.thkms.ThKmsException;
import com.chenyang.nse.bussiness.thkms.model.ThKmsCert;
import com.chenyang.nse.bussiness.thkms.model.ThKmsProperties;
import com.chenyang.nse.bussiness.thkms.service.ThKmsService;
import com.chenyang.nse.bussiness.thkms.util.Guid;
import com.chenyang.nse.bussiness.thkms.util.gmhelper.SM2Util;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.bouncycastle.crypto.engines.SM2Engine.Mode;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

@Service
public class ThKmsServiceImpl implements ThKmsService {
   protected Logger logger = LoggerFactory.getLogger(this.getClass());
   @Autowired
   protected HttpClient httpClient;
   @Autowired
   protected ThKmsProperties thKmsProperties;
   @Autowired
   protected KeyManagerService keyManagerService;
   protected Gson gson = new Gson();

   public String createKey() {
      Map<String, String> map = this.keyManagerService.showKeyParams("6");
      if (StringUtils.isEmpty((CharSequence)map.get("appid"))) {
         return "";
      } else {
         HttpPost httpPost = new HttpPost("/chiron/v1/system/createKey");

         String var12;
         try {
            httpPost.addHeader("Content-Type", "application/json");
            JsonObject json = new JsonObject();
            json.addProperty("transId", Guid.uid());
            json.addProperty("origin", "KMS");
            json.addProperty("appId", (String)map.get("appid"));
            json.addProperty("keyUsage", "ENCRYPT/DECRYPT");
            json.addProperty("keySpec", "SM4_128");
            json.addProperty("operateName", "ghca");
            String masterKeyBody = json.toString();
            this.logger.info(masterKeyBody);
            StringEntity entity = new StringEntity(masterKeyBody);
            httpPost.setEntity(entity);
            HttpHost httpHost = new HttpHost((String)map.get("thhost"), Integer.parseInt((String)map.get("thport")), (String)map.get("protocol"));
            HttpResponse res = this.httpClient.execute(httpHost, httpPost);
            int code = res.getStatusLine().getStatusCode();
            this.logger.info("code={}", code);
            String body = StreamUtils.copyToString(res.getEntity().getContent(), StandardCharsets.UTF_8);
            this.logger.info(body);
            JsonObject bodyJson = (JsonObject)this.gson.fromJson(body, JsonObject.class);
            if (bodyJson.get("status").getAsInt() != 200) {
               throw new ThKmsException(body);
            }

            String keyId = bodyJson.get("data").getAsJsonObject().get("cmkMetadata").getAsJsonObject().get("keyId").getAsString();
            var12 = keyId;
         } catch (ThKmsException thkmse) {
            throw thkmse;
         } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            throw new ThKmsException(e.getMessage(), e);
         } finally {
            httpPost.releaseConnection();
         }

         return var12;
      }
   }

   public String generateDataKey() {
      Map<String, String> map = this.keyManagerService.showKeyParams("6");
      HttpPost httpPost = new HttpPost("/chiron/v1/system/generateDataKey");

      String var12;
      try {
         httpPost.addHeader("Content-Type", "application/json");
         JsonObject json = new JsonObject();
         json.addProperty("transId", Guid.uid());
         json.addProperty("appId", (String)map.get("appid"));
         json.addProperty("keySpec", "SM4_128");
         json.addProperty("keyId", (String)map.get("keyid"));
         json.addProperty("keyVersion", "1");
         json.addProperty("encCert", ThKmsCert.getInstance().getCertB64());
         String dataKeyBody = json.toString();
         this.logger.info(dataKeyBody);
         StringEntity entity = new StringEntity(dataKeyBody);
         httpPost.setEntity(entity);
         HttpHost httpHost = new HttpHost((String)map.get("thhost"), Integer.parseInt((String)map.get("thport")), (String)map.get("protocol"));
         HttpResponse res = this.httpClient.execute(httpHost, httpPost);
         int code = res.getStatusLine().getStatusCode();
         this.logger.info("code={}", code);
         String body = StreamUtils.copyToString(res.getEntity().getContent(), StandardCharsets.UTF_8);
         this.logger.info(body);
         JsonObject bodyJson = (JsonObject)this.gson.fromJson(body, JsonObject.class);
         if (bodyJson.get("status").getAsInt() != 200) {
            throw new ThKmsException(body);
         }

         String cipherDataKey = bodyJson.get("data").getAsJsonObject().get("dkMetadata").getAsJsonObject().get("cipherDataKey").getAsString();
         var12 = cipherDataKey;
      } catch (ThKmsException thkmse) {
         throw thkmse;
      } catch (Exception e) {
         this.logger.error(e.getMessage(), e);
         throw new ThKmsException(e.getMessage(), e);
      } finally {
         httpPost.releaseConnection();
      }

      return var12;
   }

   public String decryptDataKey(String cipherDataKey) {
      if (StringUtils.isEmpty(cipherDataKey)) {
         return "";
      } else {
         Map<String, String> map = this.keyManagerService.showKeyParams("6");
         HttpPost httpPost = new HttpPost("/chiron/v1/system/decryptDataKeyByPubKey");

         String var17;
         try {
            httpPost.addHeader("Content-Type", "application/json");
            JsonObject json = new JsonObject();
            json.addProperty("transId", Guid.uid());
            json.addProperty("appId", (String)map.get("appid"));
            json.addProperty("keySpec", "SM4_128");
            json.addProperty("keyId", (String)map.get("keyid"));
            json.addProperty("keyVersion", "1");
            json.addProperty("cipherTextBlob", cipherDataKey);
            json.addProperty("encCert", ThKmsCert.getInstance().getCertB64());
            String dataKeyBody = json.toString();
            this.logger.info(dataKeyBody);
            StringEntity entity = new StringEntity(dataKeyBody);
            httpPost.setEntity(entity);
            HttpHost httpHost = new HttpHost((String)map.get("thhost"), Integer.parseInt((String)map.get("thport")), (String)map.get("protocol"));
            HttpResponse res = this.httpClient.execute(httpHost, httpPost);
            int code = res.getStatusLine().getStatusCode();
            this.logger.info("code={}", code);
            String body = StreamUtils.copyToString(res.getEntity().getContent(), StandardCharsets.UTF_8);
            this.logger.info(body);
            JsonObject bodyJson = (JsonObject)this.gson.fromJson(body, JsonObject.class);
            if (bodyJson.get("status").getAsInt() != 200) {
               throw new ThKmsException(body);
            }

            String cipherDataKeyByPubKey = bodyJson.get("data").getAsJsonObject().get("dkMetadata").getAsJsonObject().get("cipherDataKeyByPubKey").getAsString();
            byte[] cipherDataKeyBytes = Base64.getDecoder().decode(cipherDataKeyByPubKey);
            byte[] cipherDataKeyBytes132 = SM2Util.decodeDERSM2Cipher(Mode.C1C3C2, cipherDataKeyBytes);
            byte[] plainDataKeyBytes = SM2Util.decrypt(Mode.C1C3C2, (BCECPrivateKey)ThKmsCert.getInstance().getPrivateKey(), cipherDataKeyBytes132);
            String sm4Key = new String(Hex.encodeHex(plainDataKeyBytes, false));
            var17 = sm4Key;
         } catch (ThKmsException thkmse) {
            throw thkmse;
         } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            throw new ThKmsException(e.getMessage(), e);
         } finally {
            httpPost.releaseConnection();
         }

         return var17;
      }
   }
}
