Browse Source

加入接收频率协议

xusl 1 year ago
parent
commit
f546544b89

+ 5 - 6
backend/pom.xml

@@ -173,12 +173,11 @@
             <artifactId>spring-boot-configuration-processor</artifactId>
             <optional>true</optional>
         </dependency>
-<!--        &lt;!&ndash;jasypt配置文件加解密&ndash;&gt;-->
-<!--        <dependency>-->
-<!--            <groupId>com.github.ulisesbocchio</groupId>-->
-<!--            <artifactId>jasypt-spring-boot-starter</artifactId>-->
-<!--            <version>${jasypt-boot.version}</version>-->
-<!--        </dependency>-->
+        <dependency>
+            <groupId>wei.yigulu</groupId>
+            <artifactId>protocol-iec104</artifactId>
+            <version>2.4.23</version>
+        </dependency>
         <dependency>
             <groupId>com.github.whvcse</groupId>
             <artifactId>easy-captcha</artifactId>

+ 24 - 0
backend/src/main/java/com/jiayue/pfr/config/ProtocolConfig.java

@@ -0,0 +1,24 @@
+package com.jiayue.pfr.config;
+
+import com.jiayue.pfr.protocol.frequency.FmRtuMasterBuilder;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * 协议配置
+ *
+ * @author xsl
+ * @since 2023/10/27
+ */
+@Configuration
+public class ProtocolConfig {
+    /**
+     * 接收测频装置
+     */
+    @Bean
+    public void frequencyProtocol() {
+        FmRtuMasterBuilder fmRtuMasterBuilder = new FmRtuMasterBuilder("COM5");
+        fmRtuMasterBuilder.setBaudRate(115200);
+        fmRtuMasterBuilder.createByUnBlock();
+    }
+}

+ 146 - 0
backend/src/main/java/com/jiayue/pfr/protocol/frequency/DataBean.java

@@ -0,0 +1,146 @@
+package com.jiayue.pfr.protocol.frequency;
+
+import lombok.Setter;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+
+@Setter
+public class DataBean {
+
+    //频率
+    private BigDecimal F=BigDecimal.valueOf(-99);
+
+
+    //A相电压
+    private BigDecimal Ua=BigDecimal.valueOf(-99);
+    //B相电压
+    private BigDecimal Ub=BigDecimal.valueOf(-99);
+    //C相电压
+    private BigDecimal Uc=BigDecimal.valueOf(-99);
+
+
+    //A相电流
+    private BigDecimal Ia=BigDecimal.valueOf(-99);
+    //B相电流
+    private BigDecimal Ib=BigDecimal.valueOf(-99);
+    //C相电流
+    private BigDecimal Ic=BigDecimal.valueOf(-99);
+
+
+    //A相有功
+    private BigDecimal Pa=BigDecimal.valueOf(-99);
+    //B相有功
+    private BigDecimal Pb=BigDecimal.valueOf(-99);
+    //C相有功
+    private BigDecimal Pc=BigDecimal.valueOf(-99);
+
+
+    //A相无功
+    private BigDecimal Qa=BigDecimal.valueOf(-99);
+    //B相无功
+    private BigDecimal Qb=BigDecimal.valueOf(-99);
+    //C相无功
+    private BigDecimal Qc=BigDecimal.valueOf(-99);
+
+
+    //A相视在功率
+    private BigDecimal Sa=BigDecimal.valueOf(-99);
+    //B相视在功率
+    private BigDecimal Sb=BigDecimal.valueOf(-99);
+    //C相视在功率
+    private BigDecimal Sc=BigDecimal.valueOf(-99);
+
+
+    //A相未发生过流
+    private Boolean OIIa = false;
+    //B相未发生过流
+    private Boolean OIIb = false;
+    //C相未发生过流
+    private Boolean OIIc = false;
+
+
+    //A相未发生过压
+    private Boolean OVUa = false;
+    //B相未发生过压
+    private Boolean OVUb = false;
+    //C相未发生过压
+    private Boolean OVUc = false;
+
+
+    //A相是否失压
+    private Boolean LostVoltA = false;
+    //B相是否失压
+    private Boolean LostVoltB = false;
+    //C相是否失压
+    private Boolean LostVoltC = false;
+
+
+    //电压相序是否异常
+    private Boolean UPhSqErr = false;
+
+
+    public String toString() {
+        return "频率:" + F + " ;   </br>" +
+                "A相电压:" + Ua + " ;   B相电压:" + Ub + " ;   C相电压:" + Uc + " ;   </br>" +
+                "A相电流:" + Ia + " ;   B相电流:" + Ib + " ;   C相电流:" + Ic + " ;   </br>" +
+                "A相有功:" + Pa + " ;   B相有功:" + Pb + " ;   C相有功:" + Pc + " ;   </br>" +
+                "A相无功:" + Qa + " ;   B相无功:" + Qb + " ;   C相无功:" + Qc + " ;   </br>" +
+                "A相视在:" + Sa + " ;   B相视在:" + Sb + " ;   C相视在:" + Sc + " ;   </br>" +
+                "A相过流:" + (OIIa ? "是" : "否") + " ;   B相过流:" + (OIIb ? "是" : "否") + " ;   C相过流:" + (OIIc ? "是" : "否") + " ;   </br>" +
+                "A相过压:" + (OVUa ? "是" : "否") + " ;   B相过压:" + (OVUb ? "是" : "否") + " ;   C相过压:" + (OVUc ? "是" : "否") + " ;   </br>" +
+                "A相失压:" + (LostVoltA ? "是" : "否") + " ;   B相失压:" + (LostVoltB ? "是" : "否") + " ;   C相失压:" + (LostVoltC ? "是" : "否") + " ;   </br>" +
+                "电压相序:" + (UPhSqErr ? "异常" : "正常");
+
+    }
+
+
+    public String toWebString() {
+        return "频率:" + F + " ;   </br>" +
+                "A相电压:" + Ua + " ;   B相电压:" + Ub + " ;   C相电压:" + Uc + " ;   </br>" +
+                "A相电流:" + Ia + " ;   B相电流:" + Ib + " ;   C相电流:" + Ic + " ;   </br>" +
+                "A相有功:" + Pa + " ;   B相有功:" + Pb + " ;   C相有功:" + Pc + " ;   </br>" +
+                "A相无功:" + Qa + " ;   B相无功:" + Qb + " ;   C相无功:" + Qc + " ;   </br>" +
+                "A相视在:" + Sa + " ;   B相视在:" + Sb + " ;   C相视在:" + Sc + " ;   </br>" +
+                "A相过流:" + (OIIa ? "是" : "否") + " ;   B相过流:" + (OIIb ? "是" : "否") + " ;   C相过流:" + (OIIc ? "是" : "否") + " ;   </br>" +
+                "A相过压:" + (OVUa ? "是" : "否") + " ;   B相过压:" + (OVUb ? "是" : "否") + " ;   C相过压:" + (OVUc ? "是" : "否") + " ;   </br>" +
+                "A相失压:" + (LostVoltA ? "是" : "否") + " ;   B相失压:" + (LostVoltB ? "是" : "否") + " ;   C相失压:" + (LostVoltC ? "是" : "否") + " ;   </br>" +
+                "电压相序:" + (UPhSqErr ? "异常" : "正常");
+
+    }
+
+
+    public List<String> toWebDataList() {
+       List<String> list=new ArrayList<>();
+       list.add(F.toString());
+       list.add(Ua.toString());
+        list.add(Ub.toString());
+        list.add(Uc.toString());
+        list.add(Ia.toString());
+        list.add(Ib.toString());
+        list.add(Ic.toString());
+        list.add(Pa.toString());
+        list.add(Pb.toString());
+        list.add(Pc.toString());
+        list.add(Qa.toString());
+        list.add(Qb.toString());
+        list.add(Qc.toString());
+        list.add(Sa.toString());
+        list.add(Sb.toString());
+        list.add(Sc.toString());
+
+        list.add(OIIa?"是":"否");
+        list.add(OIIb?"是":"否");
+        list.add(OIIc?"是":"否");
+        list.add(OVUa?"是":"否");
+        list.add(OVUb?"是":"否");
+        list.add(OVUc?"是":"否");
+
+        list.add(LostVoltA?"是":"否");
+        list.add(LostVoltB?"是":"否");
+        list.add(LostVoltC?"是":"否");
+        list.add(UPhSqErr?"是":"否");
+        return list;
+    }
+}

+ 108 - 0
backend/src/main/java/com/jiayue/pfr/protocol/frequency/DataBeanPacker.java

@@ -0,0 +1,108 @@
+package com.jiayue.pfr.protocol.frequency;
+
+import io.netty.buffer.ByteBuf;
+
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+
+public class DataBeanPacker {
+
+
+    private DataBean lastDataBean = new DataBean();
+
+
+    private DataBeanPacker() {
+    }
+
+
+    private static class LazyHolder {
+        private static final DataBeanPacker INSTANCE = new DataBeanPacker();
+    }
+
+    /**
+     * 获取单例实例
+     *
+     * @return the instance
+     */
+    public static final DataBeanPacker getInstance() {
+        return LazyHolder.INSTANCE;
+    }
+
+    public synchronized DataBean getLastDataBean() {
+        return this.lastDataBean;
+    }
+
+    public synchronized DataBean setLastDataBean(DataBean dataBean) {
+        this.lastDataBean = dataBean;
+        return this.lastDataBean;
+    }
+
+    public DataBean decodeAnRecode(ByteBuf byteBuf) {
+        return setLastDataBean(decode(byteBuf));
+    }
+
+
+    public static DataBean decode(ByteBuf byteBuf) {
+        byteBuf.readInt();
+        DataBean dataBean = new DataBean();
+        dataBean.setUa(decodeBA(byteBuf).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
+        dataBean.setUb(decodeBA(byteBuf).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
+        dataBean.setUc(decodeBA(byteBuf).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP));
+
+
+        dataBean.setIa(decodeBA(byteBuf).divide(BigDecimal.valueOf(10), 1, RoundingMode.HALF_UP));
+        dataBean.setIb(decodeBA(byteBuf).divide(BigDecimal.valueOf(10), 1, RoundingMode.HALF_UP));
+        dataBean.setIc(decodeBA(byteBuf).divide(BigDecimal.valueOf(10), 1, RoundingMode.HALF_UP));
+
+
+        dataBean.setPa(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+        dataBean.setPb(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+        dataBean.setPc(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+
+
+        dataBean.setQa(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+        dataBean.setQb(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+        dataBean.setQc(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+
+
+        dataBean.setSa(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+        dataBean.setSb(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+        dataBean.setSc(decodeDCBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+
+
+        dataBean.setF(decodeBA(byteBuf).divide(BigDecimal.valueOf(1000), 3, RoundingMode.HALF_UP));
+
+        byte b = byteBuf.readByte();
+        dataBean.setOVUc((byte) ((b) & 0x01) == 0x01);
+        dataBean.setOVUb((byte) ((b >> 1) & 0x01) == 0x01);
+        dataBean.setOVUa((byte) ((b >> 2) & 0x01) == 0x01);
+        dataBean.setOIIc((byte) ((b >> 3) & 0x01) == 0x01);
+        dataBean.setOIIb((byte) ((b >> 4) & 0x01) == 0x01);
+        dataBean.setOIIa((byte) ((b >> 5) & 0x01) == 0x01);
+        b = byteBuf.readByte();
+        dataBean.setLostVoltC((byte) ((b) & 0x01) == 0x01);
+        dataBean.setLostVoltB((byte) ((b >> 1) & 0x01) == 0x01);
+        dataBean.setLostVoltA((byte) ((b >> 2) & 0x01) == 0x01);
+        dataBean.setUPhSqErr((byte) ((b >> 3) & 0x01) == 0x01);
+        return dataBean;
+    }
+
+
+    private static BigDecimal decodeBA(ByteBuf byteBuf) {
+        return BigDecimal.valueOf(((byteBuf.readByte() & 0xff) | ((byteBuf.readByte() & 0xff) << 8)));
+    }
+
+
+    private static BigDecimal decodeDCBA(ByteBuf byteBuf) {
+        return BigDecimal.valueOf((byteBuf.readByte() & 0xff) | ((byteBuf.readByte() & 0xff) << 8)
+                | ((byteBuf.readByte() & 0xff) << 16) | ((byteBuf.readByte() & 0xff) << 24));
+    }
+
+    private static BigDecimal decode_F_DCBA(ByteBuf byteBuf) {
+       return new BigDecimal(Float.toString(Float.intBitsToFloat((byteBuf.readByte() & 0xff) | ((byteBuf.readByte() & 0xff) << 8)
+                | ((byteBuf.readByte() & 0xff) << 16) | ((byteBuf.readByte() & 0xff) << 24))));
+    }
+    private static BigDecimal decode_F_BA(ByteBuf byteBuf) {
+        return new BigDecimal(Float.toString(Float.intBitsToFloat((byteBuf.readByte() & 0xff) | ((byteBuf.readByte() & 0xff) << 8))));
+    }
+}

+ 37 - 0
backend/src/main/java/com/jiayue/pfr/protocol/frequency/FmRtuMasterBuilder.java

@@ -0,0 +1,37 @@
+package com.jiayue.pfr.protocol.frequency;
+
+import lombok.experimental.Accessors;
+import lombok.extern.slf4j.Slf4j;
+import wei.yigulu.netty.AbstractRtuModeBuilder;
+import wei.yigulu.netty.ProtocolChannelInitializer;
+import wei.yigulu.purejavacomm.PureJavaCommChannel;
+
+/**
+ * cdt的客户端
+ *
+ * @author: xiuwei
+ * @version:
+ */
+@Accessors(chain = true)
+@Slf4j
+public class FmRtuMasterBuilder extends AbstractRtuModeBuilder {
+
+
+    public FmRtuMasterBuilder(String commPortId) {
+        super(commPortId);
+    }
+
+    @Override
+    protected ProtocolChannelInitializer getOrCreateChannelInitializer() {
+        if (this.channelInitializer == null) {
+            this.channelInitializer = new ProtocolChannelInitializer<PureJavaCommChannel>(this) {
+                @Override
+                protected void initChannel(PureJavaCommChannel ch) throws Exception {
+                    ch.pipeline().addLast(new FmRtuMasterDelimiterHandler().setLog(getLog()));
+                    ch.pipeline().addLast(new FmRtuMasterHandler((FmRtuMasterBuilder) builder));
+                }
+            };
+        }
+        return this.channelInitializer;
+    }
+}

+ 95 - 0
backend/src/main/java/com/jiayue/pfr/protocol/frequency/FmRtuMasterDelimiterHandler.java

@@ -0,0 +1,95 @@
+package com.jiayue.pfr.protocol.frequency;
+
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.experimental.Accessors;
+import org.joda.time.DateTime;
+import wei.yigulu.netty.AbstractDelimiterHandler;
+import wei.yigulu.utils.DataConvertor;
+
+
+/**
+ * 未继承netty的数据帧处理拆包类
+ *
+ * @author 修唯xiuwei
+ * @version 3.0
+ */
+
+public class FmRtuMasterDelimiterHandler extends AbstractDelimiterHandler {
+
+
+    private static byte HEAD_TAIL_1 = (byte) 0xff;
+
+    private static byte HEAD_TAIL_2 = (byte) 0x55;
+
+
+    private static final int LENGTH = 56;
+
+    /**
+     * 判断是否是断包的最大时间间隔
+     */
+    @Setter
+    @Getter
+    @Accessors(chain = true)
+    protected int maxTimeSpace = 250;
+
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+        log.info("-----------------------------------------------------------------");
+        log.info("接收到原始的报文 :" + DataConvertor.ByteBuf2String((ByteBuf) msg));
+        if (isOverMaxLength((ByteBuf) msg)) {
+            return;
+        }
+
+        if (!((cumulation.readableBytes() == 1 && cumulation.getByte(0) == HEAD_TAIL_1) ||
+                cumulation.readableBytes() > 2 && checkHead(cumulation))) {
+            log.warn("该段报文未以ff 55开头");
+            int headIndex = getHeadIndex(cumulation.readerIndex(), cumulation.writerIndex(), cumulation, new byte[]{HEAD_TAIL_1, HEAD_TAIL_2});
+            if (headIndex != -1) {
+                log.warn("该段报文发现ff 55 的报文片段,,舍弃部分报文:" + DataConvertor.ByteBuf2String(cumulation.readBytes(headIndex+2)));
+            } else {
+                log.warn("该段报文未发现ff 55 的报文片段,整段报文全部清除");
+                log.warn("这段字节中没有数据头,舍弃:" + DataConvertor.ByteBuf2String(cumulation.readBytes(cumulation.readableBytes())));
+                clearCumulation();
+                return;
+            }
+        }
+        while (cumulation.readableBytes() >= LENGTH) {
+            ByteBuf byteBuf = cumulation.readBytes(LENGTH);
+            if (checkHead(byteBuf) && checkTail(byteBuf)) {
+                log.info("发现符合ff 55开头,ff 55 结尾的56字节报文");
+                ctx.fireChannelRead(byteBuf);
+            }else{
+                log.info("该56字节不符合ff 55开头,ff 55 结尾的格式");
+                log.info( DataConvertor.ByteBuf2String(byteBuf));
+                byteBuf.release();
+            }
+        }
+        if (cumulation.readableBytes() == 0) {
+            clearCumulation();
+        } else {
+            timeMark = DateTime.now();
+        }
+
+    }
+
+
+    private boolean checkHead(ByteBuf msg) {
+        if (msg.getByte(0) == HEAD_TAIL_1 & msg.getByte(1) == HEAD_TAIL_2) {
+            return true;
+        }
+        return false;
+    }
+
+
+    private boolean checkTail(ByteBuf msg) {
+        if (msg.getByte(msg.readableBytes() - 2) == HEAD_TAIL_1 & msg.getByte(msg.readableBytes() - 1) == HEAD_TAIL_2) {
+            return true;
+        }
+        return false;
+    }
+}

+ 71 - 0
backend/src/main/java/com/jiayue/pfr/protocol/frequency/FmRtuMasterHandler.java

@@ -0,0 +1,71 @@
+package com.jiayue.pfr.protocol.frequency;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.EventLoop;
+import io.netty.channel.SimpleChannelInboundHandler;
+import lombok.Data;
+import lombok.extern.slf4j.Slf4j;
+import wei.yigulu.utils.DataConvertor;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * 16进制报文解析工具
+ *
+ * @author xiuwei
+ */
+@Data
+@Slf4j
+public class FmRtuMasterHandler extends SimpleChannelInboundHandler<ByteBuf> {
+
+
+    private static final int LEN = 52;
+
+    private FmRtuMasterBuilder FmMaster;
+
+    public FmRtuMasterHandler(FmRtuMasterBuilder FmMaster) {
+        this.FmMaster = FmMaster;
+    }
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) throws Exception {
+        FmMaster.getLog().info("-----连接串口{}成功-----", this.FmMaster.getCommPortId());
+    }
+
+    /**
+     * channel断连及不稳定时调用的方法
+     *
+     * @param ctx
+     * @throws Exception
+     */
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+        FmMaster.getLog().error("串口{}连接中断,正在启动重连机制... ", this.FmMaster.getCommPortId());
+        //在客户端与服务端连接过程中如果断连,就会调用的方法
+        final EventLoop eventLoop = ctx.channel().eventLoop();
+        eventLoop.schedule(() -> {
+            FmMaster.getLog().info("正在重连串口{}", this.FmMaster.getCommPortId());
+            this.FmMaster.create();
+        }, 3L, TimeUnit.SECONDS);
+    }
+
+    /**
+     * channel连接及传输报错时调用的方法
+     *
+     * @param ctx
+     * @param cause
+     */
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+        FmMaster.getLog().error("串口异常消息:", cause);
+    }
+
+    @Override
+    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
+       FmMaster.getLog().info("接收到串口{}发来数据帧: <= " + DataConvertor.ByteBuf2String(msg), this.FmMaster.getCommPortId());
+        if (msg.readableBytes() == LEN) {
+            DataBeanPacker.getInstance().decodeAnRecode(msg);
+        }
+    }
+}

+ 23 - 0
backend/src/main/java/com/jiayue/pfr/service/alg/FrequencyServiceImpl.java

@@ -0,0 +1,23 @@
+package com.jiayue.pfr.service.alg;
+
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+
+/**
+ * 频率服务类
+ *
+ * @author xsl
+ * @since 2023/10/27
+ */
+@Service
+public class FrequencyServiceImpl {
+
+    private BigDecimal activeFrequencyFormula(){
+
+
+
+
+        return null;
+    }
+}

+ 83 - 45
backend/src/test/java/com/jiayue/pfr/JasyptStringEncryptorDemo.java

@@ -3,55 +3,93 @@ package com.jiayue.pfr;
 //import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
 //import org.jasypt.util.text.BasicTextEncryptor;
 
+import java.util.Date;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
 /**
  * @author xsl
  * @since 2023/04/25
  */
 public class JasyptStringEncryptorDemo {
+    public static void main(String[] args) {
+        TestDto testDto = new TestDto();
+        testDto.setA("a");
+        testDto.setB("B");
+
+        ConcurrentHashMap<Long, Integer> map = new ConcurrentHashMap<>();
+        ConcurrentHashMap<String, TestDto> testmap = new ConcurrentHashMap<>();
+        testmap.put("1",testDto);
+
+        // 创建第一个线程
+        Thread thread1 = new Thread(() -> {
+//            int i=0;
+//            while (i<3000){
+//                try {
+//                    map.put(System.currentTimeMillis(),i);
+//                    Thread.sleep(100); // 模拟工作
+//                    i++;
+//                } catch (InterruptedException e) {
+//                    System.out.println("线程1异常:"+e);
+//                }
+//            }
+//            System.out.println("map容量个数:"+map.size());
+
+            while (true){
+                boolean bo = false;
+                for(Map.Entry<String, TestDto> entry: testmap.entrySet()) {
+                    bo = true;
+                    System.out.println("Value = " + entry.getValue().toString());
+                }
+                if (!bo){
+                    System.out.println(bo);
+                }
+
+            }
+        });
+
+        // 创建第二个线程
+        Thread thread2 = new Thread(() -> {
+            while (true){
+                try {
+                    TestDto testDto11 = new TestDto();
+                    testDto11.setA("A");
+                    testDto11.setB("B");
+                    testmap.put("1",testDto11);
+
+//                    ConcurrentHashMap<Long, Integer> bakmap = new ConcurrentHashMap<>();
+//                    System.out.println("操作前输出===》");
+//                    for(Map.Entry<Long, Integer> entry: map.entrySet()) {
+//                        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
+//                    }
+//                    System.out.println("《===操作前输出结束");
+//                    for(Map.Entry<Long, Integer> entry: map.entrySet()) {
+//                        if (entry.getKey()<System.currentTimeMillis()){
+//                            // 存储并删除
+//                            bakmap.put(entry.getKey(),entry.getValue());
+//                            map.remove(entry.getKey());
+//                        }
+//                    }
+//                    System.out.println("要保存的数据输出===》");
+//                    for(Map.Entry<Long, Integer> entry: bakmap.entrySet()) {
+//                        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
+//                    }
+//                    System.out.println("要保存的数据结束===》");
+//                    System.out.println("剩余数据===》");
+//                    for(Map.Entry<Long, Integer> entry: map.entrySet()) {
+//                        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
+//                    }
+//                    System.out.println("剩余数据结束===》");
+
+                    Thread.sleep(500); // 模拟工作
+                } catch (InterruptedException e) {
+                    System.out.println("线程2异常:"+e);
+                }
+            }
+        });
 
-//    public static void main(String[] args) {
-//        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
-//        textEncryptor.setPassword("atpingan");
-//        System.out.println("==========ssl配置==========");
-//        // key-store-password
-//        String keyStorePassword = textEncryptor.encrypt("s37d1gxm");
-//        System.out.println("keyStorePassword===>"+keyStorePassword);
-//        // mysql:url
-//        System.out.println("==========mysql配置==========");
-//        String mysqlURL = textEncryptor.encrypt("jdbc:mysql://localhost:3306/ssi?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&autoReconnect=true&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai");
-////        String mysqlURL = textEncryptor.encrypt("jdbc:mysql://192.168.1.208:3308/ssi?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&autoReconnect=true&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai&useSSL=true&verifyServerCertificate=true&requireSSL=true&clientCertificateKeyStoreUrl=classpath:mysql_ssl/mysql-keystore&clientCertificateKeyStorePassword=jieyue6677*&trustCertificateKeyStoreUrl=classpath:mysql_ssl/mysql-truststore&trustCertificateKeyStorePassword=jieyue6677*");
-//        System.out.println("mysqlURL===>"+mysqlURL);
-//        String mysqlUserName = textEncryptor.encrypt("root");
-//        System.out.println("mysqlUserName===>"+mysqlUserName);
-//        String mysqlPassWord = textEncryptor.encrypt("!QAZ2root");
-//        System.out.println("mysqlPassWord===>"+mysqlPassWord);
-//        // mail
-//        System.out.println("==========mail配置==========");
-//        String mailUserName = textEncryptor.encrypt("xushilong@jiayuepowertech.com");
-//        System.out.println("mailUserName===>"+mailUserName);
-//        String mailPassWord = textEncryptor.encrypt("jiayue123456");
-//        System.out.println("mailPassWord===>"+mailPassWord);
-//    }
-//
-//    /**
-//     * Jasypt 加密
-//     *
-//     * @param encryptor 加解密工具
-//     * @param plaintext 需要加密的字符串
-//     **/
-//    public static void encryption(StandardPBEStringEncryptor encryptor, String plaintext) {
-//        String ciphertext = encryptor.encrypt(plaintext);
-//        System.out.println(plaintext + " : " + ciphertext);
-//    }
-//
-//    /**
-//     * Jasypt 解密
-//     *
-//     * @param encryptor  加解密工具
-//     * @param ciphertext 需要解密的字符串
-//     **/
-//    public static void decrypt(StandardPBEStringEncryptor encryptor, String ciphertext) {
-//        String plaintext = encryptor.decrypt(ciphertext);
-//        System.out.println(ciphertext + " : " + plaintext);
-//    }
+        // 启动线程
+        thread1.start();
+        thread2.start();
+    }
 }

+ 13 - 0
backend/src/test/java/com/jiayue/pfr/TestDto.java

@@ -0,0 +1,13 @@
+package com.jiayue.pfr;
+
+import lombok.Data;
+
+/**
+ * @author jy
+ * @since 2023/10/27
+ */
+@Data
+public class TestDto {
+    String a;
+    String b;
+}

+ 0 - 90
backend/src/test/java/com/jiayue/pfr/service/BcSm2Util.java

@@ -1,90 +0,0 @@
-package com.jiayue.pfr.service;
-
-import cn.hutool.crypto.SmUtil;
-import com.jiayue.pfr.constant.SecretKeyConstants;
-import com.jiayue.pfr.util.SM2CryptUtils;
-import lombok.extern.slf4j.Slf4j;
-
-/**
-*
-*
-* @author xsl
-* @since 2023/08/08
-*/
-@Slf4j
-public class BcSm2Util {
-    public static void main(String[] args) {
-        //需要加密的明文
-//        String text = "测试";
-//        String pv = "6155d63ee27cbeca07f3e40c4f8856f1be8119fcbda1aadc7e0e595e52bad7bd";
-//        String pu = "041967638ca43d4577d8dba166bff4437fde944270101f398a95b846ec2f8177d09f8abc5d62b6cd2c7216274d7abe0c8e04b0bb691207a32dd2e12d6bd2798672";
-//
-
-//        String a = SM2CryptUtils.decrypt("8fe02b3e2bd96292691c899e1e3008ec076708a56c509ff8572a96f7da45f7d649f441d988479e14d6f0230520b1c02f6b2df95f49f4833d791757fc5a6aee6d46ed445c60856d8e625aa92fa64d09a7c3f22705d82f0a3bfe5e91b99ee013587fc6c4240c7269989e", "6155d63ee27cbeca07f3e40c4f8856f1be8119fcbda1aadc7e0e595e52bad7bd");
-//        System.out.println(a);
-
-
-
-        //创建sm2 对象
-//        SM2 sm2 = SmUtil.sm2(pv,pu);
-        //这里会自动生成对应的随机秘钥对 , 注意! 这里一定要强转,才能得到对应有效的秘钥信息
-//        byte[] privateKey = BCUtil.encodeECPrivateKey(sm2.getPrivateKey());
-//        //这里公钥不压缩  公钥的第一个字节用于表示是否压缩  可以不要
-//        byte[] publicKey = ((BCECPublicKey) sm2.getPublicKey()).getQ().getEncoded(false);
-        //这里得到的 压缩后的公钥   ((BCECPublicKey) sm2.getPublicKey()).getQ().getEncoded(true);
-        // byte[] publicKeyEc = BCUtil.encodeECPublicKey(sm2.getPublicKey());
-        //打印当前的公私秘钥
-//        System.out.println("私钥: " + HexUtil.encodeHexStr(pv.getBytes()));
-//        System.out.println("公钥: " + HexUtil.encodeHexStr(pu.getBytes()));
-        //得到明文对应的字节数组
-//        byte[] dateBytes = text.getBytes();
-//        System.out.println("数据: " + HexUtil.encodeHexStr(dateBytes));
-//        //这里需要手动设置,sm2 对象的默认值与我们期望的不一致
-//        sm2.setMode(SM2Engine.Mode.C1C3C2);
-//        sm2.setEncoding(new PlainDSAEncoding());
-//        //计算签名
-//        byte[] sign = sm2.sign(dateBytes, null);
-//        System.out.println("签名: " + HexUtil.encodeHexStr(sign));
-//        // 校验  验签
-//        boolean verify = sm2.verify(dateBytes, sign);
-//        System.out.println(verify);
-//
-//
-//        String signold = SM2CryptUtils.sign(pv,text);
-//        System.out.println(signold);
-
-        // SM3加密密码
-        String sm3password = SmUtil.sm3("asbcde").toUpperCase();
-         //再对密码sm2
-
-        String keystore = SM2CryptUtils.encrypt(sm3password,SecretKeyConstants.SERVER_PUBLIC_KEY);
-        System.out.println("keystore:"+keystore);
-//
-//        System.out.println("==========mysql配置==========");
-//        String sm2dbusername = SM2CryptUtils.encrypt("root",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("数据库用户名:"+sm2dbusername);
-//        String sm2dbpwd = SM2CryptUtils.encrypt("!QAZ2root",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("数据库密码:"+sm2dbpwd);
-//
-//        System.out.println("==========mail配置==========");
-//        String mailUserName = SM2CryptUtils.encrypt("xushilong@jiayuepowertech.com",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailUserName:"+mailUserName);
-//        String mailPassWord = SM2CryptUtils.encrypt("jiayue123456",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord:"+mailPassWord);
-
-//        String mailPassWord1 = SM2CryptUtils.encrypt("系统管理员(内置)",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord1:"+mailPassWord1);
-//        String mailPassWord2 = SM2CryptUtils.encrypt("审计管理员(内置)",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord2:"+mailPassWord2);
-//        String mailPassWord3 = SM2CryptUtils.encrypt("审核管理员(内置)",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord3:"+mailPassWord3);
-//        String mailPassWord4 = SM2CryptUtils.encrypt("业务审计员",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord4:"+mailPassWord4);
-//        String mailPassWord5 = SM2CryptUtils.encrypt("业务管理员",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord5:"+mailPassWord5);
-//        String mailPassWord6 = SM2CryptUtils.encrypt("业务操作员",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord6:"+mailPassWord6);
-//        String mailPassWord7 = SM2CryptUtils.encrypt("业务配置员",SecretKeyConstants.SERVER_PUBLIC_KEY);
-//        System.out.println("mailPassWord7:"+mailPassWord7);
-    }
-}

+ 0 - 36
backend/src/test/java/com/jiayue/pfr/service/CreateSm2Key.java

@@ -1,36 +0,0 @@
-package com.jiayue.pfr.service;
-
-import cn.hutool.core.util.HexUtil;
-import cn.hutool.crypto.BCUtil;
-import cn.hutool.crypto.SmUtil;
-import cn.hutool.crypto.asymmetric.SM2;
-import org.bouncycastle.crypto.engines.SM2Engine;
-import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
-
-/**
-* 生成sm2密钥
-*
-* @author xsl
-* @since 2023/02/28
-*/
-public class CreateSm2Key {
-    public static void main(String[] args) {
-        SM2 sm = SmUtil.sm2();
-
-        // sm2的加解密时有两种方式即 C1C2C3、 C1C3C2,
-        sm.setMode(SM2Engine.Mode.C1C3C2);
-
-        // 生成私钥
-        String privateKey = HexUtil.encodeHexStr(sm.getPrivateKey().getEncoded());
-        System.out.println("私钥:"+ privateKey);
-        // 生成公钥
-        String publicKey = HexUtil.encodeHexStr(sm.getPublicKey().getEncoded());
-        System.out.println("公钥:"+ publicKey);
-        // 生成私钥D
-        String privateKeyD = HexUtil.encodeHexStr(BCUtil.encodeECPrivateKey(sm.getPrivateKey())); // ((BCECPrivateKey) privateKey).getD().toByteArray();
-        System.out.println("私钥D:"+ privateKeyD);
-        // 生成公钥Q,以q值做为js端的加密公钥
-        String publicKeyQ = HexUtil.encodeHexStr(((BCECPublicKey) sm.getPublicKey()).getQ().getEncoded(false));
-        System.out.println("公钥Q:"+ publicKeyQ);
-    }
-}

+ 0 - 85
backend/src/test/java/com/jiayue/pfr/service/KeyUtils.java

@@ -1,85 +0,0 @@
-package com.jiayue.pfr.service;/**
-*
-*
-* @author xsl
-* @since 2023/08/08
-*/
-
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-
-import java.security.*;
-import java.security.spec.ECGenParameterSpec;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.security.spec.X509EncodedKeySpec;
-import java.util.Base64;
-
-/**
- * @author lihongxu6
- * @version 1.0
- * @className KeyUtils
- * @description TODO
- * @date 2021-01-13 23:27
- */
-public class KeyUtils {
-    /**
-     * 生成国密公私钥对
-     * <p>
-     * <code>String[0]</code> 公钥
-     * <p>
-     * <code>String[1]</code> 私钥
-     *
-     * @return
-     * @throws Exception
-     */
-    public static String[] generateSmKey() throws Exception {
-        KeyPairGenerator keyPairGenerator = null;
-        SecureRandom secureRandom = new SecureRandom();
-        ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
-        keyPairGenerator = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
-        keyPairGenerator.initialize(sm2Spec);
-        keyPairGenerator.initialize(sm2Spec, secureRandom);
-        KeyPair keyPair = keyPairGenerator.generateKeyPair();
-        PrivateKey privateKey = keyPair.getPrivate();
-        PublicKey publicKey = keyPair.getPublic();
-        String[] result = {
-                new String(Base64.getEncoder().encode(publicKey.getEncoded()))
-                , new String(Base64.getEncoder().encode(privateKey.getEncoded()))
-        };
-        return result;
-    }
-    /**
-     * 将Base64转码的公钥串,转化为公钥对象
-     *
-     * @param publicKey
-     * @return
-     */
-    public static PublicKey createPublicKey(String publicKey) {
-        PublicKey publickey = null;
-        try{
-            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
-            KeyFactory keyFactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
-            publickey = keyFactory.generatePublic(publicKeySpec);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        return publickey;
-    }
-
-    /**
-     * 将Base64转码的私钥串,转化为私钥对象
-     *
-     * @param privateKey
-     * @return
-     */
-    public static PrivateKey createPrivateKey(String privateKey) {
-        PrivateKey publickey = null;
-        try{
-            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
-            KeyFactory keyFactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
-            publickey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        return publickey;
-    }
-}

+ 0 - 410
backend/src/test/java/com/jiayue/pfr/service/Sm2Test.java

@@ -1,410 +0,0 @@
-package com.jiayue.pfr.service;
-
-import cn.hutool.crypto.asymmetric.KeyType;
-import cn.hutool.crypto.asymmetric.SM2;
-import com.jiayue.pfr.util.SM2CryptUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.bouncycastle.asn1.gm.GMNamedCurves;
-import org.bouncycastle.asn1.x9.X9ECParameters;
-import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
-import org.bouncycastle.crypto.CipherParameters;
-import org.bouncycastle.crypto.CryptoException;
-import org.bouncycastle.crypto.engines.SM2Engine;
-import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
-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.jce.spec.ECParameterSpec;
-import org.bouncycastle.jce.spec.ECPrivateKeySpec;
-import org.bouncycastle.math.ec.ECPoint;
-import org.bouncycastle.util.Strings;
-import org.bouncycastle.util.encoders.Hex;
-
-import java.math.BigInteger;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.SecureRandom;
-
-
-/**
- *
- *
- * @author xsl
- * @since 2023/08/07
- */
-@Slf4j
-public class Sm2Test {
-
-    /**
-     * 生成SM2公私钥对
-     * @return
-     */
-    private static AsymmetricCipherKeyPair genKeyPair0() {
-        //获取一条SM2曲线参数
-        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
-
-        //构造domain参数
-        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
-                sm2ECParameters.getG(), sm2ECParameters.getN());
-
-        //1.创建密钥生成器
-        ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
-
-        //2.初始化生成器,带上随机数
-        try {
-            keyPairGenerator.init(new ECKeyGenerationParameters(domainParameters, SecureRandom.getInstance("SHA1PRNG")));
-        } catch (NoSuchAlgorithmException e) {
-            log.error("生成公私钥对时出现异常:", e);
-//            e.printStackTrace();
-        }
-
-        //3.生成密钥对
-        AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.generateKeyPair();
-        return asymmetricCipherKeyPair;
-    }
-
-    /**
-     * 私钥签名
-     * @param privateKey    私钥
-     * @param content       待签名内容
-     * @return
-     */
-    public static String sign(String privateKey, String content) throws CryptoException {
-        //待签名内容转为字节数组
-        byte[] message = Hex.decode(content);
-
-        //获取一条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 sm2Signer = new SM2Signer();
-
-        //初始化签名实例,带上ID,国密的要求,ID默认值:1234567812345678
-        try {
-            sm2Signer.init(true, new ParametersWithID(new ParametersWithRandom(privateKeyParameters, SecureRandom.getInstance("SHA1PRNG")), Strings.toByteArray("31323334353637383132333435363738")));
-        } catch (NoSuchAlgorithmException e) {
-            log.error("签名时出现异常:", e);
-        }
-        sm2Signer.update(message, 0, message.length);
-        //生成签名,签名分为两部分r和s,分别对应索引0和1的数组
-        byte[] signBytes = sm2Signer.generateSignature();
-
-        String sign = Hex.toHexString(signBytes);
-
-        return sign;
-    }
-
-    /**
-     * 将R或者S修正为固定字节数
-     * @param rs
-     * @return
-     */
-    private static byte[] modifyRSFixedBytes(byte[] rs) {
-        int length = rs.length;
-        int fixedLength = 32;
-        byte[] result = new byte[fixedLength];
-        if (length < 32) {
-            System.arraycopy(rs, 0, result, fixedLength - length, length);
-        } else {
-            System.arraycopy(rs, length - fixedLength, result, 0, fixedLength);
-        }
-        return result;
-    }
-
-    /**
-     * 验证签名
-     * @param publicKey     公钥
-     * @param content       待签名内容
-     * @param sign          签名值
-     * @return
-     */
-    public static boolean verify(String publicKey, String content, String sign) {
-        //待签名内容
-        byte[] message = Hex.decode(content);
-        byte[] signData = Hex.decode(sign);
-
-        // 获取一条SM2曲线参数
-        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
-        // 构造domain参数
-        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);
-        //创建签名实例
-        SM2Signer sm2Signer = new SM2Signer();
-        ParametersWithID parametersWithID = new ParametersWithID(publicKeyParameters, Strings.toByteArray("31323334353637383132333435363738"));
-        sm2Signer.init(false, parametersWithID);
-        sm2Signer.update(message, 0, message.length);
-        //验证签名结果
-        boolean verify = sm2Signer.verifySignature(signData);
-        return verify;
-    }
-
-    /**
-     * SM2加密算法
-     * @param publicKey     公钥
-     * @param data          数据
-     * @return
-     */
-    public static String encrypt(String publicKey, String data){
-        // 获取一条SM2曲线参数
-        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
-        // 构造domain参数
-        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.Mode mode = SM2Engine.Mode.C1C3C2;
-
-        SM2Engine sm2Engine = new SM2Engine(mode);
-        sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));
-
-        byte[] arrayOfBytes = null;
-        try {
-            byte[] in = data.getBytes("utf-8");
-            arrayOfBytes = sm2Engine.processBlock(in, 0, in.length);
-        } catch (Exception e) {
-            log.error("SM2加密时出现异常:", e);
-        }
-        return Hex.toHexString(arrayOfBytes);
-    }
-
-    /**
-     * SM2加密算法
-     * @param publicKey     公钥
-     * @param data          明文数据
-     * @return
-     */
-    public static String encrypt(PublicKey publicKey, String data) {
-
-        ECPublicKeyParameters ecPublicKeyParameters = null;
-        if (publicKey instanceof BCECPublicKey) {
-            BCECPublicKey bcecPublicKey = (BCECPublicKey) publicKey;
-            ECParameterSpec ecParameterSpec = bcecPublicKey.getParameters();
-            ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
-                    ecParameterSpec.getG(), ecParameterSpec.getN());
-            ecPublicKeyParameters = new ECPublicKeyParameters(bcecPublicKey.getQ(), ecDomainParameters);
-        }
-
-        SM2Engine sm2Engine = new SM2Engine();
-        sm2Engine.init(true, new ParametersWithRandom(ecPublicKeyParameters, new SecureRandom()));
-
-        byte[] arrayOfBytes = null;
-        try {
-            byte[] in = data.getBytes("utf-8");
-            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) {
-        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.Mode mode = SM2Engine.Mode.C1C3C2;
-        SM2Engine sm2Engine = new SM2Engine(mode);
-        sm2Engine.init(false, privateKeyParameters);
-
-        String result = null;
-        try {
-            byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
-            return new String(arrayOfBytes, "utf-8");
-        } catch (Exception e) {
-            log.error("SM2解密时出现异常:", e);
-        }
-        return result;
-
-    }
-
-    /**
-     * SM2解密算法
-     * @param privateKey        私钥
-     * @param cipherData        密文数据
-     * @return
-     */
-    public static String decrypt(PrivateKey privateKey, String cipherData) {
-        byte[] cipherDataByte = Hex.decode(cipherData);
-
-        BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) privateKey;
-        ECParameterSpec ecParameterSpec = bcecPrivateKey.getParameters();
-
-        ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
-                ecParameterSpec.getG(), ecParameterSpec.getN());
-
-        ECPrivateKeyParameters ecPrivateKeyParameters = new ECPrivateKeyParameters(bcecPrivateKey.getD(),
-                ecDomainParameters);
-
-        SM2Engine sm2Engine = new SM2Engine();
-        sm2Engine.init(false, ecPrivateKeyParameters);
-
-        String result = null;
-        try {
-            byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
-            return new String(arrayOfBytes, "utf-8");
-        } catch (Exception e) {
-            log.error("SM2解密时出现异常:", e);
-        }
-        return result;
-    }
-
-    /**
-     * 将未压缩公钥压缩成压缩公钥
-     * 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04
-     * @param pubKey    未压缩公钥(16进制,不要带头部04)
-     * @return
-     */
-    public static String compressPubKey(String pubKey) {
-        pubKey = "04" + pubKey;    //将未压缩公钥加上未压缩标识.
-        // 获取一条SM2曲线参数
-        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
-        //提取公钥点
-        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(pubKey));
-        String compressPubKey = Hex.toHexString(pukPoint.getEncoded(Boolean.TRUE));
-
-        return compressPubKey;
-    }
-
-    /**
-     * 将压缩的公钥解压为非压缩公钥
-     * @param compressKey   压缩公钥
-     * @return
-     */
-    public static String unCompressPubKey(String compressKey) {
-        // 获取一条SM2曲线参数
-        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
-        //提取公钥点
-        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(compressKey));
-        String pubKey = Hex.toHexString(pukPoint.getEncoded(Boolean.FALSE));
-        //去掉前面的04   (04的时候,可以去掉前面的04)
-        pubKey = pubKey.substring(2);
-        return pubKey;
-    }
-
-    public static void main(String[] args) throws Exception{
-
-        String priKey = "6155d63ee27cbeca07f3e40c4f8856f1be8119fcbda1aadc7e0e595e52bad7bd";
-        System.out.println("私钥"+ priKey);
-        String pubKey = "1967638ca43d4577d8dba166bff4437fde944270101f398a95b846ec2f8177d09f8abc5d62b6cd2c7216274d7abe0c8e04b0bb691207a32dd2e12d6bd2798672";
-        System.out.println("公钥"+ pubKey);
-
-        //明文
-        String text = "123123";
-        System.out.println("测试明文文本" + text);
-//        //签名验签测试
-//        String sign = "";
-//        try {
-//            sign = sign(priKey, Hex.toHexString(text.getBytes()));
-//        } catch (CryptoException e) {
-//            e.printStackTrace();
-//        }
-//        System.out.println("生成签名" + sign);
-//        boolean verify = verify(pubKey, Hex.toHexString(text.getBytes()), sign);
-//        System.out.println("验签结果" + verify);
-
-//        //加解密测试
-//        String encryptData = encrypt(pubKey, text);
-//        System.out.println("加密结果" + encryptData);
-//        String decryptData = decrypt(priKey, encryptData);
-//        System.out.println("解密结果" + decryptData);
-
-
-         String privateKeyHex = "6155d63ee27cbeca07f3e40c4f8856f1be8119fcbda1aadc7e0e595e52bad7bd";
-         String x = "1967638ca43d4577d8dba166bff4437fde944270101f398a95b846ec2f8177d0";
-         String y = "9f8abc5d62b6cd2c7216274d7abe0c8e04b0bb691207a32dd2e12d6bd2798672";
-
-        SM2 sm2 = new SM2(privateKeyHex,
-                x,
-                y);
-
-        String sm2encoderparam= sm2.encryptBcd(text, KeyType.PublicKey);
-        System.out.println("hutool加密:"+sm2encoderparam);
-
-
-        System.out.println("最早hutool加密:"+SM2CryptUtils.encrypt(text,pubKey));
-    }
-
-
-    /**
-     * 签名
-     *
-     * @param withId
-     *            可以为null,若为null,则默认withId为字节数组:"1234567812345678".getBytes()
-     * @param srcData
-     * @return
-     * @throws CryptoException
-     */
-    public static String sign(String privateKey, byte[] withId, byte[] srcData)
-            throws Exception {
-
-        BCECPrivateKey bcecPrivateKey = getBCECPrivateKeyByPrivateKeyHex(privateKey);
-
-        ECPrivateKeyParameters priKeyParameters = convertPrivateKey(bcecPrivateKey);
-
-        SM2Signer signer = new SM2Signer();
-        CipherParameters param = null;
-        ParametersWithRandom pwr = new ParametersWithRandom(priKeyParameters, new SecureRandom());
-        if (withId != null) {
-            param = new ParametersWithID(pwr, withId);
-        } else {
-            param = pwr;
-        }
-        signer.init(true, param);
-        signer.update(srcData, 0, srcData.length);
-        System.out.println(srcData.length);
-        StringBuilder sb = new StringBuilder();
-        for (int i = 0; i < signer.generateSignature().length; i++) {
-            sb.append(String.format("%02x", signer.generateSignature()[i]));
-        }
-        return sb.toString();
-
-    }
-    private static X9ECParameters x9ECParameters = GMNamedCurves.getByName("sm2p256v1");
-
-    private static ECParameterSpec ecDomainParameters = new ECParameterSpec(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN());
-    /**
-     * 密钥转换
-     *
-     * @return
-     */
-    public static ECPrivateKeyParameters convertPrivateKey(BCECPrivateKey ecPriKey) {
-        ECParameterSpec parameterSpec = ecPriKey.getParameters();
-        ECDomainParameters domainParameters = new ECDomainParameters(parameterSpec.getCurve(), parameterSpec.getG(),
-                parameterSpec.getN(), parameterSpec.getH());
-        return new ECPrivateKeyParameters(ecPriKey.getD(), domainParameters);
-    }
-    public static BCECPrivateKey getBCECPrivateKeyByPrivateKeyHex(String privateKeyHex) {
-        BigInteger d = new BigInteger(privateKeyHex, 16);
-        ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(d, ecDomainParameters);
-        return new BCECPrivateKey("EC", ecPrivateKeySpec, BouncyCastleProvider.CONFIGURATION);
-    }
-}

+ 0 - 57
backend/src/test/java/com/jiayue/pfr/service/Sm2UiTest.java

@@ -1,57 +0,0 @@
-package com.jiayue.pfr.service;
-
-import cn.hutool.json.JSONUtil;
-import com.jiayue.pfr.constant.SecretKeyConstants;
-import com.jiayue.pfr.util.SM2CryptUtils;
-
-/**
-* 解析返回前端的加密数据
-*
-* @author xsl
-* @since 2023/03/14
-*/
-public class Sm2UiTest {
-    public static void main(String[] args) {
-//        // 返回前端的加密数据
-//        String encrypt = "b249d7a7c5322dc66cce4cad025cd451182b841dff6ca4a35dc52c1a2145de3725ebf0aed4829d731c536d7de819a52e392748492ec86571696a621df0eabe5510fea6327f5b3da61573e9ff103c1765e234046371d8972a6547478d27219b94ecaef8ce2bfb28b9c9db5a3d64b706cf73fac1d6bde60f7d3ecd2ab2353a18d383ed85e4ad4e8a1ac27c607d12d411e69e294d8c89d7327c983566920ede54bc827b83e9f6e7514d0e9619cdddcc6b42f6a6dc608e74285a6e42";
-//        // 返回前端签名数据
-//        String signStr = "3046022100cabcfdfbe9969122c3748dec9e3bf0b277e1a7065a57c6654ea23694813f1c79022100da8611cc8928cdd9abb9094888c50a482918bb28aea509e0785c90b95899c9cf";
-//        String text = SM2CryptUtils.decrypt(encrypt, SecretKeyConstants.CLIENT_PRIVATE_KEY);
-//            System.out.println("解密:"+text);
-//            boolean bo = SM2CryptUtils.verifySign(SecretKeyConstants.SERVER_PUBLIC_KEY,text,signStr);
-//            System.out.println("验签:"+bo);
-
-
-
-
-//        String jiami = SM2CryptUtils.encrypt("root","041967638ca43d4577d8dba166bff4437fde944270101f398a95b846ec2f8177d09f8abc5d62b6cd2c7216274d7abe0c8e04b0bb691207a32dd2e12d6bd2798672");
-//        System.out.println("加密:"+jiami);
-        String jiemi = SM2CryptUtils.decrypt("859605db44ad8ddb4ea74241ed051917ec11b62380d59e1fa879bd4febc47eabdd15812c4f46a8bfb0614f5165e068a9e2adac11e79a52929812305c29fade8bcaee16312b14d30e12339dd9d23142eccbaa704072f64f3bd26601ca2acd374182a3ee7a6f60a7bfbefc7b0e6c7ef4ef71ad0bb39c5651d2a010aabc314cfef96116f0f578d409188d571d4e2d920ebd908a0fb7c817d6dfcc4f77aef03aa4c6e1f912db444e12e967205ddb5ef99b5f80857dda4ea43de430bd38c74d5c10afc0d602294c01e2a3f5155239b7c23a8f4d62f2580f4a28c77f9f80f851fb23aa3310f523aed5a435063be4eabf91dbd42a1ed186f1583a",SecretKeyConstants.CLIENT_PRIVATE_KEY);
-        System.out.println("解密:"+jiemi);
-        Object sysTime = JSONUtil.parseObj(JSONUtil.parseObj(jiemi).get("data")).get("sysTime");
-        Object lk = JSONUtil.parseObj(JSONUtil.parseObj(jiemi).get("data")).get("lk");
-
-        String jiemi1 = SM2CryptUtils.decrypt("076a067abdb37b6aa48ec8aa16df410cd570be34d7c2f316331e82e0afb866a4cd730407f5c71e2e9615325a316fb7a7856295d6b6a21d697314f16b023d0665816886491ab6e290b5c4be1b1f87af0cc52fd59f5705983b39fee1497d5ff89e1ab6875317bfcee70700f600aa744b22289891db3e73a1e8fd0494eb8e543d05091179292c09626c51e9272b7af41400bdcc83006bf7d8413524eaaed8486ca50ba450822cfce490dbedba9a0b66386cb722d7257ea3df470b9b50b88e",SecretKeyConstants.SERVER_PRIVATE_KEY);
-        System.out.println("解密:"+jiemi1);
-
-        String commitStr = JSONUtil.parseObj(jiemi1).put("sysTime",sysTime).put("lk",lk).toString();
-
-        String qdjiami = SM2CryptUtils.encrypt(commitStr,SecretKeyConstants.SERVER_PUBLIC_KEY);
-        System.out.println("前端加密:"+qdjiami);
-        String qdqianming = SM2CryptUtils.sign(SecretKeyConstants.CLIENT_PRIVATE_KEY,commitStr);
-        System.out.println("前端签名:"+qdqianming);
-//
-//
-//        String qianming = SM2CryptUtils.sign("6155d63ee27cbeca07f3e40c4f8856f1be8119fcbda1aadc7e0e595e52bad7bd",jiemi);
-//        System.out.println("签名:"+qianming);
-//
-//        boolean yanqian = SM2CryptUtils.verifySign("041967638ca43d4577d8dba166bff4437fde944270101f398a95b846ec2f8177d09f8abc5d62b6cd2c7216274d7abe0c8e04b0bb691207a32dd2e12d6bd2798672",jiemi,qianming);
-//        System.out.println("验签:"+yanqian);
-
-
-//        String a= SmUtil.sm3("Xsl147258").toUpperCase();
-//        System.out.println(SM2CryptUtils.encrypt(a,SecretKeyConstants.SERVER_PUBLIC_KEY));
-
-
-    }
-}

+ 0 - 62
backend/src/test/java/com/jiayue/pfr/service/Test.java

@@ -1,62 +0,0 @@
-package com.jiayue.pfr.service;
-
-import cn.hutool.crypto.SmUtil;
-
-/**
-* test
-*
-* @author xsl
-* @since 2023/02/22
-*/
-public class Test {
-    public static void main(String[] args) throws Exception{
-//        SM2 sm2 = SmUtil.sm2();
-//        //这里会自动生成对应的随机秘钥对
-//        byte[] privateKey = BCUtil.encodeECPrivateKey(sm2.getPrivateKey());
-//        //这里默认公钥压缩  公钥的第一个字节用于表示是否压缩 02或者03表示是压缩公钥,04表示未压缩公钥
-////        byte[] publicKey = BCUtil.encodeECPublicKey(sm2.getPublicKey());
-//        //这里得到未压缩的公钥
-//         byte[] publicKey = ((BCECPublicKey) sm2.getPublicKey()).getQ().getEncoded(false);
-//        String priKey = HexUtil.encodeHexStr(privateKey);
-//        String pubKey = HexUtil.encodeHexStr(publicKey);
-//        System.out.println("私钥: " + priKey);
-//        System.out.println("公钥: " + pubKey);
-//
-
-
-
-//        String hex = "757365726E616D653D61646D696E2670617373776F72643D61646D696E26636F64653D3963356226766572696679757569643D6534336331633731626266643464313861306439353236633636663131363630266D61696C626F783D313131313131";
-//        int bsLength = hex.length();
-//        if (bsLength % 2 != 0) {
-//            hex = "0"+hex;
-//            bsLength = hex.length();
-//        }
-//        byte[] cs = new byte[bsLength / 2];
-//        String st;
-//        for (int i = 0; i < bsLength; i = i + 2) {
-//            st = hex.substring(i, i + 2);
-//            cs[i / 2] = (byte) Integer.parseInt(st, 16);
-//        }
-////        System.out.println(new String(cs,"utf-8"));
-//        String content = "SM2签名和验签";
-//        final SM2 sm2 = SmUtil.sm2("27ce6eec39dbf3b564a77c4da1e129fe1ba01a92f6d61055a33ed14ffcbc949e","0460ff8c8c306fe62f6f9d11c5c82c30d10bbbc703da094e423072cac7dc663c97fad52eccb34f311f47a07f280de157ba4f2aa659cabe749121384b9376ea2ed2");
-//        String sign = sm2.signHex(HexUtil.encodeHexStr(content));
-//        System.out.println("sign:" + sign);
-//
-//        boolean verify = sm2.verifyHex(HexUtil.encodeHexStr(content), sign);
-//        System.out.println("校验结果为:" + verify);
-
-//        String str = "{\"username\":\"admin\",\"password\":\"1234565\"}";
-//        Map<String,Object> map = JSONUtil.parseObj(str).getRaw();
-//        System.out.println(map.get("username"));
-//        System.out.println(map.get("password"));
-// 66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0
-// 66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0
-        System.out.println(SmUtil.sm3("abc"));
-//
-//
-//        System.out.println(Convert.toDBC("Xsl147258"));
-
-
-    }
-}