package com.jianshui.common.utils.encrypt;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * 功能描述
 * 加密常用类
 */
public class AisinoInvoiceEncryptUtil {

    private static final String ALGORITHM = "AES/GCM/NoPadding";
    private static final int IV_LENGTH = 12; // 初始化向量长度为12字节（96位）
    private static final int TAG_LENGTH = 16; // GCM模式的认证标签长度为16字节

    /** 加密共有两种方法 一、DES 二、AES*/

    /** 一、DES加密方法*/
    public static String encrypt(String xmlStr, String mkey) {
        byte[] encrypt = {};

        try {
            // 取需要加密内容的utf-8编码。
            if (xmlStr != null) {
                encrypt = xmlStr.getBytes("utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 取MD5Hash码，并组合加密数组
        byte[] md5Hasn = null;
        try {
            md5Hasn = MD5Hash(encrypt, 0, encrypt.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 组合消息体
        byte[] totalByte = addMD5(md5Hasn, encrypt);

        // 取密钥和偏转向量
        byte[] key = new byte[8];
        byte[] iv = new byte[8];
        getKeyIV(mkey, key, iv);
        SecretKeySpec deskey = new SecretKeySpec(key, "DES");
        IvParameterSpec ivParam = new IvParameterSpec(iv);

        // 使用DES算法使用加密消息体
        byte[] temp = null;
        try {
            temp = DES_CBC_Encrypt(totalByte, deskey, ivParam);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用Base64加密后返回
        return new BASE64Encoder().encode(temp);
    }


    /** DES加密接口*/
    public static byte[] DES_CBC_Encrypt(byte[] sourceBuf,
                                         SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {
        byte[] cipherByte;
        // 使用DES对称加密算法的CBC模式加密
        Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");

        encrypt.init(Cipher.ENCRYPT_MODE, deskey, ivParam);

        cipherByte = encrypt.doFinal(sourceBuf, 0, sourceBuf.length);
        // 返回加密后的字节数组
        return cipherByte;
    }

    /** AES 加密接口*/
    public static byte[] AES_Encrypt(byte[] sourceBuf,
                                         byte[] keys, IvParameterSpec ivParam) throws Exception {
        byte[] iv = keys;

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(TAG_LENGTH * 8, iv);
        SecretKeySpec keySpec = new SecretKeySpec(keys, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);

        byte[] ciphertext = cipher.doFinal(sourceBuf);

        byte[] result = new byte[IV_LENGTH + ciphertext.length];
        System.arraycopy(iv, 0, result, 0, IV_LENGTH);
        System.arraycopy(ciphertext, 0, result, IV_LENGTH, ciphertext.length);

       return result;
    }

    /** 转为十六进制字符串*/
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }


    /** 二、AES加密方法*/
    public static String encryptAES(String xmlStr, String mkey) {
        byte[] encrypt = {};

        // 取需要加密内容的utf-8编码。
        if (xmlStr != null) {
            encrypt = xmlStr.getBytes(StandardCharsets.UTF_8);
        }
        // 取MD5Hash码，并组合加密数组
        byte[] md5Hasn = null;
        try {
            md5Hasn = MD5Hash(encrypt, 0, encrypt.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 组合消息体
        byte[] totalByte = addMD5(md5Hasn, encrypt);

        // 取密钥和偏转向量
        byte[] iv = new byte[16];
        IvParameterSpec ivParam = new IvParameterSpec(iv);

        // 使用DES算法使用加密消息体
        byte[] temp = null;
        try {
            temp = AES_Encrypt(totalByte, mkey.getBytes(), ivParam);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 使用Base64加密后返回
        return bytesToHex(temp);
    }


    public static byte[] MD5Hash(byte[] buf, int offset, int length)
            throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(buf, offset, length);
        return md.digest();
    }


    public static byte[] addMD5(byte[] md5Byte, byte[] bodyByte) {
        int length = bodyByte.length + md5Byte.length;
        byte[] resutlByte = new byte[length];

        // 前16位放MD5Hash码
        for (int i = 0; i < length; i++) {
            if (i < md5Byte.length) {
                resutlByte[i] = md5Byte[i];
            } else {
                resutlByte[i] = bodyByte[i - md5Byte.length];
            }
        }

        return resutlByte;
    }


    public static void getKeyIV(String encryptKey, byte[] key, byte[] iv) {
        // 密钥Base64解密
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = null;
        try {
            buf = decoder.decodeBuffer(encryptKey);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 前8位为key
        int i;
        for (i = 0; i < key.length; i++) {
            key[i] = buf[i];
        }
        // 后8位为iv向量
        for (i = 0; i < iv.length; i++) {
            iv[i] = buf[i + 8];
        }
    }


    public static void main(String[] args) throws Exception {

        // 生成一个随机的AES密钥
        SecretKey secretKey = SecureUtil.generateKey("AES");
        // 转换为16进制字符串
        String keyHex = HexUtil.encodeHexStr(secretKey.getEncoded());
        System.out.println("AES密钥：");
        System.out.println(keyHex);

        String str = "{\"terminalNumber\":\"\",\"orderno\":\"fcd3a67d-6a6e-f714-0790-c705db41403d\",\"sellerBank\":null,\"checker\":\"\",\"saleaddress\":null,\"payee\":\"\",\"hsbz\":\"2\",\"kjlx\":\"\",\"saleaccount\":null,\"qdbz\":\"0\",\"ext\":{\"sfhqsyed\":false},\"xsfnsrsbh\":\"92370214MACAAEK16E\",\"xsflxdh\":null,\"cpybz\":\"0\",\"fjh\":\"\",\"tax\":\"0.3\",\"dkbz\":\"0\",\"phone\":\"\",\"dqbm\":\"\",\"xsfyhzh\":null,\"jshj\":\"10.3\",\"tsfs\":\"2\",\"detail\":[{\"fphxz\":\"0\",\"lslbs\":\"\",\"unit\":\"\",\"hsbz\":\"0\",\"taxrate\":\"0.03\",\"yhzcbs\":\"0\",\"zzstsgl\":\"\",\"price\":\"\",\"num\":\"\",\"goodsname\":\"维修费\",\"spbm\":\"202\",\"spec\":\"\",\"taxfreeamt\":\"10.00\",\"tax\":\"0.30\",\"taxamt\":\"10.30\"}],\"taxamt\":\"10\",\"saletaxnum\":\"92370214MACAAEK16E\",\"sellerName\":\"城阳区兴顺通制冷设备维修服务部\",\"billInfono\":\"\",\"xsfkhh\":null,\"fpqqlsh\":\"fcd3a67d-6a6e-f714-0790-c705db41403d\",\"qdxmmc\":\"\",\"gfxxconfirm\":\"\",\"invoiceLine\":\"82\",\"serviceId\":\"lzfpkj\",\"email\":\"\",\"salephone\":null,\"address\":\"北京市-西城区-市岱岳区山口镇油坊村 80965631\",\"fpdm\":\"\",\"bsrysfzjhm\":\"370882198408212815\",\"kptype\":\"1\",\"message\":\"\",\"clerk\":\"鹿旭\",\"async\":\"true\",\"xsfmc\":\"城阳区兴顺通制冷设备维修服务部\",\"xsfdz\":null,\"taxnum\":\"91370112MA3C5P3322\",\"jqbh\":\"370882198408212815\",\"account\":\"中国建设银行济南市泉城支行 376010100101019236\",\"invoicedate\":\"2024-01-30\",\"buyername\":\"高速公路有限公司\",\"fphm\":\"\"}";
        String key = "S1jIlJRLXBNtIFihvQ0VPw==";
        System.out.println(encryptAES(str,key));


    }
}











