package com.palacesun.masking.tools;

import com.palacesun.engine.gateway.EncryptionGatewayManager;
import com.palacesun.masking.adapter.StringUtils;
import com.palacesun.masking.vo.Columninfo;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Properties;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jcajce.spec.AEADParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

public class AESUtil {
   private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
   private static final byte[] iv = new byte[]{-80, 104, -85, -96, -31, -90, 1, 120, 35, 121, 26, 41};
   public static final int DEF_KEY_SIZE = 128;
   private static final String ALGORITHM_NAME = "AES";
   private static final String ENCODING = "UTF-8";
   private static Properties properties;
   private static String ENCRYPT_LIKE_SPLIT = EncryptionGatewayManager.getParameterValue("encryption.like.split");
   private static String ENCRYPT_LABEL = EncryptionGatewayManager.getParameterValue("encryption.label");
   private static final String ENCRYPT_LIKE_OPEN = "1";

   public static String encryptEcb(String encryptKey, String paramStr, String isLike, String keepfirst, String encdigit, String twoindex, String... encryptMode) throws Exception {
      byte[] keyBytes = Hex.decode(encryptKey);
      String prefix = null;
      String enc = paramStr;
      String suffix = null;
      if (!StringUtils.isBlank(keepfirst)) {
         if (!"0".equals(keepfirst) && !"1".equals(keepfirst)) {
            if (!"2".equals(keepfirst)) {
               return paramStr;
            }

            int first = 0;
            if (StringUtils.isNotBlank(encdigit)) {
               first = Integer.parseInt(encdigit);
            }

            int last = 0;
            if (StringUtils.isNotBlank(twoindex)) {
               last = Integer.parseInt(twoindex);
            }

            if (first + last >= paramStr.length() || first >= paramStr.length() || last >= paramStr.length()) {
               return paramStr;
            }

            prefix = paramStr.substring(0, first);
            enc = paramStr.substring(first, paramStr.length() - last);
            suffix = paramStr.substring(paramStr.length() - last);
         } else if (StringUtils.isNotBlank(encdigit)) {
            if (Integer.parseInt(encdigit) >= paramStr.length()) {
               return paramStr;
            }

            if (Integer.parseInt(encdigit) != 0) {
               if ("0".equals(keepfirst)) {
                  prefix = paramStr.substring(0, Integer.parseInt(encdigit));
                  enc = paramStr.substring(Integer.parseInt(encdigit));
               } else if ("1".equals(keepfirst)) {
                  enc = paramStr.substring(0, paramStr.length() - Integer.parseInt(encdigit));
                  suffix = paramStr.substring(paramStr.length() - Integer.parseInt(encdigit));
               }
            }
         }
      }

      String encResult;
      if ("1".equals(isLike)) {
         StringBuilder sb = new StringBuilder();

         for(int i = 0; i < enc.length(); ++i) {
            char c = enc.charAt(i);
            byte[] srcData = (c + "").getBytes("UTF-8");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(1, keySpec, new AEADParameterSpec(iv, 128));
            byte[] ciphertext = cipher.doFinal(srcData);
            String s = Hex.toHexString(ciphertext);
            sb.append(s).append(ENCRYPT_LIKE_SPLIT);
         }

         encResult = sb.deleteCharAt(sb.length() - 1).toString();
      } else {
         SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
         Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
         cipher.init(1, keySpec, new AEADParameterSpec(iv, 128));
         byte[] ciphertext = cipher.doFinal(enc.getBytes("UTF-8"));
         encResult = Hex.toHexString(ciphertext);
      }

      if ("0".equals(keepfirst) && null != prefix) {
         encResult = prefix + encResult;
      } else if ("1".equals(keepfirst) && null != suffix) {
         encResult = encResult + suffix;
      } else if ("2".equals(keepfirst)) {
         if (null != prefix) {
            encResult = prefix + encResult;
         }

         if (null != suffix) {
            encResult = encResult + suffix;
         }
      }

      return encResult;
   }

   public static String decryptEcb(String decryptKey, String paramStr, String isLike, String keepfirst, String encdigit, String twoindex, String... encryptMode) throws Exception {
      byte[] keyBytes = Hex.decode(decryptKey);
      String prefix = null;
      String enc = paramStr;
      String suffix = null;
      if (!StringUtils.isBlank(keepfirst)) {
         if (!"0".equals(keepfirst) && !"1".equals(keepfirst)) {
            if ("2".equals(keepfirst)) {
               int first = 0;
               if (StringUtils.isNotBlank(encdigit)) {
                  first = Integer.parseInt(encdigit);
               }

               int last = 0;
               if (StringUtils.isNotBlank(twoindex)) {
                  last = Integer.parseInt(twoindex);
               }

               if (first + last >= paramStr.length() || first >= paramStr.length() || last >= paramStr.length()) {
                  return paramStr;
               }

               prefix = paramStr.substring(0, first);
               enc = paramStr.substring(first, paramStr.length() - last);
               suffix = paramStr.substring(paramStr.length() - last);
            }
         } else if (StringUtils.isNotBlank(encdigit)) {
            if (Integer.parseInt(encdigit) >= paramStr.length()) {
               return paramStr;
            }

            if (Integer.parseInt(encdigit) != 0) {
               if ("0".equals(keepfirst)) {
                  prefix = paramStr.substring(0, Integer.parseInt(encdigit));
                  enc = paramStr.substring(Integer.parseInt(encdigit));
               } else if ("1".equals(keepfirst)) {
                  enc = paramStr.substring(0, paramStr.length() - Integer.parseInt(encdigit));
                  suffix = paramStr.substring(paramStr.length() - Integer.parseInt(encdigit));
               }
            }
         }
      }

      String encResult;
      if ("1".equals(isLike)) {
         StringBuilder sb = new StringBuilder();
         String[] split = enc.split(ENCRYPT_LIKE_SPLIT);

         for(String s : split) {
            try {
               byte[] encryptBytes = Hex.decode(s);
               SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
               Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
               cipher.init(2, keySpec, new AEADParameterSpec(iv, 128));
               byte[] decryptedData = cipher.doFinal(encryptBytes);
               sb.append(new String(decryptedData, "UTF-8"));
            } catch (Exception var22) {
               return ENCRYPT_LABEL + paramStr;
            }
         }

         encResult = sb.toString();
      } else {
         byte[] encryptBytes = Hex.decode(enc);
         SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
         Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
         cipher.init(2, keySpec, new AEADParameterSpec(iv, 128));
         byte[] decryptedData = cipher.doFinal(encryptBytes);
         encResult = new String(decryptedData, "UTF-8");
      }

      if ("0".equals(keepfirst) && null != prefix) {
         encResult = prefix + encResult;
      } else if ("1".equals(keepfirst) && null != suffix) {
         encResult = encResult + suffix;
      } else if ("2".equals(keepfirst)) {
         if (null != prefix) {
            encResult = prefix + encResult;
         }

         if (null != suffix) {
            encResult = encResult + suffix;
         }
      }

      return encResult;
   }

   public static String generaKey() throws Exception {
      return Hex.toHexString(generaKey(128));
   }

   public static byte[] generaKey(int keySize) throws Exception {
      KeyGenerator kg = KeyGenerator.getInstance("AES");
      kg.init(keySize, new SecureRandom());
      return kg.generateKey().getEncoded();
   }

   public static void main(String[] args) throws Exception {
      String key = generaKey();
      System.out.println(key);
      String data = "~这是yuanshi的明文xinxi在这里呢,1。";
      System.out.println(data);
      String encrypt = encryptEcb(key, data, "1", "0", "3", "0");
      System.out.println(encrypt);
      String decrypt = decryptEcb(key, encrypt, "1", "0", "3", "0");
      System.out.println(decrypt);
      System.out.println(data.equals(decrypt));
      encrypt = ReflectUtil.engine("AES", data, key, "1", "0", "3", "0", true, (Columninfo)null);
      System.out.println(encrypt);
      decrypt = ReflectUtil.engine("AES", encrypt, key, "1", "0", "3", "0", false, (Columninfo)null);
      System.out.println(decrypt);
      System.out.println(data.equals(decrypt));
   }

   static {
      Security.addProvider(new BouncyCastleProvider());
   }
}
