package com.chenyang.nse.bussiness.tools.encryption;

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.Properties;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class DESUtil {
   private static final String ENCODING = "UTF-8";
   public static final String ALGORITHM_NAME = "DES";
   public static final int DEFAULT_KEY_SIZE = 56;
   private static Properties properties;
   private static String ENCRYPT_LIKE_SPLIT;
   private static final String ENCRYPT_LIKE_OPEN = "1";

   public static String generateKey() throws Exception {
      return new String(Hex.encodeHex(generateKey(56), false));
   }

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

   public static String encryptEcb(String hexKey, String paramStr, String isLike, String keepfirst, String encdigit, String twoindex) throws DecoderException, NoSuchPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, BadPaddingException, InvalidKeyException {
      try {
         byte[] keyData = Hex.decodeHex(hexKey);
         DESKeySpec desKey = new DESKeySpec(keyData);
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
         SecretKey secretKey = keyFactory.generateSecret(desKey);
         Cipher cipher = Cipher.getInstance("DES");
         cipher.init(1, secretKey, new SecureRandom());
         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");
               byte[] b = cipher.doFinal(srcData);
               String s = Hex.encodeHexString(b);
               sb.append(s).append(ENCRYPT_LIKE_SPLIT);
            }

            encResult = sb.deleteCharAt(sb.length() - 1).toString();
         } else {
            byte[] cipherArray = cipher.doFinal(enc.getBytes("UTF-8"));
            encResult = Hex.encodeHexString(cipherArray);
         }

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

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

            return encResult;
         }
      } catch (Throwable e) {
         e.printStackTrace();
         throw e;
      }
   }

   public static String decryptEcb(String hexKey, String paramStr, String isLike, String keepfirst, String encdigit, String twoindex) throws DecoderException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidKeySpecException, BadPaddingException, InvalidKeyException {
      try {
         byte[] keyData = Hex.decodeHex(hexKey);
         DESKeySpec desKey = new DESKeySpec(keyData);
         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
         SecretKey secretkey = keyFactory.generateSecret(desKey);
         Cipher cipher = Cipher.getInstance("DES");
         cipher.init(2, secretkey, new SecureRandom());
         String prefix = null;
         String enc = paramStr;
         String suffix = null;
         if (!StringUtils.isBlank(encdigit)) {
            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)) {
                     suffix = paramStr.substring(paramStr.length() - Integer.parseInt(encdigit));
                     enc = paramStr.substring(0, 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[] cipherData = Hex.decodeHex(s);
                  byte[] decryptBytes = cipher.doFinal(cipherData);
                  sb.append(new String(decryptBytes));
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            encResult = sb.toString();
         } else {
            byte[] cipherData = Hex.decodeHex(enc);
            encResult = new String(cipher.doFinal(cipherData));
         }

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

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

            return encResult;
         }
      } catch (Throwable e) {
         e.printStackTrace();
         throw e;
      }
   }

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

   static {
      try {
         properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
         ENCRYPT_LIKE_SPLIT = properties.get("encryption.like.split").toString();
      } catch (IOException e) {
         e.printStackTrace();
      }

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