package com.cusc.nirvana.user.rnr.fp.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Description AESUtil function
 *
 * @author zx
 * @version 1.0
 * @date 2022-06-16 10:29
 */
public class AESUtil {
    private static final Logger log = LoggerFactory.getLogger(AESUtil.class);
    private static final String ALGORITHM = "AES";
    private static final String PATTERN = "AES/ECB/PKCS5Padding";
    private static final int CACHE_SIZE = 1024;

    public AESUtil() {
    }

    public static byte[] encrypt(byte[] data, String key) throws Exception {
        Key k = toKey(MD5(key));
        byte[] raw = k.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(1, secretKeySpec);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] data, String key) throws Exception {
        Key k = toKey(MD5(key));
        byte[] raw = k.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(2, secretKeySpec);
        return cipher.doFinal(data);
    }

    public static File encryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
        File sourceFile = new File(sourceFilePath);
        File destFile = new File(destFilePath);
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            destFile.createNewFile();
            InputStream in = new FileInputStream(sourceFile);
            OutputStream out = new FileOutputStream(destFile);
            Key k = toKey(MD5(key));
            byte[] raw = k.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(1, secretKeySpec);
            CipherInputStream cin = new CipherInputStream(in, cipher);
            byte[] cache = new byte[1024];
            boolean var13 = false;

            int nRead;
            while ((nRead = cin.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }

            out.close();
            cin.close();
            in.close();
            return destFile;
        } else {
            log.error("文件[{}]不存在！", sourceFilePath);
            return null;
        }
    }

    public static void decryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
        File sourceFile = new File(sourceFilePath);
        File destFile = new File(destFilePath);
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            destFile.createNewFile();
            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(destFile);
            Key k = toKey(MD5(key));
            byte[] raw = k.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(2, secretKeySpec);
            CipherOutputStream cout = new CipherOutputStream(out, cipher);
            byte[] cache = new byte[1024];
            boolean var13 = false;

            int nRead;
            while ((nRead = in.read(cache)) != -1) {
                cout.write(cache, 0, nRead);
                cout.flush();
            }

            cout.close();
            out.close();
            in.close();
        }

    }

    private static Key toKey(byte[] key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        return secretKey;
    }

    public static byte[] MD5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            return md.digest();
        } catch (NoSuchAlgorithmException var2) {
            log.error("MD5加密失败，异常信息:", var2);
            return null;
        }
    }

    public static String encryptStr(String str,String key) {
        if (StringUtils.isEmpty(str)){
            return str;
        }
        AES aes = SecureUtil.aes(AESUtil.MD5(key));
        String decryptStr = aes.encryptHex(str, CharsetUtil.CHARSET_UTF_8);
        log.info("decode content: {}", decryptStr);
        return decryptStr;
    }

    public static void main(String[] args) throws Exception {
        String type = args[0];
        System.out.println("操作类型：" + type);
        String key = args[1];
        System.out.println("密钥字符串：" + key);
        String sourcePath = args[2];
        System.out.println("源文件路径：" + sourcePath);
        String destPath = args[3];
        System.out.println("目标文件路径：" + destPath);
        if (args.length != 4) {
            System.out.println("参数错误，参数格式：操作类型 密钥字符串 源文件路径 目标文件路径");
        }

        if (type.equals("e")) {
            System.out.println("开始加密...");
            encryptFile(key, sourcePath, destPath);
            System.out.println("加密完成，目标文件路径：" + destPath);
        } else if (type.equals("d")) {
            System.out.println("开始解密...");
            decryptFile(key, sourcePath, destPath);
            System.out.println("解密完成，目标文件路径：" + destPath);
        } else {
            System.out.println("参数错误，参数格式：操作类型 密钥字符串 源文件路径 目标文件路径");
        }

    }
}
