Browse Source

15天调证激活码

juxin_zhenghao 2 weeks ago
commit
76db5f6a1a

+ 30 - 0
src/main/java/com/ruoyi/business/Main.java

@@ -0,0 +1,30 @@
+package com.ruoyi.business;
+
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
+import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
+import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
+import org.springframework.context.annotation.ComponentScan;
+
+@SpringBootApplication(exclude = {
+        DataSourceAutoConfiguration.class,
+        DataSourceTransactionManagerAutoConfiguration.class,
+        HibernateJpaAutoConfiguration.class,
+        JdbcTemplateAutoConfiguration.class
+})
+public class Main {
+    public static void main(String[] args) {
+        SpringApplication.run(Main.class, args);
+        System.out.println("(♥◠‿◠)ノ゙  项目启动成功   ლ(´ڡ`ლ)゙  \n" +
+                "   ___      __    __   __    ___  \n" +
+                "   ___      __    __   __    ___  \n" +
+                "   ___      __    __   __    ___  \n" +
+                "   ___      __    __   __    ___  \n" +
+                "   ___      __    __   __    ___  \n"+
+                "   ___      __    __   __    ___  \n"
+        );
+    }
+}

+ 63 - 0
src/main/java/com/ruoyi/business/constant/TaieOcConstants.java

@@ -0,0 +1,63 @@
+package com.ruoyi.business.constant;
+import java.util.Arrays;
+import java.util.List;
+
+public class TaieOcConstants {
+
+    public static final String EN_DOT = ".";
+
+    public static final String EN_COMMA = ",";
+
+    public static final String EMP_STRING = "";
+
+    public  static final String DEFAULT_VERSION = "1.0.0";
+
+    public static final String EN_COLON = ":";
+
+    public static final String EMPTY_STRING = "";
+
+    public static final String EN_SLASH = "/";
+
+    public static final String YES = "Y";
+
+    public static final String SIGN_DELIMA = "=";
+
+    public static final String DATE_SHORT_FORMAT = "yyyy-MM-dd";
+
+    public static final String DATE_LONG_FORMAT = "yyyy-MM-dd HH:mm:ss";
+
+    public static final String PASSWORD_MASK = "******";
+
+    public static final String QUERY = "查看";
+
+    public static final String DELETE = "删除";
+
+    public static final String TENANT_MODIFY = "修改许可数";
+
+    public static final String TENANT_SAVE = "保存许可数";
+
+    public static final String TENANT_RESET = "重置密码";
+
+    public static final String PERCENT_FORMAT = "##%";
+
+    public static final String PIONEER_TENANT = "pioneer";
+
+    public static final String PIONEER_CONSOLE = "对内";
+
+
+    public static final String VERSION_TYPE_SPLIT_SYMBOL = "\\.";
+
+    public static final String SMALL_TYPE = "small";
+
+    public static final String MEDIUM_TYPE = "medium";
+
+    public static final String LARGE_TYPE = "large";
+
+    public static final String LEFT_BRACKET = "(";
+
+    public static final String RIGHT_BRACKET = ")";
+
+    public static final List<String> BADGE_PAGE_OPERATION = Arrays.asList("编辑");
+
+}
+

+ 23 - 0
src/main/java/com/ruoyi/business/controller/LicenseController.java

@@ -0,0 +1,23 @@
+package com.ruoyi.business.controller;
+
+import com.ruoyi.business.service.LicenseService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+@RequestMapping("/license")
+@RestController
+public class LicenseController {
+
+    @Autowired
+    private LicenseService licenseService;
+
+    @GetMapping("/create")
+    public String createLicenseAAA(@RequestParam(value = "type") String type,
+    @RequestParam(value = "machineCode") String machineCode) {
+       return licenseService.createLicense(type,machineCode);
+    }
+
+}

+ 65 - 0
src/main/java/com/ruoyi/business/entity/MachineLicenseAcquireReqDto.java

@@ -0,0 +1,65 @@
+package com.ruoyi.business.entity;
+
+
+import java.util.Map;
+
+public class MachineLicenseAcquireReqDto {
+    private String machineCode;
+    private String user;
+    private String machineKey;
+    // 执行器、设计器
+    private String machineType;
+    // license类型 local/remote
+    private String licenseType;
+    // 扩展字段
+    private Map<String,Object> paramsMap;
+
+    public String getMachineCode() {
+        return machineCode;
+    }
+
+    public void setMachineCode(String machineCode) {
+        this.machineCode = machineCode;
+    }
+
+    public String getUser() {
+        return user;
+    }
+
+    public void setUser(String user) {
+        this.user = user;
+    }
+
+    public String getMachineKey() {
+        return machineKey;
+    }
+
+    public void setMachineKey(String machineKey) {
+        this.machineKey = machineKey;
+    }
+
+    public String getMachineType() {
+        return machineType;
+    }
+
+    public void setMachineType(String machineType) {
+        this.machineType = machineType;
+    }
+
+    public String getLicenseType() {
+        return licenseType;
+    }
+
+    public void setLicenseType(String licenseType) {
+        this.licenseType = licenseType;
+    }
+
+    public Map<String, Object> getParamsMap() {
+        return paramsMap;
+    }
+
+    public void setParamsMap(Map<String, Object> paramsMap) {
+        this.paramsMap = paramsMap;
+    }
+}
+

+ 5 - 0
src/main/java/com/ruoyi/business/service/LicenseService.java

@@ -0,0 +1,5 @@
+package com.ruoyi.business.service;
+
+public interface LicenseService {
+    String createLicense(String type,String machineCode);
+}

+ 70 - 0
src/main/java/com/ruoyi/business/service/impl/licenseServiceImpl.java

@@ -0,0 +1,70 @@
+package com.ruoyi.business.service.impl;
+
+import cn.hutool.core.date.DateField;
+import cn.hutool.core.date.DateTime;
+import cn.hutool.core.date.DateUtil;
+import com.ruoyi.business.entity.MachineLicenseAcquireReqDto;
+import com.ruoyi.business.service.LicenseService;
+import com.ruoyi.business.util.DESUtils;
+import com.ruoyi.business.util.SM2Utils;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.interceptor.TransactionAspectSupport;
+
+@Service
+public class licenseServiceImpl implements LicenseService {
+
+    public static int DELAY_DAY = 15 ;
+
+    @Override
+    public String createLicense(String type,String licenseCode) {
+        if("DZ".equals(type)){
+            return createLicenseForDZ(licenseCode);
+        }else if("SP".equals(type)){
+            return createLicenseForSP(licenseCode);
+        }
+        return null;
+    }
+
+    /**
+     * 调证
+     * @param licenseCode
+     * @return
+     */
+        private String createLicenseForDZ(String licenseCode) {
+        String strRobotNum = "999";
+        DateTime endTime = DateUtil.offset(DateUtil.date(), DateField.DAY_OF_YEAR, DELAY_DAY);
+        String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");
+        System.out.println("到期时间:" + endTimeStr);
+
+        //        下属数字员工个数
+        String miyao = DESUtils.encrypt(strRobotNum, DESUtils.SECRET_KEY);
+        String decrypt = DESUtils.decrypt(miyao, DESUtils.SECRET_KEY);
+
+        //        日期license
+        MachineLicenseAcquireReqDto reqDto = new MachineLicenseAcquireReqDto();
+        reqDto.setMachineCode(licenseCode);
+        reqDto.setLicenseType(licenseCode);
+        reqDto.setMachineType("ALL");
+        System.out.println("执行入参:" + reqDto);
+        String license;
+        try {
+            license = SM2Utils.generateLicense(reqDto.getLicenseType(), reqDto.getMachineType()
+                    , endTimeStr, null);
+        } catch (Exception e) {
+            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
+            return null;
+        }
+        String resultLicense = license + "%%&&" + miyao;
+        System.out.println("执行许可:" + resultLicense);
+        return resultLicense;
+    }
+
+    /**
+     * 审批
+     * @param licenseCode
+     * @return
+     */
+    private String createLicenseForSP(String licenseCode) {
+        return null;
+    }
+}

+ 218 - 0
src/main/java/com/ruoyi/business/util/DESUtils.java

@@ -0,0 +1,218 @@
+package com.ruoyi.business.util;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+public class DESUtils {
+
+
+    /**
+     * 随意定一个私钥(长度必须为24位)
+     */
+    public static final String SECRET_KEY = "ABCDEFGHIJKLMN1234567890";
+
+    /**
+     * 加密
+     *
+     * @param inStr     需要加密的内容
+     * @param secretKey 密钥
+     * @return 加密后的数据
+     */
+
+    public static String encrypt(String inStr, String secretKey) {
+
+        SecretKey deskey = new SecretKeySpec(secretKey.getBytes(), "DESede");
+
+        Cipher cipher;
+
+        String outStr = null;
+
+        try {
+
+            cipher = Cipher.getInstance("DESede");
+
+            cipher.init(Cipher.ENCRYPT_MODE, deskey);
+
+            outStr = byte2hex(cipher.doFinal(inStr.getBytes()));
+
+        } catch (Exception e) {
+
+            System.err.println("3DES加密异常"+ e.getMessage());
+        }
+        System.out.println("3DES加密后字符串:" + outStr);
+
+        return outStr;
+
+    }
+
+    /**
+     * 解密
+     *
+     * @param inStr     需要解密的内容
+     * @param secretKey 密钥
+     * @return 解密后的数据
+     */
+
+    public static String decrypt(String inStr, String secretKey) {
+
+        SecretKey deskey = new SecretKeySpec(secretKey.getBytes(), "DESede");
+
+        Cipher cipher;
+        String outStr = null;
+
+        try {
+
+            cipher = Cipher.getInstance("DESede");
+
+            cipher.init(Cipher.DECRYPT_MODE, deskey);
+
+            outStr = new String(cipher.doFinal(hex2byte(inStr)));
+
+        } catch (Exception e) {
+
+            System.err.println("3DES解密异常"+e.getMessage());
+
+        }
+        System.out.println("3DES解密后数据:" + outStr);
+
+        return outStr;
+
+    }
+
+    /**
+     * 转化为16进制字符串方法
+     *
+     * @param digest 需要转换的字节组
+     * @return 转换后的字符串
+     */
+
+    private static String byte2hex(byte[] digest) {
+
+        StringBuffer hs = new StringBuffer();
+
+        String stmp = "";
+
+        for (int n = 0; n < digest.length; n++) {
+
+            stmp = Integer.toHexString(digest[n] & 0XFF);
+
+            if (stmp.length() == 1) {
+
+                hs.append("0" + stmp);
+
+            } else {
+
+                hs.append(stmp);
+
+            }
+
+        }
+
+        return hs.toString().toUpperCase();
+
+    }
+
+    /**
+     * 十六进转二进制
+     *
+     * @param hexStr 待转换16进制字符串
+     * @return 二进制字节组
+     */
+
+    public static byte[] hex2byte(String hexStr) {
+
+        if (hexStr == null)
+
+            return null;
+
+        hexStr = hexStr.trim();
+
+        int len = hexStr.length();
+
+        if (len == 0 || len % 2 == 1)
+
+            return null;
+
+        byte[] digest = new byte[len / 2];
+
+        try {
+
+            for (int i = 0; i < hexStr.length(); i += 2) {
+
+                digest[i / 2] = (byte) Integer.decode("0x" + hexStr.substring(i, i + 2)).intValue();
+
+            }
+            return digest;
+
+        } catch (Exception e) {
+
+            return null;
+
+        }
+
+    }
+
+
+//    public static void main(String[] args) {
+////        String pwd = "11111111";
+////        String encrypt = encrypt(pwd,SECRET_KEY);
+////        System.out.println(encrypt);
+////
+////        System.out.println(decrypt("6AFD5420C5BB8F4F",SECRET_KEY));
+////        System.out.println(decrypt(encrypt,SECRET_KEY));
+//
+//        int num = 0;
+//        do {
+//            Scanner sc = new Scanner(System.in);
+//            System.out.println("请输入要加密的类型数字: 1、加密账号密码字符串   2、加密xsd文件  3、解密数据");
+//            String str = sc.nextLine();
+//            if (str.equals("1")) {
+//                System.out.println("请输入要加密的数据:");
+//                String data = sc.nextLine();
+//                System.out.println("加密后的数据为:" + encrypt(data, SECRET_KEY));
+//            } else if(str.equals("2")){
+//                System.out.println("请输入要加密的xsd路径:");
+//                String xsdPath = sc.nextLine();
+//                System.out.println("加密后的xsd内容为:" + encryptXsd(xsdPath));
+//            } else {
+//                System.out.println("请输入要解密的数据:");
+//                String data = sc.nextLine();
+//                System.out.println("解密后的数据为:" + decrypt(data, SECRET_KEY));
+//            }
+//            System.out.println("是否继续操作? 0 继续, 1 退出");
+//            num = sc.nextInt();
+//        } while (num==0);
+//        System.exit(0);
+//
+//    }
+
+
+
+    public static String encryptXsd(String xsdPath){
+        ByteArrayInputStream bytein = null;
+        String data = null;
+//        String xsdPath = "xsd/pacs.008.001.06.xsd";
+        try{
+            BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(DESUtils.class.getClassLoader().getResource(xsdPath).toURI())) ;
+            StringBuilder stringBuilder = new StringBuilder();
+            String liner = "";
+            while ((liner = bufferedReader.readLine()) != null) {
+                stringBuilder.append(liner);
+            }
+            System.out.println("读取的xsd内容:" + stringBuilder.toString());
+            data = encrypt(stringBuilder.toString(),SECRET_KEY);
+            System.out.println("加密后内容:" + data);
+            bytein = new ByteArrayInputStream(data.getBytes());
+            String decStr = decrypt(data,SECRET_KEY);
+            System.out.println("解密后内容:" + decStr);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return  data;
+    }
+}

+ 489 - 0
src/main/java/com/ruoyi/business/util/SM2Utils.java

@@ -0,0 +1,489 @@
+package com.ruoyi.business.util;
+
+import com.google.gson.Gson;
+import com.ruoyi.business.constant.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.Arrays;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Map;
+
+@Slf4j
+public class SM2Utils {
+
+    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.签名值:{签名值}+{时间戳}={签名内容}+{SM2私钥}
+        //获取SM2密钥,需要保存,公钥用来验签,私钥用来加签
+        // Map<String, String> SM2_key = sm.getpublicKey();
+        //使用SM2私钥加签{签名内容}
+        Map<String, String> map = sm.Sign(sign_content, privateKey, expireTime);
+
+//          3.加密签名内容:{加密签名内容}=({签名内容}=={时间戳})+{SM4加密}
+//          生成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.解密签名内容:{解密签名内容}={加密签名内容}+{SM4解密}={签名内容}+{时间戳}
+        String sign_content_decrypt = sm.decryptEcb(SM4_KEY, license);
+        //  2.验证签名:{验证签名}={签名内容}+{时间戳}+{签名值}+{SM2公钥}
+        //  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.解密签名内容:{解密签名内容}={加密签名内容}+{SM4解密}={签名内容}+{时间戳}
+        String sign_content_decrypt = sm.decryptEcb(SM4_key, license);
+//          5.验证签名:{验证签名}={签名内容}+{时间戳}+{签名值}+{SM2公钥}
+//          分割截取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;
+    }
+}
+

+ 5 - 0
src/main/resources/application.yml

@@ -0,0 +1,5 @@
+server:
+  port: 9623
+
+
+