教育训练处考试制证系统后端
heheng
2025-02-20 9318f2446a94ce7df308c57c1c651e0c23e0036b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
package com.gkhy.exam.pay.utils;
 
import cn.com.jit.mof.MOFClient;
import cn.com.jit.mof.bean.MOFSignResult;
import cn.com.jit.mof.bean.MOFVerifyResult;
import cn.com.jit.new_vstk.AdvanceSignClient;
import cn.com.jit.new_vstk.Bean.*;
import cn.com.jit.new_vstk.exception.NewCSSException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.gkhy.exam.pay.entity.PayReqData;
import com.xjhys.edu.fee.sdk.client.BillClient;
import com.xjhys.edu.fee.sdk.client.impl.ClientFactory;
import com.xjhys.edu.fee.sdk.model.ResponseDataVo;
import com.xjhys.edu.fee.sdk.model.SignatureFileVo;
import com.xjhys.edu.fee.sdk.model.UploadXmlReponseDataVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;
 
/**
 * 缴费相关接口
 */
@Component
@Slf4j
public class PayUtils {
 
//    private final static String appid = "ED76A5F1703540BE977D34780B371FEB";
 
    @Value("${finance.orderUrl}")
    private String orderUrl;
 
    @Value("${finance.payNotifyUrl}")
    private String payNotifyUrl;
 
    @Value("${finance.payQueryUrl}")
    private String payQueryUrl;
 
    @Value("${finance.apiId}")
    private String appId;
 
    @Value("${finance.queryUrl}")
    private String queryUrl;
 
    @Value("${finance.uploadXmlUrl}")
    private String uploadXmlUrl;
 
//    @Value(("${finance.path}"))
//    private String path;
 
    /**
     * 请求开票,发起支付
     *
     * @param payReqData
     * @return
     * @throws IOException
     */
    public ResultVo sendApiPost(PayReqData payReqData) throws IOException {
 
        Map<String, String> param = new HashMap<>();
        String appid = "A1749891493E4CDDBFE4506357B1F0AB";
        String orderUrl = "http://finpt.xjcz.gov.cn/fs-service/fs-pay/invoice.do";
 
        HttpPost httpPost = new HttpPost(orderUrl);
        log.info("请求地址:" + orderUrl);
        //请求参数转为json格式base64编码
        String reqData = Base64.getEncoder().encodeToString(JSONObject.toJSONString(payReqData).getBytes());
        String mac = appid + "||" + reqData;
        mac = DigestUtils.md5Hex(mac.getBytes());
        param.put("appid", appid);
        log.info("请求appid:" + appid);
        param.put("reqdata", reqData);
        param.put("mac", mac);
 
        httpPost.setEntity(assemblyFormEntity(param, "utf-8"));
        HttpClient httpClient = getHttpClient(orderUrl);
        HttpResultVo execute = httpClient.execute(httpPost, getResponseHandler());
        String stringContent = execute.getStringContent();
        ResultVo resultVo = JSONObject.parseObject(stringContent, ResultVo.class);
        log.info("请求结果为:" + resultVo);
        return resultVo;
    }
 
    //组装请求体
    private static UrlEncodedFormEntity assemblyFormEntity(Map<String, String> parameters, String charset) {
        List<NameValuePair> formParameters = assemblyParameter(parameters);
        UrlEncodedFormEntity formEntity = null;
        try {
            if (charset != null) {
                formEntity = new UrlEncodedFormEntity(formParameters, charset);
            } else {
                formEntity = new UrlEncodedFormEntity(formParameters);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return formEntity;
    }
 
    private static List<NameValuePair> assemblyParameter(Map<String, String> parameters) {
        List<NameValuePair> allParameter = new ArrayList<>();
        if (parameters != null && !parameters.isEmpty()) {
            for (String name : parameters.keySet()) {
                NameValuePair parameter = new BasicNameValuePair(name, parameters.get(name));
                allParameter.add(parameter);
            }
        }
        return allParameter;
    }
 
    public static HttpClient getHttpClient(String url) {
        // 判断https访问
        if (url.startsWith("https")) {
            return sslClient();
        }
        return HttpClients.createDefault();
 
    }
 
    //在调用SSL之前需要重写验证方法,取消检测SSL 创建ConnectionManager,添加Connection配置信息
    private static HttpClient sslClient() {
        try {
            // 在调用SSL之前需要重写验证方法,取消检测SSL
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
 
                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }
 
                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            ctx.init(null, new TrustManager[]{trustManager}, null);
            SSLConnectionSocketFactory socketFactory =
                    new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            // 创建Registry
            RequestConfig requestConfig =
                    RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(Boolean.TRUE)
                            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
            // 创建ConnectionManager,添加Connection配置信息
            PoolingHttpClientConnectionManager connectionManager =
                    new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
                    .setDefaultRequestConfig(requestConfig).build();
            return closeableHttpClient;
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
 
    }
 
    //获取响应结果处理器,将响应结果封装为HttpResult对象
    private static ResponseHandler<HttpResultVo> getResponseHandler() {
        ResponseHandler<HttpResultVo> responseHandler = new ResponseHandler<HttpResultVo>() {
            @Override
            public HttpResultVo handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                if (httpResponse == null) {
                    throw new ClientProtocolException("HttpResponse is null");
                }
 
                StatusLine statusLine = httpResponse.getStatusLine();
                HttpEntity httpEntity = httpResponse.getEntity();
                if (statusLine == null) {
                    throw new ClientProtocolException("HttpResponse contains no StatusLine");
                }
                if (statusLine.getStatusCode() != 200) {
                    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
                }
                if (httpEntity == null) {
                    throw new ClientProtocolException("HttpResponse contains no HttpEntity");
                }
 
                HttpResultVo httpResult = new HttpResultVo();
                httpResult.setStatusCode(statusLine.getStatusCode());
                ContentType contentType = ContentType.getOrDefault(httpEntity);
                httpResult.setContentType(contentType.toString());
                boolean isTextType = isTextType(contentType);
                httpResult.setTextType(isTextType);
                if (isTextType) {
                    httpResult.setStringContent(EntityUtils.toString(httpEntity));
                } else {
                    httpResult.setByteArrayContent(EntityUtils.toByteArray(httpEntity));
                }
 
                httpResult.setHeaders(httpResponse.getAllHeaders());
 
                return httpResult;
            }
        };
        return responseHandler;
    }
 
    //判断相应内容是否为文本类型
    private static boolean isTextType(ContentType contentType) {
        if (contentType == null) {
            throw new RuntimeException("ContentType is null");
        }
        if (contentType.getMimeType().startsWith("text")) {
            return true;
        } else if (contentType.getMimeType().startsWith("image")) {
            return false;
        } else if (contentType.getMimeType().startsWith("application")) {
            if (contentType.getMimeType().contains("json") || contentType.getMimeType().contains("xml")) {
                return true;
            } else {
                return false;
            }
        } else if (contentType.getMimeType().startsWith("multipart")) {
            return false;
        } else {
            return true;
        }
    }
 
 
    //缴费结果通知
    public Map<String, String> receive(JSONObject jsonObject) throws IOException {
 
        Map<String, String> params = new HashMap<>();
        JSONObject reqdata = new JSONObject();
 
        Map<String, String> result = (Map<String, String>) jsonObject.get("reqdata");
        String orderNo = result.get("orderNo");
 
        //确认是否成功
        String notarize = affirmPost(orderNo);
        reqdata.put("orderNo", orderNo);
        reqdata.put("status", notarize);
 
        String req = Base64.getEncoder().encodeToString(reqdata.toJSONString().getBytes());
        String mac = appId + "||" + req;
        mac = DigestUtils.md5Hex(mac.getBytes());
        params.put("appid", appId);
        params.put("reqdata", req);
        params.put("mac", mac);
 
        return params;
    }
 
    //缴费结果确认查询
    public String affirmPost(String orderNo) throws IOException {
 
        HashMap<String, String> param = new HashMap<>();
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo", orderNo);
        String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
        String mac = appId + "||" + reqdata;
        mac = DigestUtils.md5Hex(mac.getBytes());
        param.put("appid", appId);
        param.put("reqdata", reqdata);
        param.put("mac", mac);
 
        HttpPost httppost = new HttpPost(payNotifyUrl);
        httppost.setEntity(assemblyFormEntity(param, "utf-8"));
        HttpClient httpClient = getHttpClient(payNotifyUrl);
        HttpResultVo execute = httpClient.execute(httppost, getResponseHandler());
        String stringContent = execute.getStringContent();
        ResultVo resultVo = JSONObject.parseObject(stringContent, ResultVo.class);
        log.info("请求结果为:" + resultVo);
        if (resultVo.getRespcode().equals("BUS0000")) {
            return "success";
        }
        return "fail";
    }
 
    //缴费结果查询
    public JSONObject query(String orderNo) throws IOException {
        HashMap<String, String> param = new HashMap<>();
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo", orderNo);
        String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
        String mac = appId + "||" + reqdata;
        mac = DigestUtils.md5Hex(mac.getBytes());
        param.put("appid", appId);
        param.put("reqdata", reqdata);
        param.put("mac", mac);
 
        HttpPost httppost = new HttpPost(payQueryUrl);
        httppost.setEntity(assemblyFormEntity(param, "utf-8"));
        HttpClient httpClient = getHttpClient(payQueryUrl);
        HttpResultVo execute = httpClient.execute(httppost, getResponseHandler());
        String stringContent = execute.getStringContent();
        JSONObject result = JSONObject.parseObject(stringContent);
        log.info("请求结果json为:" + result);
        return result;
    }
 
 
    //票据查询
    public ResponseEntity<String> findBill(String billNO) throws IOException {
        Map<String, String> params = new HashMap<>();
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("billNo", billNO);
        String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
        String mac = appId + "||" + reqdata;
        mac = DigestUtils.md5Hex(mac.getBytes());
        params.put("appid", appId);
        params.put("reqdata", reqdata);
        params.put("mac", mac);
 
        HttpPost httpPost = new HttpPost(queryUrl);
        httpPost.setEntity(assemblyFormEntity(params, "utf-8"));
        HttpClient httpClient = getHttpClient(queryUrl);
        HttpResultVo execute = httpClient.execute(httpPost, getResponseHandler());
        String stringContent = execute.getStringContent();
        JSONObject jsonObject1 = JSONObject.parseObject(stringContent);
        log.info("请求结果转json后为:" + jsonObject1);
        String result = (String) jsonObject1.get("reqdata");
        return ResponseEntity.ok(result);
 
    }
 
    //上传财政电子票据签名文件
    public ResultVo uploadXml(String orderId, String plain) throws IOException {
        Map<String, String> params = new HashMap<>();
 
//        Sign sign = new Sign();
//        SignResult sign1 = this.sign(plain);
//        log.info("签名结果为:"+ Arrays.toString(sign1.getSignData()));
//        VerifyResult verify = this.verify(plain, sign1.getSignData());
//        SignDto signDto = new SignDto("SM3", "Base64", new Date(), verify.getReturnData(), verify.getSerialNumber(), verify.getIssure());
//        Element signature = sign.getSignature(signDto);
 
        String appid = "A1749891493E4CDDBFE4506357B1F0AB";
        String orderUrl = "http://finpt.xjcz.gov.cn/fs-service/fs-pay/uploadXml.do";
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo", orderId);
        jsonObject.put("fileData", Base64.getEncoder().encodeToString(plain.getBytes()));
 
        String reqdata = Base64.getEncoder().encodeToString(jsonObject.toJSONString().getBytes());
        String mac = appid + "||" + reqdata;
        mac = DigestUtils.md5Hex(mac.getBytes());
 
        params.put("appid", appid);
        params.put("reqdata", reqdata);
        params.put("mac", mac);
 
        HttpPost httpPost = new HttpPost(orderUrl);
        httpPost.setEntity(assemblyFormEntity(params, "utf-8"));
        HttpClient httpClient = getHttpClient(orderUrl);
        HttpResultVo execute = httpClient.execute(httpPost, getResponseHandler());
        String stringContent = execute.getStringContent();
        ResultVo resultVo = JSONObject.parseObject(stringContent, ResultVo.class);
        log.info("请求结果转为:" + resultVo);
        return resultVo;
    }
 
 
    public ResultVo faqiV2(PayReqData payReqData) {
        System.out.println("发起接到参数===" + payReqData.toString());
 
        String reqdatastr = JSONObject.toJSONString(payReqData);
 
        String mac = this.getMD5("A1749891493E4CDDBFE4506357B1F0AB||" + this.getBase64(reqdatastr));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid", "A1749891493E4CDDBFE4506357B1F0AB");
        jsonObject.put("mac", mac);
        jsonObject.put("reqdata", this.getBase64(reqdatastr));
        Map<String, String> header = new HashMap();
        header.put("Accept", "application/json;charset=utf-8");
        header.put("Content-Type", "application/json;charset=utf-8");
        String resultStr = HttpUtil.post("http://finpt.xjcz.gov.cn/fs-service/fs-pay/invoice.do ", jsonObject);
        System.out.println("发起入参===" + jsonObject);
        JSONObject result = JSONObject.parseObject(resultStr);
        ResultVo resultVo = JSONObject.parseObject(resultStr, ResultVo.class);
        System.out.println("发起回参===" + result);
        result.put("postData", reqdatastr);
        JSONObject jsonObject2 = result.getJSONObject("respdata");
        String signfile = jsonObject2.getString("fileData");
        String orderNo1 = jsonObject2.getString("orderNo");
        String xmlFilePath = "F:/files/" + orderNo1 + ".xml";
        generateBase64StringToFile(signfile, xmlFilePath);
        String trr2 = "";
 
        try {
            File file = new File(xmlFilePath);
            FileReader reader1 = new FileReader(file);
            BufferedReader bReader = new BufferedReader(reader1);
            StringBuilder sb = new StringBuilder();
            String s = "";
 
            while ((s = bReader.readLine()) != null) {
                sb.append(s);
            }
 
            bReader.close();
            trr2 = sb.toString();
        } catch (Exception var34) {
            Exception e = var34;
            e.printStackTrace();
        }
 
        String jmsignfile = this.signFilejdnew(trr2);
        String zuizhongpath = montageXmlV3(xmlFilePath, jmsignfile);
        String zzsignfile = convertFileToBase64(zuizhongpath);
        Boolean b = this.uploadXmlV2(orderNo1, zzsignfile);
 
        File file = new File(xmlFilePath);
        file.delete();
        File file1 = new File(zuizhongpath);
        file1.delete();
        if (b) {
            return resultVo;
        } else {
            resultVo.setRespcode("BUS8888");
        }
        return resultVo;
    }
 
    public static String montageXmlV3(String ywfilePath, String xmlStr) {
        try {
            String outputxmlpath = ywfilePath.replace(".xml", "_3.xml");
            xmlStr = xmlStr.trim().replace("\n", "");
            FileWriter writer = new FileWriter(outputxmlpath);
            writer.write(xmlStr);
            writer.close();
            return outputxmlpath;
        } catch (Exception var4) {
            Exception e = var4;
            e.printStackTrace();
            return null;
        }
    }
 
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
 
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[((InputStream) in).available()];
            ((InputStream) in).read(data);
            ((InputStream) in).close();
        } catch (IOException var4) {
            IOException e = var4;
            e.printStackTrace();
        }
 
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        return base64Str;
    }
 
    public static boolean generateBase64StringToFile(String fileStr, String fileFilePath) {
        if (fileStr == null) {
            return false;
        } else {
            try {
                byte[] b = org.apache.commons.codec.binary.Base64.decodeBase64(fileStr);
 
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] = (byte) (b[i] + 256);
                    }
                }
 
                OutputStream out = new FileOutputStream(fileFilePath);
                ((OutputStream) out).write(b);
                ((OutputStream) out).flush();
                ((OutputStream) out).close();
                return true;
            } catch (Exception var4) {
                return false;
            }
        }
    }
 
    public String signFilejdnew(String plain) {
        BillSign sign = new BillSign(new ISignCommond() {
            @Override
            public SignDto signSm3Detach(String plain) {
                SignDto dto = null;
 
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("data", plain);
                    JSONObject Result = signFileV2(jsonObject);
                    dto = new SignDto(Result.getJSONObject("content").getDate("signTime"), Result.getJSONObject("content").getString("signResult"), "CN=Private Certificate Authority Of MOF SM2,O=MOF,C=CN", "142FA2FA197E349C");
                } catch (Exception var5) {
                    Exception exception = var5;
                    exception.printStackTrace();
                }
 
                return dto;
            }
        });
 
        try {
            String xx = sign.signBill(plain);
            return xx;
        } catch (Exception var4) {
            var4.printStackTrace();
            return null;
        }
    }
 
 
    public JSONObject signFileV2(JSONObject job) throws Exception {
        JSONObject xysfResult = new JSONObject();
        String certId = "11650000MB1957293J";
        String plain = job.getString("data").trim();
        MOFSignResult result = null;
        Map<String, Object> mmp = new HashMap();
 
        try {
            String filePath = "F:/cssconfig.properties";
            System.out.println("配置文件路径:" + filePath);
            MOFClient client = new MOFClient(filePath);
            System.out.println("证书标识为:" + certId);
            System.out.println("待签名数据:" + plain);
            result = client.sign(certId, plain.getBytes(StandardCharsets.UTF_8));
            System.out.println("签名返回结果:" + JSONObject.toJSONString(result));
            byte[] signData = result.getSignData();
            String base64Str = new String(cn.com.jit.ida.util.pki.encoders.Base64.encode(signData));
            mmp.put("signResult", base64Str);
            MOFVerifyResult resultVer = client.verifySign(signData, plain.getBytes(StandardCharsets.UTF_8));
            System.out.println("验签结果为:" + JSONObject.toJSONString(resultVer));
            mmp.put("issure", resultVer.getIssure());
            mmp.put("sn", resultVer.getSn());
            mmp.put("signTime", resultVer.getSignTime());
            xysfResult.put("success", true);
            xysfResult.put("content", mmp);
            return xysfResult;
        } catch (NewCSSException var12) {
            NewCSSException e = var12;
            System.out.println("****签名失败****");
            System.out.println("错误号为:" + e.getCode());
            System.out.println("错误描述为:" + e.getDescription());
            xysfResult.put("success", false);
            xysfResult.put("msg", "系统错误");
            return xysfResult;
        }
    }
 
    public Boolean uploadXmlV2(String orderNo, String signFile) {
        log.info("上传验签开始");
        log.info("上传验签参数订单号:" + orderNo + "签名文件:" + signFile);
        ResponseDataVo<?> res = ClientFactory.sdkConfig("A1749891493E4CDDBFE4506357B1F0AB", "http://finpt.xjcz.gov.cn/fs-service", "http://finpt.xjcz.gov.cn/fs-service");
        SignatureFileVo signatureFile = new SignatureFileVo();
        signatureFile.setFileData(signFile);
        signatureFile.setOrderNo(orderNo);
        BillClient billClient = ClientFactory.getBillClient();
        ResponseDataVo<UploadXmlReponseDataVo> dataRes = billClient.uploadXml(signatureFile);
 
        if (!dataRes.getRespcode().equals("BUS0000")) {
            log.info("上传验签失败:" + dataRes);
            return false;
        }
//        String mac = this.getMD5("A1749891493E4CDDBFE4506357B1F0AB||" + this.getBase64(signatureFile.toString()));
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("appid", "A1749891493E4CDDBFE4506357B1F0AB");
//        jsonObject.put("mac", mac);
//        jsonObject.put("reqdata", this.getBase64(signatureFile.toString()));
        return true;
    }
 
    public String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            byte[] var5 = messageDigest;
            int var6 = messageDigest.length;
 
            for (int var7 = 0; var7 < var6; ++var7) {
                byte b = var5[var7];
                hexString.append(String.format("%02x", b));
            }
 
            return hexString.toString();
        } catch (NoSuchAlgorithmException var9) {
            NoSuchAlgorithmException e = var9;
            throw new RuntimeException(e);
        }
    }
 
    public String getBase64(String str) {
        String encodedStr = org.apache.commons.codec.binary.Base64.encodeBase64String(str.getBytes());
        return encodedStr;
    }
 
 
    //获取XML文件字节码
    public static byte[] convertElementToByteArray(Element element) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 
        try {
            // 设置输出格式
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8"); // 设置编码为UTF-8
 
            // 创建 XMLWriter
            XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8), format);
 
            // 写入 Element 对象
            writer.write(element.getDocument());
            writer.close(); // 关闭 writer,确保所有数据都被写入
 
        } catch (IOException e) {
            e.printStackTrace(); // 打印异常信息
            // 处理异常,比如返回一个空的字节数组或重新抛出异常
            return new byte[0];
        }
 
        // 返回字节数组
        return byteArrayOutputStream.toByteArray();
    }
 
 
    public JSONObject signFileV2(String fileData) throws Exception {
        JSONObject xysfResult = new JSONObject();
        String certId = "11650000MB1957293J";
        MOFSignResult result = null;
//        Map<String, Object> mmp = new HashMap<>();
 
        try {
            String filePath = "F:\\text\\cssconfig.properties";
            System.out.println("配置文件路径:" + filePath);
            MOFClient client = new MOFClient(filePath);
            System.out.println("证书标识为:" + certId);
            System.out.println("待签名数据:" + fileData);
            result = client.sign(certId, fileData.getBytes(StandardCharsets.UTF_8));
            System.out.println("签名返回结果:" + JSONObject.toJSONString(result));
            byte[] signData = result.getSignData();
            String base64Str = new String(Base64.getEncoder().encode(signData));
//            mmp.put("signResult", base64Str);
            MOFVerifyResult resultVer = client.verifySign(signData, fileData.getBytes(StandardCharsets.UTF_8));
            System.out.println("验签结果为:" + JSONObject.toJSONString(resultVer));
//            mmp.put("issure", resultVer.getIssure());
//            mmp.put("sn", resultVer.getSn());
//            mmp.put("signTime", resultVer.getSignTime());
            SignDto signDto = new SignDto(resultVer.getSignTime(), base64Str, resultVer.getIssure(), resultVer.getSn());
            xysfResult.put("success", Boolean.valueOf(true));
            xysfResult.put("content", signDto);
            return xysfResult;
        } catch (NewCSSException e) {
            System.out.println("****签名失败****");
            System.out.println("错误号为:" + e.getCode());
            System.out.println("错误描述为:" + e.getDescription());
            xysfResult.put("success", Boolean.valueOf(false));
            xysfResult.put("msg", "系统错误");
            return xysfResult;
        }
    }
 
 
    //签名
    public SignResult sign(String strData) {
        SignResult result = null;
        String certId = "11650000MB1957293J";
        try {
            MOFClient client = new MOFClient("F:\\text\\cssconfig.properties");
            result = client.sign(certId, strData.getBytes(StandardCharsets.UTF_8));
            log.info("***签名成功***");
            log.info("签名返回结果为:" + result);
            byte[] signData = result.getSignData();
            String s = new String(Base64.getEncoder().encode(signData));
            log.info("签名结果为:" + s);
        } catch (NewCSSException e) {
            log.info("签名失败");
            log.info("错误号为:" + e.getCode());
            log.info("错误描述为: " + e.getDescription());
            log.info("日志标识码: " + e.getSerialNumber());
        }
        return result;
    }
 
    /**
     * 验签名
     */
    public MOFVerifyResult verify(byte[] strData, String signData) {
        MOFVerifyResult verify = null;
        try {
            MOFClient client = new MOFClient("F:\\text\\cssconfig.properties");
 
            verify = client.verifySign(strData, signData.getBytes(StandardCharsets.UTF_8));
            log.info("验签成功");
            log.info("    证书subjectdn: " + verify.getSubjectdn());
            log.info("    证书issuer: " + verify.getIssure());
            log.info("    证书SN: " + verify.getSn());
            log.info("    证书实体base64: " + verify.getDsCert());
 
        } catch (NewCSSException e) {
            log.info("****操作失败****");
            log.info("错误号为:" + e.getCode());
            log.info("错误描述为: " + e.getDescription());
            log.info("日志标识码: " + e.getSerialNumber());
        }
        return verify;
    }
 
    /**
     * 制作数字信封
     */
    public EnvelopResult encryptEnvelop(byte[] plain) {
        EnvelopResult envelopResult = null;
        try {
            AdvanceSignClient client = new AdvanceSignClient("F:\\text\\cssconfig.properties");
            String certId = "rsa";
            CertIdParams certIdParams = new CertIdParams(certId);
            //将封装好的加密证书参数对象放入 数组中
            CertParams[] envelopCerts = new CertIdParams[]{certIdParams};
            /* 制作信封 */
            envelopResult = client.encryptEnvelop(envelopCerts, plain);
            byte[] envelopData = envelopResult.getEnvelopData();
            log.info("信封结果:[" + envelopData + "]");
        } catch (NewCSSException e) {
            throw new RuntimeException(e);
        }
        return envelopResult;
    }
 
    /**
     * 解密数字信封
     */
    public DecryptResult decryptEnvelop(String signData) {
        DecryptResult result = null;
        try {
            AdvanceSignClient client = new AdvanceSignClient("F:\\text\\cssconfig.properties");
            byte[] enc_data = signData.getBytes();
            result = client.decryptEnvelop(enc_data);
            log.info("解密数字信封结果成功");
            String plainData = new String(result.getPlainData());
            log.info("原文:" + plainData);
            log.info("    证书subjectdn: " + result.getSubjectdn());
            log.info("    证书issuer: " + result.getIssure());
            log.info("    证书SN: " + result.getSn());
            log.info("    证书实体base64: " + result.getDsCert());
 
        } catch (NewCSSException e) {
            log.info("****操作失败****");
            log.info("错误号为:" + e.getCode());
            log.info("错误描述为: " + e.getDescription());
            log.info("日志标识码: " + e.getSerialNumber());
        }
        return result;
    }
 
 
}