liuyc 1 an în urmă
părinte
comite
8a16f0f746

+ 0 - 19
blade-service/blade-user/src/main/java/org/springblade/system/user/bean/TripartiteSecretKeyBean.java

@@ -1,19 +0,0 @@
-package org.springblade.system.user.bean;
-
-import com.baomidou.mybatisplus.annotation.TableName;
-import lombok.Data;
-
-import java.io.Serializable;
-import java.util.Date;
-
-@Data
-@TableName("a_tripartite_secret_key")
-public class TripartiteSecretKeyBean implements Serializable {
-
-    private Long uuid;
-    private String publicKey;
-    private String privateKey;
-    private Date createTime;
-    private String appKey;
-
-}

+ 27 - 52
blade-service/blade-user/src/main/java/org/springblade/system/user/thirdparty/ThirdPartySystemApi.java

@@ -13,27 +13,24 @@ 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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 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.bean.TripartiteSecretKeyBean;
 import org.springblade.system.user.entity.User;
 import org.springblade.system.user.util.RsaUtils;
-import org.springblade.system.user.util.TokenBucket;
 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.scheduling.annotation.Scheduled;
 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;
 
 
 /**
@@ -48,17 +45,19 @@ import java.util.*;
 public class ThirdPartySystemApi {
 
     private final JdbcTemplate jdbcTemplate;
-    private static final Logger logger = LoggerFactory.getLogger(ThirdPartySystemApi.class);
-    private final TokenBucket tokenBucket = new TokenBucket(5, 5, 60000); /*令牌桶=60秒5次*/
+    private final RedisTemplate<String, String> redisTemplate;
 
     /**
      * 获取公钥信息
      */
-    @GetMapping("/getPublicKeyAndUUIDByAppKey")
-    public Map<String, Object> getPublicKeyAndUUID(@RequestParam String appKey) {
-        if (!tokenBucket.tryConsume()) {
-            throw new ServiceException("请求频率超过限制,请稍后再试");
+    @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不能为空");
         }
@@ -74,7 +73,16 @@ public class ThirdPartySystemApi {
 
         Map<String, Object> resultMap = new HashMap<>();
         try {
-            insertKeyPairIntoDatabase(uuid, pk, sk, appKey);
+            //存储到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);
@@ -82,11 +90,6 @@ public class ThirdPartySystemApi {
             resultMap.put("msg", e.getMessage());
             return resultMap;
         }
-        resultMap.put("uuid", uuid);
-        resultMap.put("pk", pk);
-        resultMap.put("code", 200);
-        resultMap.put("msg", "操作成功");
-        return resultMap;
     }
 
     private boolean isValidAppKey(String appKey) {
@@ -98,32 +101,21 @@ public class ThirdPartySystemApi {
         return !bladeClients.isEmpty();
     }
 
-    private void insertKeyPairIntoDatabase(Long uuid, String pk, String sk, String appKey) {
-        jdbcTemplate.update(
-                "INSERT INTO a_tripartite_secret_key (uuid, public_key, private_key, create_time, app_key) VALUES (?, ?, ?, ?, ?)",
-                uuid, pk, sk, new Date(), appKey
-        );
-    }
-
     /**
      * 获取token
      */
-    @PostMapping("/getTokenByCondition")
+    @PostMapping("/auth/token")
     public R<Object> getToken(@RequestBody GetTokenDTO dto) {
         if (dto.getUuid().isEmpty() || dto.getIdcard().isEmpty()) {
             throw new ServiceException("入参不能为空");
         }
 
-        /*根据uuid获取私钥*/
-        TripartiteSecretKeyBean tripartiteSecretKey = jdbcTemplate.query(
-                "SELECT private_key FROM a_tripartite_secret_key WHERE uuid = ?",
-                new Object[]{dto.getUuid()},
-                new BeanPropertyRowMapper<>(TripartiteSecretKeyBean.class))
-                .stream().findAny().orElse(null);
+        /*从Redis中获取私钥*/
+        String redisKey = "bm-secret-key:" + dto.getUuid();
+        String privateKey = redisTemplate.opsForValue().get(redisKey + ":sk");
 
-        if (tripartiteSecretKey != null && StringUtils.isNotEmpty(tripartiteSecretKey.getPrivateKey())) {
-            /*解密密钥对获取身份证信息*/
-            String privateKey = tripartiteSecretKey.getPrivateKey();
+        if (privateKey != null) {
+            /*解密入参密钥对获取身份证信息*/
             String decryptedIdCard = RsaUtils.decryptWithSk(dto.getIdcard(), privateKey);
 
             /*根据身份证获取用户token*/
@@ -196,26 +188,9 @@ public class ThirdPartySystemApi {
         return R.data(451, null, "未获取到对应的私钥信息");
     }
 
-    /**
-     * 定时删除昨天及之前的密钥对信息
-     */
-    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨1点执行
-    public void delTripartiteSecretKeyInfos() {
-        //获取昨天及之前的日期
-        Calendar calendar = Calendar.getInstance();
-        calendar.add(Calendar.DAY_OF_MONTH, -1);
-        Date yesterday = calendar.getTime();
-
-        //执行删除操作
-        String sql = "DELETE FROM a_tripartite_secret_key WHERE create_time <= ?";
-        int deletedRows = jdbcTemplate.update(sql, yesterday);
-
-        logger.info("执行方法【delTripartiteSecretKeyInfos】,删除 " + deletedRows + " 条密钥对信息成功...");
-    }
-
     /*public static void main(String[] args) {
         //公钥
-        String pk = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKHbUex3gTpQsaGgMtfWWDwE6LrCETLr8c588diQYHSdVEYbU6A1RnKioGIxGer6G6Cb/81wn6s9Zx833uNf6VkCAwEAAQ==";
+        String pk = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJnZ0kMi0AG9sR97sdRD0/kqX9a7kSsVM56DUwmEbxf9n5SW0aRwxYcoyZQUC7ZW2MrXSNbzwbtmdD0RfQ4TJI0CAwEAAQ==";
 
         //字符串
         String idcard = "100136199809011400";

+ 0 - 41
blade-service/blade-user/src/main/java/org/springblade/system/user/util/TokenBucket.java

@@ -1,41 +0,0 @@
-package org.springblade.system.user.util;
-
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class TokenBucket {
-
-    private final int capacity;
-    private final AtomicInteger tokens;
-    private long lastRefillTime;
-    private final long refillInterval;
-
-    public TokenBucket(int capacity, int tokens, long refillInterval) {
-        this.capacity = capacity;
-        this.tokens = new AtomicInteger(Math.min(tokens, capacity));
-        this.lastRefillTime = System.currentTimeMillis();
-        this.refillInterval = refillInterval;
-    }
-
-    public synchronized boolean tryConsume() {
-        refill();
-        if (tokens.get() > 0) {
-            tokens.decrementAndGet();
-            return true;
-        }
-        return false;
-    }
-
-    private void refill() {
-        long currentTime = System.currentTimeMillis();
-        long timeSinceLastRefill = currentTime - lastRefillTime;
-
-        //计算经过的时间内需要补充的令牌数
-        int newTokens = (int) (timeSinceLastRefill / refillInterval);
-
-        //设置桶中的令牌数,不超过桶的容量
-        tokens.set(Math.min(capacity, tokens.get() + newTokens));
-
-        lastRefillTime = currentTime;
-    }
-
-}