Explorar o código

upadte-更新AES加密方法,并重写返回类tostring方法

liu %!s(int64=3) %!d(string=hai) anos
pai
achega
ee8f679c3b

+ 1 - 5
pom.xml

@@ -18,6 +18,7 @@
     </properties>
     <dependencies>
 
+
         <!-- fastjson -->
         <dependency>
             <groupId>com.alibaba</groupId>
@@ -99,11 +100,6 @@
             <version>1.67</version>
         </dependency>
 
-        <dependency>
-            <groupId>commons-lang</groupId>
-            <artifactId>commons-lang</artifactId>
-            <version>2.6</version>
-        </dependency>
 
     </dependencies>
 

+ 17 - 0
src/main/java/com/example/faceverification/Dto/DataDto.java

@@ -0,0 +1,17 @@
+package com.example.faceverification.Dto;
+
+import lombok.Data;
+
+@Data
+public class DataDto {
+//    图片
+    private String url;
+//    姓名
+    private String name;
+//    身份证号
+    private String idCard;
+//    类别
+    private String category;
+//    学工号
+    private String studentNumber;
+}

+ 10 - 10
src/main/java/com/example/faceverification/aop/EncryptAOP.java

@@ -2,17 +2,17 @@ package com.example.faceverification.aop;
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
-import com.baomidou.mybatisplus.extension.api.R;
 import com.example.faceverification.annotation.Encrypt;
 import com.example.faceverification.core.RequestWrapper;
-import com.example.faceverification.utils.AesUtils;
+import com.example.faceverification.response.BaseResponse;
+import com.example.faceverification.response.enums.StatusEnum;
+import com.example.faceverification.utils.AES;
 import com.example.faceverification.utils.ServletUtil;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
-import org.aspectj.lang.annotation.Before;
 import org.aspectj.lang.annotation.Pointcut;
-import org.bouncycastle.jcajce.provider.symmetric.AES;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.core.annotation.Order;
 import org.springframework.stereotype.Component;
 
@@ -32,6 +32,8 @@ import javax.servlet.http.HttpServletRequest;
 @Component
 public class EncryptAOP {
 
+    @Value("${aes-key}")
+    public String aesKey;
 
 
     @Pointcut("@annotation(com.example.faceverification.annotation.Encrypt)")
@@ -42,7 +44,7 @@ public class EncryptAOP {
      *  环绕增强,加密出参
      * */
     @Around(value = "point() && @annotation(encrypt)")
-    public Object around (ProceedingJoinPoint joinPoint , Encrypt encrypt) throws Throwable {
+    public BaseResponse around (ProceedingJoinPoint joinPoint , Encrypt encrypt) throws Throwable {
         //返回的结果
         Object returnValue = null;
         //从当前上下文提取request
@@ -60,13 +62,11 @@ public class EncryptAOP {
             returnValue = joinPoint.proceed();
         }
 
-        //把接口的出参,用前端此次传过来的AES密钥进行加密,然后返回
-//        JSONObject jsonObject = JSON.parseObject(body);
-        String encryptData = AesUtils.encrypt(returnValue.toString() , "6edfcc178c0f415d8e6628238761976f");
+        String encryptData = AES.encryptToBase64(returnValue.toString(), aesKey);
 
-        returnValue=encryptData;
-        return returnValue;
+        return BaseResponse.ok(StatusEnum.SUCCESS,encryptData);
     }
 
 
+
 }

+ 3 - 1
src/main/java/com/example/faceverification/api/IdentityComparisonRecordControllerAPI.java

@@ -1,5 +1,7 @@
 package com.example.faceverification.api;
 
+import com.example.faceverification.Dto.DataDto;
+import com.example.faceverification.response.BaseResponse;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -8,6 +10,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
 public interface IdentityComparisonRecordControllerAPI {
 
 
-    String test(String name);
+    BaseResponse comparison(DataDto name);
 
 }

+ 96 - 0
src/main/java/com/example/faceverification/config/SearchByImageConfig.java

@@ -0,0 +1,96 @@
+package com.example.faceverification.config;
+
+
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.TypeReference;
+import com.example.faceverification.utils.BaseClass;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.util.Map;
+
+public class SearchByImageConfig extends BaseClass {
+
+    /**
+     * 创建以图搜图
+     * @param dateMap
+     * @param requestMode
+     * @param reqBody
+     * @param urlString
+     * @return
+     */
+
+    public static Map<String, Object> searchByImageRecord(Map<String, Object> dateMap, String requestMode, String reqBody, String urlString) {
+        String url = getNvrUrl() + urlString;
+        CloseableHttpClient httpClient = HttpClients.custom().build();
+
+        JSONObject jsonOParam = JSONObject.parseObject(reqBody);
+
+        //不带鉴权信息调用login,获取nonce;调用接口时必须调用/LAPI/V1.0/System/Security/Login
+        CloseableHttpResponse resp = doPut(httpClient, getLoginUrl(), "", "");
+
+        //从第一次调用中获取nonce值
+        String nonce = getMatch("nonce=\"(.*)\",stale", getHeaderinfo(resp, "WWW-Authenticate"));
+        //生成cnonce
+        String cnonce = getCnonce();
+
+        //计算报文头中Authorization字段信息
+        String curAuthorization = getAuthRespInfo(getNvrName(), getNvrPwd(), urlString, nonce, cnonce, requestMode);
+
+        //System.out.println(curAuthorization);
+
+        CloseableHttpResponse resp2;
+        //带鉴权信息调用业务接口
+        if (requestMode.equals("POST")) {
+            resp2 = doPost(httpClient, url, curAuthorization, reqBody);
+        } else if ("DELETE".equals(requestMode)){
+            resp2=doDelete(httpClient, url, curAuthorization, reqBody);
+        }else if ("GET".equals(requestMode)){
+            resp2=doGet(httpClient,url,curAuthorization);
+        } else {
+            resp2 = doPut(httpClient, url, curAuthorization, reqBody);
+        }
+        HttpEntity entity = resp2.getEntity();
+
+        try {
+            String responString = EntityUtils.toString(entity);
+            //解析response中body,获取相关字段的值
+            JSONObject body = JSONObject.parseObject(responString);
+            JSONObject response = JSONObject.parseObject(body.getString("Response"));
+            String ResponseString = response.getString("ResponseString");
+            String data = response.getString("Data");
+            JSONObject jsonObject = JSONObject.parseObject(data);
+            if ("Succeed".equals(ResponseString)) {
+                dateMap = JSONObject.parseObject(jsonObject.toString(),new TypeReference<Map<String, String>>(){});
+            }
+        } catch (Exception e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } finally {
+            // 关闭相关资源
+            if (null != resp) {
+                try {
+                    resp.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+            if (null != resp2) {
+                try {
+                    resp2.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+        return dateMap;
+    }
+
+
+
+
+}

+ 19 - 5
src/main/java/com/example/faceverification/controller/IdentityComparisonRecordController.java

@@ -1,14 +1,22 @@
 package com.example.faceverification.controller;
 
 
+import com.example.faceverification.Dto.DataDto;
 import com.example.faceverification.annotation.Encrypt;
 import com.example.faceverification.api.IdentityComparisonRecordControllerAPI;
+import com.example.faceverification.response.BaseResponse;
+import com.example.faceverification.service.IdentityComparisonRecordService;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 
 import org.springframework.web.bind.annotation.RestController;
 
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+
 /**
  * <p>
  *  前端控制器
@@ -21,14 +29,20 @@ import org.springframework.web.bind.annotation.RestController;
 @RequestMapping("/api/identity-comparison-record")
 public class IdentityComparisonRecordController implements IdentityComparisonRecordControllerAPI {
 
+    @Autowired
+    IdentityComparisonRecordService identityComparisonRecordService;
 
     @Override
-    @PostMapping("/test")
+    @PostMapping("/comparison")
     @Encrypt
-    public String test(@RequestBody String name) {
-        System.out.println("name = " + name);
-        System.out.println("测试");
-        return "123456";
+    public BaseResponse comparison(@RequestBody DataDto data) {
+
+       return identityComparisonRecordService.comparison(data);
     }
+
+
+
+
+
 }
 

+ 9 - 10
src/main/java/com/example/faceverification/core/ReplaceStreamFilter.java

@@ -2,7 +2,7 @@ package com.example.faceverification.core;
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
-import com.example.faceverification.utils.AesUtils;
+import com.example.faceverification.utils.AES;
 import com.example.faceverification.utils.RSAUtils;
 import lombok.SneakyThrows;
 import lombok.extern.slf4j.Slf4j;
@@ -23,7 +23,8 @@ import java.io.IOException;
 public class ReplaceStreamFilter implements Filter {
     @Value("${my-security.privateKey}")
     public String privateKey;
- 
+    @Value("${aes-key}")
+    public String aesKey;
     @SneakyThrows
     @Override
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
@@ -36,8 +37,6 @@ public class ReplaceStreamFilter implements Filter {
             return;
         }
 
-
-
         //读出json请求体
         StringBuffer buffer = new StringBuffer();
         String line = null;
@@ -51,18 +50,18 @@ public class ReplaceStreamFilter implements Filter {
         JSONObject jsonObject = JSON.parseObject(buffer.toString());
         //得到的密文
         String data = jsonObject.getString("data");
-
+        //先用RSA解密,得到AES加密的数据
         String decrypt = RSAUtils.decrypt(data, RSAUtils.getPrivateKey(privateKey));
-        //再用AES的key解密数据
-        AesUtils.decrypt(decrypt,"");
-
+        //再用AES解密数据
+         decrypt = AES.decryptFromBase64(decrypt, aesKey);
+        System.out.println("decrypt = " + decrypt);
         //把解密之后的aesKey一并交给下游,方便在AOP对出参加密
 //        jsonObject = JSON.parseObject(data);
 //        jsonObject.put("aesKey" , aesKey);
 
         //重置json请求体,保证下游业务无感知获取数据
-        requestWrapper.setBody(jsonObject.toJSONString().getBytes());
-       
+        requestWrapper.setBody(decrypt.getBytes());
+
         chain.doFilter(requestWrapper, response);
     }
  

+ 3 - 1
src/main/java/com/example/faceverification/model/IdentityComparisonRecord.java

@@ -37,11 +37,13 @@ public class IdentityComparisonRecord implements Serializable {
     private String identityCard;
 
 
-    private Integer studentNumber;
+    private String studentNumber;
 
 
     private String category;
 
+    private Integer results;
+
 
     @TableField(fill = FieldFill.INSERT)
     private Date createTime;

+ 72 - 0
src/main/java/com/example/faceverification/response/BaseResponse.java

@@ -0,0 +1,72 @@
+package com.example.faceverification.response;
+
+
+import com.alibaba.fastjson.JSONObject;
+import com.example.faceverification.response.enums.Code;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.Data;
+
+import java.io.Serializable;
+
+@Data
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class BaseResponse<T> implements Serializable {
+    private Integer status;
+    private  String desc;
+    private T data;
+
+    private String authorization;
+
+
+    @Override
+    public String toString() {
+        JSONObject map = new JSONObject();
+        map.put("status",status);
+        map.put("desc",desc);
+        map.put("data",data);
+        map.put("authorization",authorization);
+        return map.toJSONString();
+    }
+
+    public BaseResponse(Code code, T data, String authorization) {
+        this.status = code.getStatus();
+        this.desc = code.getDesc();
+        this.data = data;
+        this.authorization = authorization;
+    }
+
+    public static<T> BaseResponse<T> ok (Code code, T data, String authorization) {
+      return new BaseResponse(code,data,authorization);
+    }
+
+    public static<T> BaseResponse<T> ok (Code code, T data) {
+        return new BaseResponse(code,data,null);
+    }
+
+    public static<T> BaseResponse<T> ok (Code code, String authorization) {
+        return new BaseResponse(code,null,authorization);
+    }
+
+    public static<T> BaseResponse<T> ok (Code code) {
+        return new BaseResponse(code,null,null);
+    }
+
+    public static<T> BaseResponse<T> error (Code code) {
+        return ok(code,null,null);
+    }
+    public static<T> BaseResponse<T> error (Code code, T data) {
+        return ok(code,data,null);
+    }
+
+    public static BaseResponse error(Integer status, String desc){
+        BaseResponse tBaseResponseResult =  new BaseResponse();
+        tBaseResponseResult.setStatus(status);
+        tBaseResponseResult.setDesc(desc);
+        return tBaseResponseResult;
+    }
+
+    private BaseResponse() {
+    }
+
+
+}

+ 6 - 0
src/main/java/com/example/faceverification/response/enums/Code.java

@@ -0,0 +1,6 @@
+package com.example.faceverification.response.enums;
+
+public interface Code {
+    Integer getStatus();
+    String getDesc();
+}

+ 34 - 0
src/main/java/com/example/faceverification/response/enums/StatusEnum.java

@@ -0,0 +1,34 @@
+package com.example.faceverification.response.enums;
+
+public enum StatusEnum implements Code {
+    SUCCESS(200, "操作成功"),
+    FAIL(501,"操作失败 "),
+    SUCCESS_ADD(202,"添加成功"),
+    FAIL_ADD(502,"添加失败"),
+    SUCCESS_UPDATE(203, "修改成功"),
+    FAIL_UPDATE(503,"修改失败 "),
+    SUCCESS_DELETE(204, "删除成功"),
+    FAIL_DELETE(504,"删除失败 "),
+    SUCCESS_SELECT(205, "查询成功"),
+    FAIL_SELECT(505,"查询失败 "),
+    FACE_SUCCESS(200,"对比成功"),
+    FACE_FAIL(500,"对比失败"),
+    PARAMETER_FAIL(500,"参数错误");
+    private Integer status;
+    private String desc;
+
+    private StatusEnum(Integer status, String desc) {
+        this.status = status;
+        this.desc = desc;
+    }
+
+    @Override
+    public Integer getStatus() {
+        return status;
+    }
+
+    @Override
+    public String getDesc() {
+        return desc;
+    }
+}

+ 4 - 0
src/main/java/com/example/faceverification/service/IdentityComparisonRecordService.java

@@ -1,7 +1,9 @@
 package com.example.faceverification.service;
 
+import com.example.faceverification.Dto.DataDto;
 import com.example.faceverification.model.IdentityComparisonRecord;
 import com.baomidou.mybatisplus.extension.service.IService;
+import com.example.faceverification.response.BaseResponse;
 
 /**
  * <p>
@@ -13,4 +15,6 @@ import com.baomidou.mybatisplus.extension.service.IService;
  */
 public interface IdentityComparisonRecordService extends IService<IdentityComparisonRecord> {
 
+    BaseResponse comparison(DataDto data);
+
 }

+ 223 - 1
src/main/java/com/example/faceverification/service/impl/IdentityComparisonRecordServiceImpl.java

@@ -1,20 +1,242 @@
 package com.example.faceverification.service.impl;
 
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
+import com.example.faceverification.Dto.DataDto;
+import com.example.faceverification.config.SearchByImageConfig;
 import com.example.faceverification.model.IdentityComparisonRecord;
 import com.example.faceverification.mapper.IdentityComparisonRecordMapper;
+import com.example.faceverification.response.BaseResponse;
+import com.example.faceverification.response.enums.StatusEnum;
 import com.example.faceverification.service.IdentityComparisonRecordService;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.example.faceverification.utils.Base64Utils;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Service;
 
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
 /**
  * <p>
- *  服务实现类
+ * 服务实现类
  * </p>
  *
  * @author ceshi
  * @since 2023-04-27
  */
 @Service
+@Slf4j
 public class IdentityComparisonRecordServiceImpl extends ServiceImpl<IdentityComparisonRecordMapper, IdentityComparisonRecord> implements IdentityComparisonRecordService {
+    String taskId = "";
+
+    @Override
+    public synchronized BaseResponse comparison(DataDto data) {
+        log.info("人脸开始对比");
+        if (ObjectUtils.isEmpty(data)) {
+            return BaseResponse.error(StatusEnum.PARAMETER_FAIL);
+        }
+        Map<String, Object> query = null;
+        IdentityComparisonRecord comparisonRecord = new IdentityComparisonRecord();
+        comparisonRecord.setName(data.getName());
+        comparisonRecord.setCategory(data.getCategory());
+        comparisonRecord.setPictureUrl(data.getUrl());
+        comparisonRecord.setIdentityCard(data.getIdCard());
+        comparisonRecord.setStudentNumber(data.getStudentNumber());
+        comparisonRecord.setDeleted(0L);
+        synchronized (this) {
+            String url = data.getUrl();
+            try {
+
+                String s = taskID();
+                target(s, url);
+                control(s);
+                //        获取进度
+                String s1 = get(s);
+                while (!"100".equals(s1)) {
+                    s1 = get(s);
+                }
+                query = query(s);
+                String s2 = query.get("Total").toString();
+                Integer integer = Integer.valueOf(s2);
+                if (0>=integer) {
+                    log.info("人脸对比失败");
+                    comparisonRecord.setResults(1);
+                    this.save(comparisonRecord);
+                    return  BaseResponse.error(StatusEnum.FACE_FAIL);
+                }
+
+                String personList = query.get("PersonList").toString();
+                JSONArray jsonArray = JSONArray.parseArray(personList);
+                for (int i = 0; i < jsonArray.size(); i++) {
+                    JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
+                    JSONObject targetInfo = jsonObject.getJSONObject("TargetInfo");
+//                    获取姓名
+                    String personName = targetInfo.getString("PersonName");
+                    log.info("找到对比图片的姓名【{}】",personName);
+//                    获取证件号
+                    JSONArray identificationList = jsonObject.getJSONArray("IdentificationList");
+                    if (ObjectUtils.isNotEmpty(identificationList)) {
+                        for (int j = 0; j < identificationList.size(); j++) {
+                            JSONObject jsonObject1 = JSONObject.parseObject(identificationList.get(j).toString());
+                            String number = jsonObject1.getString("Number");
+                            log.info("找到对比图片的证件号【{}】",number);
+                            if (data.getIdCard().equals(number)||data.getStudentNumber().equals(number)) {
+                                comparisonRecord.setResults(0);
+                                this.save(comparisonRecord);
+                                return BaseResponse.ok(StatusEnum.FACE_SUCCESS);
+                            }
+                        }
+                    }
+                    if (data.getName().equals(personName)) {
+                        log.info("人脸对比成功");
+                        comparisonRecord.setResults(0);
+                        this.save(comparisonRecord);
+                        return BaseResponse.ok(StatusEnum.FACE_SUCCESS);
+                    }
+                }
+
+            } catch (Exception e) {
+                log.error("人脸对比报错");
+            } finally {
+                delect(taskId);
+            }
+        }
+
+        comparisonRecord.setResults(1);
+        log.info("人脸对比失败");
+        this.save(comparisonRecord);
+        return BaseResponse.error(StatusEnum.FACE_FAIL);
+    }
+
+    /**
+     * 创建图搜任务
+     *
+     * @return
+     */
+    public String taskID() {
+        HashMap<String, Object> map = new HashMap<>();
+        Map<String, Object> post = SearchByImageConfig.searchByImageRecord(map, "POST", "", "/LAPI/V1.0/Smart/SearchByImage/Task");
+        taskId = post.get("TaskId").toString();
+        return taskId;
+    }
+
+
+    public Map target(String id, String url) {
+//        添加检索参数
+        Map<String, Object> FileInfo = new HashMap<String, Object>();
+        FileInfo.put("Type", 1);
+        String s = Base64Utils.imageUrlToBase64(url);
+//        String s = Base64Utils.GetImageStr(url);
+        s = s.replace("\r\n", "")/*.replace("+","")*/;
+
+        FileInfo.put("Size", s.length());
+
+        FileInfo.put("Data", s);
+
+
+        ArrayList<Map> FileInfos = new ArrayList<>();
+        FileInfos.add(FileInfo);
+
+        Map<String, Object> TargetInfo = new HashMap<String, Object>();
+        TargetInfo.put("SimilarityThreshold", 80);
+        TargetInfo.put("TargetInfoList", FileInfos);
+        TargetInfo.put("TargetNum", 1);
+
+        HashMap<String, Object> SearchTarget = new HashMap<String, Object>();
+        SearchTarget.put("TargetInfo", TargetInfo);
+
+        Map<String, Object> CompareLib = new HashMap<String, Object>();
+        CompareLib.put("LibType", 0);
+        ArrayList<Integer> strings = new ArrayList<>();
+        HashMap<String, Object> map1 = new HashMap<>();
+        Map<String, Object> get = SearchByImageConfig.searchByImageRecord(map1, "GET", "", "/LAPI/V1.0/PeopleLibraries/BasicInfo");
+        String num = get.get("Num").toString();
+        JSONArray jsonObject = JSONObject.parseArray(get.get("LibList").toString());
+        for (int i = 0; i < jsonObject.size(); i++) {
+            Map map = JSONObject.parseObject(jsonObject.get(i).toString(), Map.class);
+            String id1 = map.get("ID").toString();
+            strings.add(Integer.valueOf(id1));
+        }
+        CompareLib.put("LibNum", num);
+        CompareLib.put("LibList", strings);
+
+        Map<String, Object> CompareTarget = new HashMap<String, Object>();
+        CompareTarget.put("Type", 1);
+        CompareTarget.put("CompareLib", CompareLib);
+
+
+        JSONObject map2 = new JSONObject();
+        map2.put("SearchTarget", SearchTarget);
+        map2.put("CompareTarget", CompareTarget);
+        String jsonString = map2.toJSONString();
+
+        HashMap<String, Object> map = new HashMap<>();
+        Map<String, Object> post1 = SearchByImageConfig.searchByImageRecord(map, "POST", jsonString, "/LAPI/V1.0/Smart/SearchByImage/Task/" + id + "/Target");
+
+        return post1;
+
+
+    }
+
+    /**
+     * 启动
+     *
+     * @param id
+     * @return
+     */
+    public void control(String id) {
+        //        启动
+        JSONObject jsonObject1 = new JSONObject();
+        jsonObject1.put("Control", 0);
+        String s = jsonObject1.toJSONString();
+        HashMap<String, Object> map3 = new HashMap<>();
+        Map<String, Object> put = SearchByImageConfig.searchByImageRecord(map3, "PUT", s, "/LAPI/V1.0/Smart/SearchByImage/Task/" + id + "/Control");
+
+    }
+
+
+    /**
+     * 获取进度
+     *
+     * @param id
+     * @return
+     */
+    public String get(String id) {
+        HashMap<String, Object> map = new HashMap<>();
+        Map<String, Object> get = SearchByImageConfig.searchByImageRecord(map, "GET", "", "/LAPI/V1.0/Smart/SearchByImage/Progress?TaskID=" + id);
+        String percent = get.get("Percent").toString();
+        return percent;
+    }
+
+    /**
+     * 获取对比结果
+     *
+     * @param id
+     * @return
+     */
+    public Map<String, Object> query(String id) {
+        HashMap<String, Object> map = new HashMap<>();
+
+        Map<String, Object> get = SearchByImageConfig.searchByImageRecord(map, "GET", "", "/LAPI/V1.0/Smart/SearchByImage/Query?Task=" + id + "&Limit=12&Offset=0");
+        return get;
+    }
+
+
+    /**
+     * 删除图搜任务
+     *
+     * @param id
+     * @return
+     */
+    public void delect(String id) {
+        HashMap<String, Object> map = new HashMap<>();
+        Map<String, Object> post = SearchByImageConfig.searchByImageRecord(map, "DELETE", "", "/LAPI/V1.0/Smart/SearchByImage/Task/" + id);
+    }
+
 
 }

+ 184 - 0
src/main/java/com/example/faceverification/utils/AES.java

@@ -0,0 +1,184 @@
+package com.example.faceverification.utils;
+
+
+import org.bouncycastle.util.encoders.Base64;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.UnsupportedEncodingException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Random;
+
+/**
+ * 	AES加密解密
+ */
+public class AES {
+    public static final String CHAR_ENCODING = "UTF-8";
+    public static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
+	private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+	/**
+	 * 随机生成AESKey
+	 * @return string
+	 */
+	public static String getAESKey(int length) throws Exception {
+		Random random = new Random();
+		StringBuilder ret = new StringBuilder();
+		for (int i = 0; i < length; i++) {
+			boolean isChar = (random.nextInt(2) % 2 == 0);// 输出字母还是数字
+			if (isChar) { // 字符串
+				int choice = (random.nextInt(2) % 2 == 0) ? 65 : 97; // 取得大写字母还是小写字母
+				ret.append((char) (choice + random.nextInt(26)));
+			} else { // 数字
+				ret.append((random.nextInt(10)));
+			}
+		}
+		return ret.toString();
+	}
+
+	/**
+	 * 加密
+	 * 
+	 * @param / content
+	 *            需要加密的内容
+	 * @param /password
+	 *            加密密码
+	 * @return
+	 */
+	public static byte[] encrypt(byte[] data, byte[] key) {
+		if(key.length!=16){
+			throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
+		}
+		try {
+			SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); 
+			byte[] enCodeFormat = secretKey.getEncoded();
+			SecretKeySpec seckey = new SecretKeySpec(enCodeFormat,"AES");
+			Cipher cipher = Cipher.getInstance(AES_ALGORITHM);// 创建密码器
+			cipher.init(Cipher.ENCRYPT_MODE, seckey);// 初始化
+			byte[] result = cipher.doFinal(data);
+			return result; // 加密
+		} catch (Exception e){
+			throw new RuntimeException("encrypt fail!", e);
+		}
+	}
+
+	/**
+	 * 解密
+	 * 
+	 * @param / content
+	 *            待解密内容
+	 * @param /password
+	 *            解密密钥
+	 * @return
+	 */
+	public static byte[] decrypt(byte[] data, byte[] key) {
+		if(key.length!=16){
+			throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
+		}
+		try {
+			SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); 
+			byte[] enCodeFormat = secretKey.getEncoded();
+			SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
+			Cipher cipher = Cipher.getInstance(AES_ALGORITHM);// 创建密码器
+			cipher.init(Cipher.DECRYPT_MODE, seckey);// 初始化
+			byte[] result = cipher.doFinal(data);
+			return result; // 加密
+		} catch (Exception e){
+			throw new RuntimeException("decrypt fail!", e);
+		}
+	}
+	//	//加密
+	public static String encryptToBase64(String data, String key){
+		try {
+			byte[] valueByte = encrypt(data.getBytes(CHAR_ENCODING), key.getBytes(CHAR_ENCODING));
+			return new String(Base64.encode(valueByte));
+		} catch (UnsupportedEncodingException e) {
+			throw new RuntimeException("encrypt fail!", e);
+		}
+		
+	}
+	//	解密
+	public static String decryptFromBase64(String data, String key){
+		try {
+			byte[] originalData = Base64.decode(data.getBytes());
+			byte[] valueByte = decrypt(originalData, key.getBytes(CHAR_ENCODING));
+			return new String(valueByte, CHAR_ENCODING);
+		} catch (UnsupportedEncodingException e) {
+			throw new RuntimeException("decrypt fail!", e);
+		}
+	}
+
+
+	public static String encryptWithKeyBase64(String data, String key){
+		try {
+			byte[] valueByte = encrypt(data.getBytes(CHAR_ENCODING), Base64.decode(key.getBytes()));
+			return new String(Base64.encode(valueByte));
+		} catch (UnsupportedEncodingException e) {
+			throw new RuntimeException("encrypt fail!", e);
+		}
+	}
+
+
+	public static String decryptWithKeyBase64(String data, String key){
+		try {
+			byte[] originalData = Base64.decode(data.getBytes());
+			byte[] valueByte = decrypt(originalData, Base64.decode(key.getBytes()));
+			return new String(valueByte, CHAR_ENCODING);
+		} catch (UnsupportedEncodingException e) {
+			throw new RuntimeException("decrypt fail!", e);
+		}
+	}
+	
+	public static byte[] genarateRandomKey(){
+		KeyGenerator keygen = null;
+		try {
+			keygen = KeyGenerator.getInstance(AES_ALGORITHM);
+		} catch (NoSuchAlgorithmException e) {
+			throw new RuntimeException(" genarateRandomKey fail!", e);
+		}
+		SecureRandom random = new SecureRandom();
+		keygen.init(random);
+		Key key = keygen.generateKey();
+		return key.getEncoded();
+	}
+	
+	public static String genarateRandomKeyWithBase64(){
+		return new String(Base64.encode(genarateRandomKey()));
+	}
+
+	public static void main(String[] args) throws Exception {
+		String aesKey = getAESKey(16);
+		System.out.println("aesKey = " + aesKey);
+
+
+		String key="Vl3726F2RE62zPjH";
+
+//		String ss="https://chtech.ncjti.edu.cn/campusclock/attendance-media/1683595495359_wcbm4bxzrq.jpg";
+		String ss="{\n" +
+				"    \"url\" : \"https://chtech.ncjti.edu.cn/campusclock/attendance-media/1683595495359_wcbm4bxzrq.jpg\" ,\n" +
+				"    \"name\" : \"周祥\" ,\n" +
+				"    \"idCard\" : \"123456789101112131\" ,\n" +
+				"    \"category\" : \"打卡签到\" ,\n" +
+				"    \"studentNumber\" : \"45146054656461\" \n" +
+				"}";
+//		加密
+		String encrypt = encryptToBase64(ss, key);
+		System.out.println("encrypt = " + encrypt);
+
+
+
+		String s="qedS5LjKuPlHHLTiy657GYAAPWslki6rv8AbgN6hqDZLM2Rbgd5XilvOUivIRCHxQJeQeKd2ydDj621GcO6HNVIz3wBtIrUwhe0TJm7kfIfuRQXuo2QVZtX7/S6KowSU";
+//		String s="UtoBNp9fICucUkBimiClN3z5Tz7o0KLiwJ9z50zjOiWNcnqYZ/p/awyi01nDEmxOShfMZFTd9uWkWM7fNPHotvsGhxAdHZNiv3WOMYWzuHIDu27iNcH9tkZhEIr72EFo";
+//		解密
+		String decrypt = decryptFromBase64("MQdw2zW/srXr5Lm/vntgQ8rlW6gin+/VKfb9aKi36nyiEtwg1hORSLOTm9y0m8WxpLoECkMeDa0WQevMHmkNGQajYMrDRhGho6jGGvdNdQVRQXNSWGRZgQTg3ycq1cxT", key);
+		System.out.println("decrypt = " + decrypt);
+
+
+
+
+
+	}
+
+}

+ 0 - 209
src/main/java/com/example/faceverification/utils/AesUtils.java

@@ -1,209 +0,0 @@
-package com.example.faceverification.utils;
-
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang.StringUtils;
-import org.bouncycastle.util.encoders.Base64;
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.spec.SecretKeySpec;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * @Author: liujun
- * @Description: Aes 加解密算法
- * @Date Create in 上午 9:38$ 2017/12/26 0026$
- * @Modify By:
- */
-@Slf4j
-public class AesUtils {
-    /**
-     * @Author liujun
-     * @Description:
-     * @params: * @param content 需要加密的内容
-     * @param password  加密密码
-     * @Date 上午 9:41 2017/12/26 0026
-     */
-
-    public static String encrypt(String content, String password) {
-        //数据为空,不需要进行加解密,否则会出现空指针异常
-        if(StringUtils.isEmpty(content)) {
-            return null;
-        }
-
-        if(password.length()<16) {
-            password = password + "0000000000000000".substring(0, 16-password.length());
-        }
-        else if(password.length()>16) {
-            password = password.substring(0, 16);
-        }
-
-        return bytes2HexString(encryptAES(content.getBytes(), password.getBytes()));
-    }
-
-
-    /**
-     * @Author liujun
-     * @Description:
-     * @params: * @param content 待解密内容
-     * @param password 解密密钥
-     * @Date 上午 9:40 2017/12/26 0026
-     */
-    public static String decrypt(String content, String password) {
-        //数据为空,不需要进行加解密,否则会出现空指针异常
-        if(StringUtils.isEmpty(content)) {
-            return null;
-        }
-
-        if(password.length()<16) {
-            password = password + "0000000000000000".substring(0, 16-password.length());
-        }
-        else if(password.length()>16) {
-            password = password.substring(0, 16);
-        }
-
-        return new String(decryptAES(hexString2Bytes(content), password.getBytes()));
-    }
-
-    /**
-     * AES 加密
-     *
-     * @param data 明文
-     * @param key  16、24、32 字节秘钥
-     * @return 密文
-     */
-    public static byte[] encryptAES(final byte[] data,
-                                    final byte[] key) {
-
-        try {
-            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
-            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
-            byte[] byteContent = data;
-            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
-            byte[] result = cipher.doFinal(byteContent);
-            return result; // 加密
-        } catch (NoSuchAlgorithmException e) {
-            log.error(e.getMessage(),e);
-        } catch (NoSuchPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (InvalidKeyException e) {
-            log.error(e.getMessage(),e);
-        } catch (IllegalBlockSizeException e) {
-            log.error(e.getMessage(),e);
-        } catch (BadPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (Exception e) {
-            log.error(e.getMessage(),e);
-        }
-        return null;
-    }
-
-    /**
-     * AES 解密
-     *
-     * @param data 密文
-     * @param key  16、24、32 字节秘钥
-     * @return 明文
-     */
-    public static byte[] decryptAES(final byte[] data,
-                                    final byte[] key) {
-
-        try {
-            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
-            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
-            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化
-            byte[] result = cipher.doFinal(data);
-            return result; // 加密
-        } catch (NoSuchAlgorithmException e) {
-            log.error(e.getMessage(),e);
-        } catch (NoSuchPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (InvalidKeyException e) {
-            log.error(e.getMessage(),e);
-        } catch (IllegalBlockSizeException e) {
-            log.error(e.getMessage(),e);
-        } catch (BadPaddingException e) {
-            log.error(e.getMessage(),e);
-        } catch (Exception e) {
-            log.error(e.getMessage(),e);
-        }
-        return null;
-    }
-
-    public static String bytes2HexString(final byte[] bytes) {
-        if (bytes == null) return null;
-        int len = bytes.length;
-        if (len <= 0) return null;
-        char[] ret = new char[len << 1];
-        for (int i = 0, j = 0; i < len; i++) {
-            ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f];
-            ret[j++] = hexDigits[bytes[i] & 0x0f];
-        }
-        return new String(ret);
-    }
-
-    private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
-
-    public static byte[] hexString2Bytes(String hexString) {
-        if (isSpace(hexString)) return null;
-        int len = hexString.length();
-        if (len % 2 != 0) {
-            hexString = "0" + hexString;
-            len = len + 1;
-        }
-        char[] hexBytes = hexString.toUpperCase().toCharArray();
-        byte[] ret = new byte[len >> 1];
-        for (int i = 0; i < len; i += 2) {
-            ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
-        }
-        return ret;
-    }
-
-    private static int hex2Dec(final char hexChar) {
-        if (hexChar >= '0' && hexChar <= '9') {
-            return hexChar - '0';
-        } else if (hexChar >= 'A' && hexChar <= 'F') {
-            return hexChar - 'A' + 10;
-        } else {
-            throw new IllegalArgumentException();
-        }
-    }
-
-    public static byte[] base64Encode(final byte[] input) {
-        return Base64.encode(input);
-    }
-
-    public static byte[] base64Decode(final byte[] input) {
-
-        return Base64.decode(input);
-    }
-
-    private static boolean isSpace(final String s) {
-        if (s == null) return true;
-        for (int i = 0, len = s.length(); i < len; ++i) {
-            if (!Character.isWhitespace(s.charAt(i))) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    public static void main(String[] args) {
-        String s="{\n" +
-                "  \"categoryId\": \"d0c248256f8346d2a19afa296562b319\",\n" +
-                "     \"luid\": \"80A036AE25AC\",\n" +
-                "     \"type\":\"5\",\n" +
-                "     \"userName\":\"13097286670\",\n" +
-                "\"startTime\":\"1682498606000\",\n" +
-                "     \"endTime\":\"1684981484000\"\n" +
-                "}";
-        //加密
-        String encryptString = AesUtils.encrypt(s, "6edfcc178c0f415d8e6628238761976f");
-        System.out.println("加密后字符串:"+encryptString);
-        //解密
-        String decryptString = AesUtils.decrypt(encryptString, "6edfcc178c0f415d8e6628238761976f");
-        System.out.println("解密后字符串:"+decryptString);
-    }
-}

+ 185 - 0
src/main/java/com/example/faceverification/utils/Base64Utils.java

@@ -0,0 +1,185 @@
+package com.example.faceverification.utils;
+
+import org.apache.commons.lang.StringUtils;
+import sun.misc.BASE64Decoder;
+import sun.misc.BASE64Encoder;
+import sun.net.www.protocol.http.HttpURLConnection;
+
+import javax.net.ssl.HttpsURLConnection;
+import java.io.*;
+import java.net.URL;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Base64Utils {
+    /**
+     * 本地 图片转化成base64字符串
+     * @param imgPath
+     * @return
+     */
+    public static String GetImageStr(String imgPath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
+
+
+//        String imgFile = imgPath;// 待处理的图片
+        InputStream in = null;
+        byte[] data = null;
+//        不需要这些头
+//        String encode ="data:image/jpeg;base64,"; // 返回Base64编码过的字节数组字符串
+//        String encode ="";
+        // 对字节数组Base64编码
+        BASE64Encoder encoder = new BASE64Encoder();
+        try {
+            // 读取图片字节数组
+            in = new FileInputStream(imgPath);
+            data = new byte[in.available()];
+            in.read(data);
+//            encode = encode+encoder.encode(data);
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                in.close();
+            } catch (IOException e) {
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            }
+        }
+        String encode = encode(data);
+        return encode;
+
+
+    }
+
+
+
+    /**
+     * base64字符串转化成图片
+     *
+     * @param imgData
+     *            图片编码
+     * @param imgFilePath
+     *            存放到本地路径
+     * @return
+     * @throws IOException
+     */
+
+    public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
+        if (imgData == null|| StringUtils.isBlank(imgFilePath)) // 图像数据为空
+        {
+            return false;
+        }
+        BASE64Decoder decoder = new BASE64Decoder();
+//        将空格转成+
+        imgData = imgData.replaceAll(" ", "+").split("base64,")[1];
+        OutputStream out = null;
+        try {
+            out = new FileOutputStream(imgFilePath);
+            // Base64解码
+            byte[] b = decoder.decodeBuffer(imgData);
+            for (int i = 0; i < b.length; ++i) {
+                if (b[i] < 0) {// 调整异常数据
+                    b[i] += 256;
+                }
+            }
+            out.write(b);
+        } catch (FileNotFoundException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } finally {
+            out.flush();
+            out.close();
+            return true;
+        }
+    }
+
+    /**
+     * 线上图片地址解析
+     * @param imgUrl
+     * @return
+     */
+    public static String imageUrlToBase64(String imgUrl) {
+        URL url = null;
+        InputStream is = null;
+        ByteArrayOutputStream outStream = null;
+        HttpsURLConnection httpUrl = null;
+
+        try {
+            url = new URL(imgUrl);
+            httpUrl = (HttpsURLConnection) url.openConnection();
+            httpUrl.connect();
+            httpUrl.getInputStream();
+
+            is = httpUrl.getInputStream();
+            outStream = new ByteArrayOutputStream();
+
+            //创建一个Buffer字符串
+            byte[] buffer = new byte[1024];
+            //每次读取的字符串长度,如果为-1,代表全部读取完毕
+            int len = 0;
+            //使用输入流从buffer里把数据读取出来
+            while( (len = is.read(buffer)) != -1 ){
+                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
+                outStream.write(buffer, 0, len);
+            }
+
+            // 对字节数组Base64编码
+            return encode(outStream.toByteArray());
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if(is != null) {
+                    is.close();
+                }
+                if(outStream != null) {
+                    outStream.close();
+                }
+                if(httpUrl != null) {
+                    httpUrl.disconnect();
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * 图片转字符串
+     * @param image 图片Buffer
+     * @return Base64编码
+     */
+    public static String encode(byte[] image){
+        BASE64Encoder decoder = new BASE64Encoder();
+        return replaceEnter(decoder.encode(image));
+    }
+
+    /**
+     * 字符替换
+     * @param str 字符串
+     * @return 替换后的字符串
+     */
+    public static String replaceEnter(String str){
+        String reg ="[\n-\r]";
+        Pattern p = Pattern.compile(reg);
+        Matcher m = p.matcher(str);
+        return m.replaceAll("");
+    }
+
+
+
+
+    public static void main(String[] args) throws IOException {
+        String url="http://172.22.45.3:9003/?scenefaces/dn@0_0/12/41-30fcb2c8-3c830";
+        System.out.println("url = " + url);
+        String s = Base64Utils.imageUrlToBase64(url);
+        System.out.println("s = " + s);
+    }
+
+}
+
+

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 4 - 4
src/main/java/com/example/faceverification/utils/RSAUtils.java


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 16 - 3
src/main/resources/application.yml