package com.friday.tooldriver.utils;
import com.google.gson.Gson;
import com.friday.operation.api.keepalive.constant.taieoc.TaieOcConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class SM2Utils {

/*    @Value("93f2eca686469186")
    private static String SM4_KEY;
    @Value("00dc5fd5e756731eb744c36b72f2500fee1d1f589b89345b4d5496af66ac2c4911")
    private static String privateKey;

    @Value("040fccb5debc513fa63c46dc50ab0e0ab070393a96f9f1d31176f7cf651bfb4449ef1bdc8e3cfa6194563381afaee17603019075112c2d70dc1ec8fefc1a7f920b")
    private static String publicKey;*/

    private static final Gson gson = new Gson();

    private static final String privateKey = "00dc5fd5e756731eb744c36b72f2500fee1d1f589b89345b4d5496af66ac2c4911";

    private static final String publicKey = "040fccb5debc513fa63c46dc50ab0e0ab070393a96f9f1d31176f7cf651bfb4449ef1bdc8e3cfa6194563381afaee17603019075112c2d70dc1ec8fefc1a7f920b";
    private static final String SM4_KEY = "93f2eca686469186";

    /**
     * 许可生成
     * @param licenseType
     * @param machineType
     * @param expireTime
     * @param reqMap
     * @return
     */

    public static String generateLicense(String licenseType, String machineType, String expireTime, Map<String, Object> reqMap) throws Exception {
        SM2Utils sm = new SM2Utils();


//          1.签名内容：｛签名内容｝＝｛许可类型＝机器类型=许可过期时间｝,设备ID由执行器上传，许可类型，许可有效期由平台填充,可根据需要扩充字段
        String reqStr = reqMap == null?TaieOcConstants.EMPTY_STRING:gson.toJson(reqMap);
        String sign_content = StringUtils.joinWith(TaieOcConstants.SIGN_DELIMA,licenseType,machineType,expireTime,reqStr);
//          2.签名值：｛签名值｝＋｛时间戳｝＝｛签名内容｝＋｛SM２私钥｝
        //获取SM2密钥，需要保存，公钥用来验签，私钥用来加签
       // Map<String, String> SM2_key = sm.getpublicKey();
        //使用SM2私钥加签{签名内容}
        Map<String, String> map = sm.Sign(sign_content,privateKey, expireTime);

//          3.加密签名内容：｛加密签名内容｝＝（｛签名内容｝==｛时间戳｝）＋｛SM４加密｝
//          生成16位16进制SM4密钥,SM4加解密使用同一密钥加密（｛签名内容｝==｛时间戳｝），解密需保存密钥值
       // String SM4_key = sm.generateKey();
//          根据签名内容SM2加密数据，SM2加签时间组合SM4加密数据
        String sign_content_encrypt = map.get("sign")+ "==" +map.get("timestamp");
//          使用SM4_key再次加密签名内容
        String cipher = sm.encryptEcb(SM4_KEY, sign_content_encrypt);
        return cipher;

    }

    public static String getSM4encrypt(String str){
        SM2Utils sm = new SM2Utils();
        return sm.encryptEcb(SM4_KEY, str);
    }

    public static String getSM4decrypt(String str){
        SM2Utils sm = new SM2Utils();
        return sm.decryptEcb(SM4_KEY,str);
    }

    /**
     * 许可验证
     * @param license
     * @return
     */
    public static boolean verifyMachineLicense(String license,String licenseType,
                                               String machineType,
                                               String expireTime, String reqMap) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(TaieOcConstants.DATE_LONG_FORMAT);
        SM2Utils sm = new SM2Utils();
        String sign_content = StringUtils.joinWith(TaieOcConstants.SIGN_DELIMA,licenseType,machineType,expireTime,reqMap);

        //  1.解密签名内容：｛解密签名内容｝＝｛加密签名内容｝＋｛SM４解密｝＝｛签名内容｝＋｛时间戳｝
        String sign_content_decrypt = sm.decryptEcb(SM4_KEY,license);
        //  2.验证签名：｛验证签名｝＝｛签名内容｝＋｛时间戳｝＋｛签名值｝＋｛SM２公钥｝
        //  3.分割截取SM2加密签名值及加密时间
        String sign_value_decrypt = sign_content_decrypt.split("==")[0];
        String datetime = sign_content_decrypt.split("==")[1];
        //使用SM2公钥验签
        return sm.VerifySign(sign_content, publicKey, sign_value_decrypt, datetime);
    }


    public static String getDecryptValue(String license) throws Exception {
        SM2Utils sm = new SM2Utils();
        String SM4_key = sm.generateKey();
        Map<String, String> SM2_key = sm.getpublicKey();
//  1.解密签名内容：｛解密签名内容｝＝｛加密签名内容｝＋｛SM４解密｝＝｛签名内容｝＋｛时间戳｝
        String sign_content_decrypt = sm.decryptEcb(SM4_key,license);
//          5.验证签名：｛验证签名｝＝｛签名内容｝＋｛时间戳｝＋｛签名值｝＋｛SM２公钥｝
//          分割截取SM2加密签名值及加密时间
        String sign_value_decrypt = sign_content_decrypt.split("==")[0];
        String datetime = sign_content_decrypt.split("==")[1];
        //使用SM2公钥验签
        return sign_value_decrypt;
    }


    public  Map<String, String> getpublicKey(){
        Map<String, String> map = new HashMap<String, String>();
        ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
        KeyPairGenerator kpg;
        try {


            kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
            // 使用SM2参数初始化生成器
            kpg.initialize(sm2Spec,new SecureRandom());
            // 获取密钥对
            KeyPair keyPair = kpg.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            BCECPublicKey p=(BCECPublicKey)publicKey;
            map.put("publicKey", Hex.toHexString(p.getQ().getEncoded(false)));
            SM2Utils sm = new SM2Utils();
            PrivateKey privateKey = keyPair.getPrivate();
            BCECPrivateKey s=(BCECPrivateKey)privateKey;
            map.put("privateKey",Hex.toHexString(s.getD().toByteArray()));

        } catch (NoSuchAlgorithmException e) {
            log.error("get public key error", e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error("get public key error", e);
        }
        return  map;
    }


    /// <summary>
    /// 签名，国密SM2
    /// </summary>
    /// <param name="body">参数内容</param>
    /// <param name="privateKey">私钥</param>
    /// <param name="sign">签名值</param>
    /// <param name="timestamp">时间戳</param>
    public  Map<String, String> Sign(String body, String privateKey, String dateStr)
    {
        Map<String, String> map = new HashMap<>();
        String sign;
        try {
            if (body == null || body.equals("")) return null;
            if (privateKey == null || privateKey.equals("")) return null;

            // 加密算法采用SM2加密算法
            sign = Hex.toHexString(Sign(body.getBytes("utf-8"), privateKey, dateStr.getBytes("utf-8")));
            map.put("sign",sign);
            map.put("timestamp",dateStr);
        }catch (Exception e){
            log.error("Sign error", e);
        }
        return map;
    }

    /// <summary>
    /// 加签算法 标准C1C2C3模式
    /// </summary>
    /// <param name="sourceData">源数据</param>
    /// <param name="privateKey">私钥</param>
    /// <param name="userId">用户标识</param>
    public  byte[] Sign(byte[] sourceData, String privateKey, byte[] userId) throws CryptoException
    {
        //获取一条SM2曲线参数
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        //构造domain参数
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);
        SM2Signer sm2 = new SM2Signer(new SM3Digest());
        CipherParameters cp;
        if (userId != null) cp = new ParametersWithID(new ParametersWithRandom(privateKeyParameters), userId);
        else cp = new ParametersWithRandom(privateKeyParameters);
        sm2.init(true, cp);
        sm2.update(sourceData, 0, sourceData.length);
        return sm2.generateSignature();
    }




    /// <summary>
    /// 验签，国密SM2
    /// </summary>
    /// <param name="body">参数内容</param>
    /// <param name="publicKey">公约</param>
    /// <param name="sign">签名值</param>
    /// <param name="timestamp">时间戳</param>
    /// <returns>成功与否</returns>
    public  Boolean VerifySign(String body, String publicKey, String sign, String timestamp)
    {
        Boolean flag =false;
        try {
            if (body == null || body.equals("")) return false;
            if (publicKey == null || publicKey.equals("")) return false;
            if (sign == null || sign.equals("")) return false;
            if (timestamp == null || timestamp.equals("")) return false;

            flag =VerifySign(body.getBytes("utf-8"), Hex.decode(publicKey),Hex.decode(sign), timestamp.getBytes("utf-8"));
        }catch (Exception e){
            log.error("VerifySign error", e);
        }

        return flag;
    }


    /// <summary>
    /// 验签算法 标准C1C2C3模式
    /// </summary>
    /// <param name="sourceData">源数据</param>
    /// <param name="publicKey">公钥</param>
    /// <param name="signData">验签数据</param>
    /// <param name="userId">用户标识</param>
    /// <returns></returns>
    public static Boolean VerifySign(byte[] sourceData, byte[] publicKey, byte[] signData, byte[] userId )
    {
        X9ECParameters x9ec = GMNamedCurves.getByName("sm2p256v1");
        ECDomainParameters domainParameters = new ECDomainParameters(x9ec.getCurve(), x9ec.getG(), x9ec.getN());
        CipherParameters publicKeyParameters = new ECPublicKeyParameters(x9ec.getCurve().decodePoint(publicKey),domainParameters );
        SM2Signer sm2 = new SM2Signer(new SM3Digest());
        CipherParameters cp;
        if (userId != null) cp = new ParametersWithID(publicKeyParameters, userId);
        else cp = publicKeyParameters;
        sm2.init(false, cp);
        sm2.update(sourceData, 0, sourceData.length);
        return sm2.verifySignature(signData);
    }


    /**
     * SM2加密算法
     * @param publicKey     公钥
     * @param data          明文数据
     * @return
     */
    public static String encrypt(String publicKey, String data) {

        // 获取一条SM2曲线参数
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        // 构造ECC算法参数，曲线方程、椭圆曲线G点、大整数N
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
        //提取公钥点
        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));
        // 公钥前面的02或者03表示是压缩公钥，04表示未压缩公钥, 04的时候，可以去掉前面的04
        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

        SM2Engine sm2Engine = new SM2Engine(new SM3Digest());
        // 设置sm2为加密模式
        sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters));

        byte[] arrayOfBytes = null;
        try {
            byte[] in = Hex.decode(data);
            arrayOfBytes = sm2Engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            log.error("SM2加密时出现异常:", e);
        }
        return Hex.toHexString(arrayOfBytes);

    }

    /**
     * SM2解密算法
     * @param privateKey        私钥
     * @param cipherData        密文数据
     * @return
     */
    public static String decrypt(String privateKey, String cipherData) {

        // 使用BC库加解密时密文以04开头，传入的密文前面没有04则补上
        if (!cipherData.startsWith("04")){
            cipherData = "04" + cipherData;
        }
        byte[] cipherDataByte = Hex.decode(cipherData);

        //获取一条SM2曲线参数
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        //构造domain参数
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());

        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);

        SM2Engine sm2Engine = new SM2Engine(new SM3Digest());
        // 设置sm2为解密模式
        sm2Engine.init(false, privateKeyParameters);

        String result = "";
        try {
            byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
            return Hex.toHexString(arrayOfBytes);
        } catch (Exception e) {
            log.error("SM2解密时出现异常:", e);
        }
        return result;

    }





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

    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 64;

    /**
     * 自动生成密钥
     *
     * @return
     * @explain
     */
    public String generateKey() throws Exception {
        return new String(Hex.encode(generateKey(DEFAULT_KEY_SIZE)));
    }

    /**
     * @param keySize
     * @return
     * @throws Exception
     * @explain
     */
    public byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * 生成ECB暗号
     *
     * @param algorithmName 算法名称
     * @param mode          模式
     * @param key
     * @return
     * @throws Exception
     * @explain ECB模式（电子密码本模式：Electronic codebook）
     */
    private Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     * sm4加密
     *
     * @param hexKey   16进制密钥（忽略大小写）
     * @param paramStr 待加密字符串
     * @return 返回16进制的加密字符串
     * @explain 加密模式：ECB
     * 密文长度不固定，会随着被加密字符串长度的变化而变化
     */
    public  String encryptEcb(String hexKey, String paramStr) {
        try {
            String cipherText = "";
            // 16进制字符串-->byte[]
            byte[] keyData = hexKey.getBytes("utf-8");
            // String-->byte[]
            byte[] srcData =paramStr.getBytes("utf-8");
            // 加密后的数组
            byte[] cipherArray = encryptEcbPadding(keyData, srcData);
            // byte[]-->hexString
            cipherText = Base64.getEncoder().encodeToString(cipherArray);
            return cipherText;
        } catch (Exception e) {
            return paramStr;
        }
    }



    /**
     * sm4解密
     *
     * @param hexKey     16进制密钥
     * @param cipherText 16进制的加密字符串（忽略大小写）
     * @return 解密后的字符串
     * @throws Exception
     * @explain 解密模式：采用ECB
     */
    public  String decryptEcb(String hexKey, String cipherText) {
        // 用于接收解密后的字符串
        String decryptStr = "";
        try {
            // hexString-->byte[]
            byte[] keyData = hexKey.getBytes("utf-8");
            // hexString-->byte[]
            byte[] cipherData = Base64.getDecoder().decode(cipherText);
            // 解密
            byte[] srcData = new byte[0];
            srcData = decryptEcbPadding(keyData, cipherData);
            // byte[]-->String
            decryptStr = new String(srcData, ENCODING);
        } catch (Exception e) {
            log.error("decryptEcb error", e);
        }
        return decryptStr;
    }


    /**
     * 加密模式之Ecb
     *
     * @param key
     * @param data
     * @return
     * @throws Exception
     * @explain
     */
    public  byte[] encryptEcbPadding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     *
     * @param key
     * @param cipherText
     * @return
     * @throws Exception
     * @explain
     */
    public  byte[] decryptEcbPadding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    /**
     * 校验加密前后的字符串是否为同一数据
     *
     * @param hexKey     16进制密钥（忽略大小写）
     * @param cipherText 16进制加密后的字符串
     * @param paramStr   加密前的字符串
     * @return 是否为同一数据
     * @throws Exception
     * @explain
     */
    public  boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        // 用于接收校验结果
        boolean flag = false;
        try {
            // hexString-->byte[]
            byte[] keyData = hexKey.getBytes("utf-8");

            // 将16进制字符串转换成数组
            byte[] cipherData = ByteUtils.fromHexString(cipherText);
            // 解密
            byte[] decryptData = decryptEcbPadding(keyData, cipherData);
            // 将原字符串转换成byte[]
            byte[] srcData = paramStr.getBytes(ENCODING);
            // 判断2个数组是否一致
            flag = Arrays.equals(decryptData, srcData);
        } catch (Exception e) {
            log.error("verifyEcb error", e);
        }
        return flag;
    }
}

