Эх сурвалжийг харах

Merge remote-tracking branch 'origin/master' into master

yangyj 1 жил өмнө
parent
commit
6c2ac56950

+ 1 - 0
blade-gateway/src/main/java/org/springblade/gateway/provider/AuthProvider.java

@@ -32,6 +32,7 @@ public class AuthProvider {
     private static final List<String> DEFAULT_SKIP_URL = new ArrayList<>();
 
     static {
+        DEFAULT_SKIP_URL.add("/bm/**"); //白马三方接口放行
         DEFAULT_SKIP_URL.add("/example");
         DEFAULT_SKIP_URL.add("/oauth/token/**");
         DEFAULT_SKIP_URL.add("/loginByToken");

+ 10 - 2
blade-service-api/blade-archive-api/src/main/java/org/springblade/archive/entity/ArchiveProjectConfig.java

@@ -36,6 +36,14 @@ public class ArchiveProjectConfig extends BaseEntity {
     //是否打页码
     public boolean isPage() {
         return getFactorType().contains("5");
-    }
-
+    };
+
+    //是否同步wbs节点
+    public boolean bSyncWbs() {
+        return getFactorType().contains("6");
+    };
+    //是否4位虚数
+    public boolean bAutoIndexLen4() {
+        return getFactorType().contains("7");
+    };
 }

+ 12 - 2
blade-service/blade-archive/src/main/java/org/springblade/archive/service/impl/ArchivesAutoServiceImpl.java

@@ -1729,7 +1729,13 @@ public class ArchivesAutoServiceImpl extends BaseServiceImpl<ArchivesAutoMapper,
 				contractId = node.getContractId();
 			}
 		}
-		this.refreshFileNumberNoSlipt(list,contractId,nodeId,bforce);
+
+		Integer indexType = 0;
+		ArchiveProjectConfig config = archiveProjectConfigService.getByProjectIdOrNew(projectId);
+		if (config!= null && config.bAutoIndexLen4()) {
+			indexType = 1;
+		}
+		this.refreshFileNumberNoSlipt(list,contractId,nodeId,bforce,indexType);
 	}
 
 	/**
@@ -1738,7 +1744,7 @@ public class ArchivesAutoServiceImpl extends BaseServiceImpl<ArchivesAutoMapper,
 	 * @param contractId
 	 * @param nodeId
 	 */
-	public void refreshFileNumberNoSlipt(List<ArchiveTreeContract> archiveTreeContracts,Long contractId,Long nodeId,boolean bforce) {
+	public void refreshFileNumberNoSlipt(List<ArchiveTreeContract> archiveTreeContracts,Long contractId,Long nodeId,boolean bforce,Integer indexType) {
 
 		List<ArchiveTreeContractVO2> subTreeList = new ArrayList<>();
 		List<List<ArchiveTreeContract>>  subGroupedList = new ArrayList<>();
@@ -1795,6 +1801,10 @@ public class ArchivesAutoServiceImpl extends BaseServiceImpl<ArchivesAutoMapper,
 				}
 
 				String fileNumber = fileNumberPrefix +"_"+ index;
+				if (indexType == 1) {
+					String formattedIndex = String.format("%04d", index);
+					fileNumber = fileNumberPrefix + "_" + formattedIndex;
+				}
 				if (bforce) {
 					if (archiveAutoPdfService.refreshFileNumberForce(archivesAuto,fileNumber)){
 						changeList.add(archivesAuto);

+ 4 - 1
blade-service/blade-business/src/main/java/org/springblade/business/controller/TaskController.java

@@ -1550,7 +1550,7 @@ public class TaskController extends BladeController {
         //封装入参SQL
         List<Object> params = new ArrayList<>();
         Integer eVisaStatus = dto.getVisaStatus();
-        StringBuilder sqlString = new StringBuilder("SELECT * FROM u_task WHERE approval_type != 4 AND contract_id = " + dto.getContractId()); //approval_type != 4 非档案的任务就是1填报资料,2工程文件,3日志资料
+        StringBuilder sqlString = new StringBuilder("SELECT * FROM u_task WHERE approval_type != 4 AND status != 3 AND contract_id = " + dto.getContractId()); //approval_type != 4 非档案的任务就是1填报资料,2工程文件,3日志资料
 
         if (StringUtils.isNotBlank(dto.getStartTimeValue()) && StringUtils.isNotBlank(dto.getEndTimeValue())) {
             if (dto.getStartTimeValue().equals(dto.getEndTimeValue())) {
@@ -1650,6 +1650,9 @@ public class TaskController extends BladeController {
                         for (TaskParallel taskPa : taskParallelList) {
                             if (taskPa.getStatus() == 2 && ObjectUtil.isNotEmpty(taskPa.getEVisaStatus()) && taskPa.getEVisaStatus() == 1) {
                                 taskPa.setEVisaStatus(2);
+                                if (taskPa.getEVisaContent().contains("请等待") && ObjectUtil.isEmpty(eVisaFailedInfo)) {
+                                    eVisaFailedInfo = taskPa.getEVisaContent();
+                                }
                             } else if (taskPa.getStatus() == 3 && taskPa.getTaskUser().equals(SecureUtil.getUserId().toString())) {
                                 taskPa.setEVisaStatus(3);
                             } else if (ObjectUtil.isNotEmpty(taskPa.getEVisaStatus()) && taskPa.getEVisaStatus() == 99) {

+ 10 - 22
blade-service/blade-business/src/main/java/org/springblade/business/service/impl/InformationQueryServiceImpl.java

@@ -520,13 +520,13 @@ public class InformationQueryServiceImpl extends BaseServiceImpl<InformationQuer
             List<Long> informationIds = result.stream().filter(f -> f.getStatus().equals(1) || f.getStatus().equals(2)).map(InformationQuery::getId).collect(Collectors.toList());
             String informationIdsStr = informationIds.stream().map(String::valueOf).collect(Collectors.joining(","));
             if (StringUtils.isNotEmpty(informationIdsStr)) {
-                List<Task> query = jdbcTemplate.query("SELECT id,form_data_id,process_instance_id,approval_type,status,batch,project_id,contract_id FROM u_task WHERE form_data_id IN(" + informationIdsStr + ") AND status IN (1, 2, 3) AND is_deleted = 0", new BeanPropertyRowMapper<>(Task.class));
+                List<Task> query = jdbcTemplate.query("SELECT id,form_data_id,process_instance_id,approval_type,status,batch,project_id,contract_id FROM u_task WHERE form_data_id IN(" + informationIdsStr + ") AND status IN (1, 2) AND is_deleted = 0", new BeanPropertyRowMapper<>(Task.class));
 
                 taskMaps = query.stream().collect(Collectors.groupingBy(Task::getFormDataId));
 
                 Set<String> processInstanceIds = query.stream().map(Task::getProcessInstanceId).map(id -> "'" + id + "'").collect(Collectors.toSet());
                 if (processInstanceIds.size() > 0) {
-                    List<TaskParallel> taskParallels = jdbcTemplate.query("select task_user, task_user_name, e_visa_status, status, process_instance_id from u_task_parallel where is_deleted = 0 and process_instance_id in(" + StringUtils.join(processInstanceIds, ",") + ")", new BeanPropertyRowMapper<>(TaskParallel.class));
+                    List<TaskParallel> taskParallels = jdbcTemplate.query("select task_user, task_user_name, e_visa_status, status, process_instance_id, initiative from u_task_parallel where is_deleted = 0 and process_instance_id in(" + StringUtils.join(processInstanceIds, ",") + ")", new BeanPropertyRowMapper<>(TaskParallel.class));
                     taskParallelMaps = taskParallels.stream().collect(Collectors.groupingBy(TaskParallel::getProcessInstanceId));
                 }
             }
@@ -573,17 +573,6 @@ public class InformationQueryServiceImpl extends BaseServiceImpl<InformationQuer
 
                 if (Arrays.asList("1,2".split(",")).contains(vor.getStatus().toString())) {
                     //说明属于待审批和已审批状态,查询待办信息
-                    /*List<Task> tasks = this.taskClient.queryTaskListByFormDataId(String.valueOf(vor.getId()));
-                    if (tasks != null && tasks.size() > 0) {
-                        //查询当前任务的所有待办人
-                        List<TaskParallel> linkTasks = this.taskParallelService.queryApprovalUser(tasks.get(0).getProcessInstanceId());
-                        if (linkTasks != null && linkTasks.size() > 0) {
-                            //处理审批状态
-                            this.integrationMethod(vor, linkTasks);
-                        }
-                        //设置上报批次
-                        vor.setReportNumber(String.valueOf(tasks.get(0).getBatch()));
-                    }*/
                     List<Task> tasks = finalTaskMaps.getOrDefault(vor.getId().toString(), null);
                     if (tasks != null && tasks.size() > 0) {
                         //查询当前任务的所有待办人
@@ -599,14 +588,6 @@ public class InformationQueryServiceImpl extends BaseServiceImpl<InformationQuer
 
                 //校验关联的工序节点是否全都已审批
                 if (StringUtils.isNotEmpty(vor.getSjRecordIds())) {
-                    /*List<InformationQuery> informationQueryList = this.baseMapper.selectBatchIds(Func.toLongList(vor.getSjRecordIds()));
-                    List<InformationQuery> collect = informationQueryList.stream().filter(f -> f.getStatus().equals(2)).collect(Collectors.toList());
-                    if (collect.size() == informationQueryList.size()) {
-                        vor.setIsApprove(true);
-                    } else {
-                        vor.setIsApprove(false);
-                    }*/
-
                     List<String> recordIdList = Func.toStrList(vor.getSjRecordIds());
                     List<InformationQuery> informationQueryList = finalInformationQueries.stream()
                             .filter(f -> recordIdList.contains(f.getId().toString()))
@@ -817,7 +798,14 @@ public class InformationQueryServiceImpl extends BaseServiceImpl<InformationQuer
      * 统合方法
      */
     private void integrationMethod(InformationQueryVO vo, List<TaskParallel> linkList) {
-        linkList.forEach(link -> vo.setWaitingUserList(link.getTaskUserName(), new Integer("999").equals(link.getEVisaStatus()) ? 999 : new Integer("2").equals(link.getStatus()) ? 2 : new Integer("3").equals(link.getStatus()) && new Integer("1").equals(link.getInitiative()) ? 3 : 1));
+        for (TaskParallel link : linkList) {
+            vo.setWaitingUserList
+                    (link.getTaskUserName(),
+                            new Integer(999).equals(link.getEVisaStatus()) ? 999 :
+                                    (new Integer(2).equals(link.getStatus()) ? 2 :
+                                            (new Integer(3).equals(link.getStatus()) && new Integer(1).equals(link.getInitiative())) ? 3
+                                                    : 1));
+        }
     }
 
     /**

+ 2 - 3
blade-service/blade-business/src/main/java/org/springblade/business/service/impl/TaskServiceImpl.java

@@ -1223,7 +1223,7 @@ public class TaskServiceImpl extends BaseServiceImpl<TaskMapper, Task> implement
             ArchiveProjectConfig archiveProjectConfig = archiveAutoClient.getByProjectIdOrNew(query.getProjectId());
 
             //测试阶段,必须打开项目配置才能同步wbs节点
-            if (archiveProjectConfig != null && archiveProjectConfig.getFactorType().contains("6")) {
+            if (archiveProjectConfig != null && archiveProjectConfig.bSyncWbs()) {
                 //废除
                 if (status == 0) {
                     delArchiveFileBusinessData(query.getProjectId(), query.getWbsId());
@@ -1462,8 +1462,7 @@ public class TaskServiceImpl extends BaseServiceImpl<TaskMapper, Task> implement
                         //修改重签状态为保存PDF失败
                         this.taskParallelService.update(Wrappers.<TaskParallel>lambdaUpdate()
                                 .set(TaskParallel::getEVisaContent, "重新保存PDF失败")
-                                .eq(TaskParallel::getProcessInstanceId, task.getProcessInstanceId())
-                                .eq(TaskParallel::getEVisaStatus, "99"));
+                                .eq(TaskParallel::getProcessInstanceId, task.getProcessInstanceId()));
                     }
                 }
 

+ 1 - 1
blade-service/blade-manager/src/main/java/org/springblade/manager/service/impl/ArchiveTreeContractSyncImpl.java

@@ -191,7 +191,7 @@ public class ArchiveTreeContractSyncImpl {
         ArchiveProjectConfig archiveProjectConfig = archiveAutoClient.getByProjectIdOrNew(projectId);
 
         //测试阶段,必须打开项目配置才能同步wbs节点
-        if (archiveProjectConfig!= null && archiveProjectConfig.getFactorType().contains("6")) {
+        if (archiveProjectConfig!= null && archiveProjectConfig.bSyncWbs()) {
             //todo 等测试OK再打开
             saveList =arTreeContractInitService.getContractExtNodes(AuthUtil.getTenantId(),projectId,dstTree,classify);
         }

+ 13 - 0
blade-service/blade-user/src/main/java/org/springblade/system/user/bean/GetTokenDTO.java

@@ -0,0 +1,13 @@
+package org.springblade.system.user.bean;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+@Data
+public class GetTokenDTO implements Serializable {
+
+    private String uuid;
+    private String idcard;
+
+}

+ 205 - 0
blade-service/blade-user/src/main/java/org/springblade/system/user/thirdparty/ThirdPartySystemApi.java

@@ -0,0 +1,205 @@
+package org.springblade.system.user.thirdparty;
+
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import lombok.AllArgsConstructor;
+import org.apache.commons.lang.StringUtils;
+import org.apache.http.Consts;
+import org.apache.http.HttpResponse;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.message.BasicNameValuePair;
+import org.springblade.common.utils.SnowFlakeUtil;
+import org.springblade.core.log.exception.ServiceException;
+import org.springblade.core.tool.api.R;
+import org.springblade.core.tool.utils.DigestUtil;
+import org.springblade.system.entity.AuthClient;
+import org.springblade.system.user.bean.GetTokenDTO;
+import org.springblade.system.user.entity.User;
+import org.springblade.system.user.util.RsaUtils;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.data.redis.core.RedisTemplate;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
+
+
+/**
+ * 白马三方接口相关
+ *
+ * @author liuyc
+ * @date 2023年11月14日15:15:42
+ */
+@RestController
+@AllArgsConstructor
+@RequestMapping("/bm")
+public class ThirdPartySystemApi {
+
+    private final JdbcTemplate jdbcTemplate;
+    private final RedisTemplate<String, String> redisTemplate;
+
+    /**
+     * 获取公钥信息
+     */
+    @GetMapping("/auth/public-key")
+    public Map<String, Object> getPublicKey(@RequestParam String appKey) {
+        /*查询Redis中已有的键值对数量*/
+        String redisKeyPattern = "bm-secret-key:*";
+        if (Objects.requireNonNull(redisTemplate.keys(redisKeyPattern)).size() >= 10) {
+            throw new ServiceException("请求频率超过限制,请2分钟后重试");
+        }
+
+        if (StringUtils.isEmpty(appKey)) {
+            throw new ServiceException("appKey不能为空");
+        }
+        if (!isValidAppKey(appKey)) {
+            throw new ServiceException("appKey验证失败");
+        }
+
+        /*创建秘钥对*/
+        Map<String, String> keyPair = RsaUtils.createKeyPair();
+        String pk = keyPair.get("pk");
+        String sk = keyPair.get("sk");
+        Long uuid = SnowFlakeUtil.getId();
+
+        Map<String, Object> resultMap = new HashMap<>();
+        try {
+            //存储到Redis,并设置过期时间为2分钟
+            String redisKey = "bm-secret-key:" + uuid;
+            redisTemplate.opsForValue().set(redisKey + ":pk", pk, 2, TimeUnit.MINUTES);
+            redisTemplate.opsForValue().set(redisKey + ":sk", sk, 2, TimeUnit.MINUTES);
+
+            resultMap.put("uuid", uuid);
+            resultMap.put("pk", pk);
+            resultMap.put("code", 200);
+            resultMap.put("msg", "操作成功");
+            return resultMap;
+        } catch (Exception e) {
+            resultMap.put("uuid", null);
+            resultMap.put("pk", null);
+            resultMap.put("code", 400);
+            resultMap.put("msg", e.getMessage());
+            return resultMap;
+        }
+    }
+
+    private boolean isValidAppKey(String appKey) {
+        List<AuthClient> bladeClients = jdbcTemplate.query(
+                "SELECT (1) FROM blade_client WHERE client_id = ?",
+                new Object[]{appKey},
+                new BeanPropertyRowMapper<>(AuthClient.class)
+        );
+        return !bladeClients.isEmpty();
+    }
+
+    /**
+     * 获取token
+     */
+    @PostMapping("/auth/token")
+    public R<Object> getToken(@RequestBody GetTokenDTO dto) {
+        if (dto.getUuid().isEmpty() || dto.getIdcard().isEmpty()) {
+            throw new ServiceException("入参不能为空");
+        }
+
+        /*从Redis中获取私钥*/
+        String redisKey = "bm-secret-key:" + dto.getUuid();
+        String privateKey = redisTemplate.opsForValue().get(redisKey + ":sk");
+
+        if (privateKey != null) {
+            /*解密入参密钥对获取身份证信息*/
+            String decryptedIdCard = RsaUtils.decryptWithSk(dto.getIdcard(), privateKey);
+
+            /*根据身份证获取用户token*/
+            if (StringUtils.isNotEmpty(decryptedIdCard)) {
+                List<User> users = jdbcTemplate.query(
+                        "SELECT account, plaintext_password FROM blade_user WHERE is_deleted = 0 AND status = 1 AND id_number = ?",
+                        new Object[]{decryptedIdCard},
+                        new BeanPropertyRowMapper<>(User.class)
+                );
+
+                if (users.size() > 0 && users.size() != 1) {
+                    throw new ServiceException("获取用户信息异常");
+                } else if (users.size() == 1) {
+                    User user = users.get(0);
+                    HttpClient httpClient = HttpClientBuilder.create().build();
+                    HttpPost httpPost = new HttpPost("http://127.0.0.1:8090/blade-auth/oauth/token");
+                    httpPost.setHeader("Authorization", "Basic Y2xpZW50OmNsaWVudF9zZWNyZXQ=");
+                    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
+                    httpPost.setHeader("Tenant-Id", "000000");
+                    List<NameValuePair> params = new ArrayList<NameValuePair>();
+                    params.add(new BasicNameValuePair("grant_type", "password"));
+                    params.add(new BasicNameValuePair("username", user.getAccount()));
+
+                    /*密码加密*/
+                    String plaintextPassword = user.getPlaintextPassword();
+                    String hex = DigestUtil.md5Hex(plaintextPassword);
+
+                    params.add(new BasicNameValuePair("password", hex));
+                    params.add(new BasicNameValuePair("scope", "all"));
+                    params.add(new BasicNameValuePair("tenantId", "000000"));
+                    httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
+
+                    try {
+                        HttpResponse httpResponse = httpClient.execute(httpPost);
+                        InputStream inputStream = httpResponse.getEntity().getContent();
+                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+                        byte[] buffer = new byte[1024];
+                        int index;
+                        while ((index = inputStream.read(buffer)) != -1) {
+                            outputStream.write(buffer, 0, index);
+                        }
+
+                        JSONObject jsonObject = JSON.parseObject(outputStream.toString());
+                        Object accessToken = jsonObject.get("access_token");
+                        if (accessToken != null) {
+                            Object expiresIn = jsonObject.get("expires_in");
+                            int minutes = 0;
+                            if (expiresIn instanceof Integer) {
+                                int seconds = (Integer) expiresIn;
+                                minutes = seconds / 60;
+                            }
+                            Map<String, Object> resultMap = new HashMap<>();
+                            resultMap.put("access_token", accessToken);
+                            resultMap.put("expires_in", minutes);
+                            return R.data(200, resultMap, "操作成功");
+
+                        } else {
+                            return R.data(400, null, "解析异常,token为空");
+                        }
+
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                        return R.data(500, null, e.getMessage());
+                    }
+                } else {
+                    return R.data(400, null, "未获取到对应的用户信息");
+                }
+            }
+        }
+        return R.data(451, null, "未获取到对应的私钥信息");
+    }
+
+    /*public static void main(String[] args) {
+        //公钥
+        String pk = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJnZ0kMi0AG9sR97sdRD0/kqX9a7kSsVM56DUwmEbxf9n5SW0aRwxYcoyZQUC7ZW2MrXSNbzwbtmdD0RfQ4TJI0CAwEAAQ==";
+
+        //字符串
+        String idcard = "100136199809011400";
+
+        //使用公钥加密
+        String encryptedIdCard = RsaUtils.encryptWithPk(idcard, pk);
+
+        System.out.println("Encrypted Id Card: " + encryptedIdCard);
+    }*/
+
+}
+

+ 209 - 0
blade-service/blade-user/src/main/java/org/springblade/system/user/util/RsaUtils.java

@@ -0,0 +1,209 @@
+package org.springblade.system.user.util;
+
+import javax.crypto.Cipher;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.SecureRandom;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Map;
+
+public final class RsaUtils {
+    /**
+     * 密钥长度 于原文长度对应 以及越长速度越慢
+     */
+    private final static int KEY_SIZE = 512;
+
+    /**
+     * 随机生成密钥对
+     */
+    public static Map<String, String> createKeyPair() {
+        try {
+            Map<String, String> keyMap = new HashMap<>(2);
+            // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
+            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
+            // 初始化密钥对生成器
+            keyPairGen.initialize(KEY_SIZE, new SecureRandom());
+            // 生成一个密钥对,保存在keyPair中
+            KeyPair keyPair = keyPairGen.generateKeyPair();
+            // 得到私钥
+            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
+            // 得到公钥
+            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
+            String publicKeyString = encryptBASE64(publicKey.getEncoded());
+            // 得到私钥字符串
+            String privateKeyString = encryptBASE64(privateKey.getEncoded());
+            // 将公钥和私钥保存到Map
+            keyMap.put("pk", publicKeyString);
+            keyMap.put("sk", privateKeyString);
+            return keyMap;
+        } catch (Exception ex) {
+            throw new RuntimeException("密钥对生成失败");
+        }
+    }
+
+    /**
+     * RSA公钥加密
+     *
+     * @param data      加密字符串
+     * @param publicKey 公钥
+     * @return 密文
+     */
+    public static String encryptWithPk(String data, String publicKey) {
+        try {
+            //base64编码的公钥
+            byte[] decoded = decryptBASE64(publicKey);
+            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
+            //RSA加密
+            Cipher cipher = Cipher.getInstance("RSA");
+            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
+            return encryptBASE64(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
+        } catch (Exception ex) {
+            throw new RuntimeException("数据加密处理失败(encrypt with pk)");
+        }
+    }
+
+    /**
+     * RSA公钥解密
+     *
+     * @param data      加密字符串
+     * @param publicKey 公钥
+     * @return 明文
+     */
+    public static String decryptWithPk(String data, String publicKey) {
+        try {
+            //64位解码加密后的字符串
+            byte[] inputByte = decryptBASE64(data);
+            //base64编码的私钥
+            byte[] decoded = decryptBASE64(publicKey);
+            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
+            //RSA解密
+            Cipher cipher = Cipher.getInstance("RSA");
+            cipher.init(Cipher.DECRYPT_MODE, pubKey);
+            return new String(cipher.doFinal(inputByte));
+        } catch (Exception ex) {
+            throw new RuntimeException("数据解析处理失败(decrypt with pk)");
+        }
+    }
+
+    /**
+     * RSA私钥加密
+     *
+     * @param data       加密字符串
+     * @param privateKey 私钥
+     * @return 密文
+     */
+    public static String encryptWithSk(String data, String privateKey) {
+        try {
+            //base64编码的公钥
+            byte[] decoded = decryptBASE64(privateKey);
+            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
+            //RSA加密
+            Cipher cipher = Cipher.getInstance("RSA");
+            cipher.init(Cipher.ENCRYPT_MODE, priKey);
+            return encryptBASE64(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
+        } catch (Exception ex) {
+            throw new RuntimeException("数据加密处理失败(encrypt with sk)");
+        }
+    }
+
+    /**
+     * RSA私钥解密
+     *
+     * @param data       加密字符串
+     * @param privateKey 私钥
+     * @return 明文
+     */
+    public static String decryptWithSk(String data, String privateKey) {
+        try {
+            //64位解码加密后的字符串
+            byte[] inputByte = decryptBASE64(data);
+            //base64编码的私钥
+            byte[] decoded = decryptBASE64(privateKey);
+            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
+            //RSA解密
+            Cipher cipher = Cipher.getInstance("RSA");
+            cipher.init(Cipher.DECRYPT_MODE, priKey);
+            return new String(cipher.doFinal(inputByte));
+        } catch (Exception ex) {
+            throw new RuntimeException("数据解析处理失败(decrypt with sk)");
+        }
+    }
+
+    /**
+     * 编码返回字符串
+     */
+    private static String encryptBASE64(byte[] key) {
+        try {
+            return Base64.getEncoder().encodeToString(key);
+        } catch (Exception ex) {
+            throw new RuntimeException("编码返回字符串失败");
+        }
+    }
+
+    /**
+     * 解码返回byte
+     */
+    private static byte[] decryptBASE64(String key) {
+        try {
+
+            return Base64.getDecoder().decode(key);
+        } catch (Exception ex) {
+            throw new RuntimeException("解码返回byte失败");
+        }
+    }
+
+    /*private static void testCreateKeyPair() {
+        //生成公钥和私钥
+        Map<String, String> keyMap = createKeyPair();
+        //加密字符串
+        long temp = System.currentTimeMillis();
+        System.out.println("公钥:" + keyMap.get("pk"));
+        System.out.println("私钥:" + keyMap.get("sk"));
+        System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
+
+        String message = "RSA测试aaa";
+        System.out.println("原文:" + message);
+        System.out.println("--------------------------------------");
+        temp = System.currentTimeMillis();
+        String messagePEn = encryptWithPk(message, keyMap.get("pk"));
+        System.out.println("密文:" + messagePEn);
+        System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
+
+        temp = System.currentTimeMillis();
+        String messageSDe = decryptWithSk(messagePEn, keyMap.get("sk"));
+        System.out.println("解密:" + messageSDe);
+        System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
+        System.out.println("--------------------------------------");
+
+        temp = System.currentTimeMillis();
+        String messageSEn = encryptWithSk(message, keyMap.get("sk"));
+        System.out.println("密文:" + messageSEn);
+        System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
+
+        temp = System.currentTimeMillis();
+        String messagePDe = decryptWithPk(messageSEn, keyMap.get("pk"));
+        System.out.println("解密:" + messagePDe);
+        System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
+    }
+
+    public static void main(String[] args) throws Exception {
+        testCreateKeyPair();
+        String pk = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALZL9pOjNpDs1wu15o8xmoeNg4YGCUO5zoLrKiGlmFl7\\r\\nCKXKwJ83pDmu/bE4Szf2RAyzwr33bViqoNH45/EaCrECAwEAAQ==\\r\\n";
+        System.out.println(encryptWithPk("admin", pk));
+        System.out.println(encryptWithPk("admin123", pk));
+
+        String str1 = Base64.getEncoder().encodeToString(pk.getBytes());
+        String str2 = (new BASE64Encoder()).encodeBuffer(pk.getBytes());
+        System.out.println("# " + str1);
+        System.out.println("# " + str2);
+        System.out.println(str1.equals(str2));
+    }*/
+
+}