Parcourir la source

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

luofeiyun il y a 1 semaine
Parent
commit
d225769cbb
14 fichiers modifiés avec 1176 ajouts et 6 suppressions
  1. 123 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/OperatePasswordController.java
  2. 21 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordCheckAndResetReqVO.java
  3. 36 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordPageReqVO.java
  4. 39 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordRespVO.java
  5. 25 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordSaveReqVO.java
  6. 27 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordUpdateReqVO.java
  7. 46 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/dal/dataobject/password/OperatePasswordDO.java
  8. 29 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/dal/mysql/password/OperatePasswordMapper.java
  9. 6 5
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/distributor/DistributorServiceImpl.java
  10. 5 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/distributorrecharge/DistributorRechargeServiceImpl.java
  11. 88 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/password/OperatePasswordService.java
  12. 183 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/password/OperatePasswordServiceImpl.java
  13. 547 0
      ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/password/RSAUtils.java
  14. 1 1
      ship-server-web/src/main/resources/application.yaml

+ 123 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/OperatePasswordController.java

@@ -0,0 +1,123 @@
+package com.yc.ship.module.ota.controller.admin.password;
+
+import com.yc.ship.framework.common.pojo.CommonResult;
+import com.yc.ship.framework.common.pojo.PageParam;
+import com.yc.ship.framework.common.pojo.PageResult;
+import com.yc.ship.framework.common.util.object.BeanUtils;
+import com.yc.ship.framework.excel.core.util.ExcelUtils;
+import com.yc.ship.framework.operatelog.core.annotations.OperateLog;
+import com.yc.ship.module.ota.controller.admin.password.vo.*;
+import com.yc.ship.module.ota.dal.dataobject.password.OperatePasswordDO;
+import com.yc.ship.module.ota.service.password.OperatePasswordService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletResponse;
+import javax.validation.Valid;
+import java.io.IOException;
+import java.util.List;
+
+import static com.yc.ship.framework.common.pojo.CommonResult.success;
+import static com.yc.ship.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
+
+
+@Tag(name = "管理后台 - 操作密码")
+@RestController
+@RequestMapping("/operate-password")
+@Validated
+public class OperatePasswordController {
+
+    @Resource
+    private OperatePasswordService operatePasswordService;
+
+    @PostMapping("/create")
+    @Operation(summary = "创建操作密码")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:create')")
+    public CommonResult<Long> createOperatePassword(@Valid @RequestBody OperatePasswordSaveReqVO createReqVO) {
+        return success(operatePasswordService.createOperatePassword(createReqVO));
+    }
+
+    @PutMapping("/update")
+    @Operation(summary = "更新操作密码")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:update')")
+    public CommonResult<Boolean> updateOperatePassword(@Valid @RequestBody OperatePasswordSaveReqVO updateReqVO) {
+        operatePasswordService.updateOperatePassword(updateReqVO);
+        return success(true);
+    }
+
+    @DeleteMapping("/delete")
+    @Operation(summary = "删除操作密码")
+    @Parameter(name = "id", description = "编号", required = true)
+    @PreAuthorize("@ss.hasPermission('support:operate-password:delete')")
+    public CommonResult<Boolean> deleteOperatePassword(@RequestParam("id") Long id) {
+        operatePasswordService.deleteOperatePassword(id);
+        return success(true);
+    }
+
+    @GetMapping("/get")
+    @Operation(summary = "获得操作密码")
+    @Parameter(name = "id", description = "编号", required = true, example = "1024")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:query')")
+    public CommonResult<OperatePasswordRespVO> getOperatePassword(@RequestParam("id") Long id) {
+        OperatePasswordDO operatePassword = operatePasswordService.getOperatePassword(id);
+        return success(BeanUtils.toBean(operatePassword, OperatePasswordRespVO.class));
+    }
+
+    @GetMapping("/page")
+    @Operation(summary = "获得操作密码分页")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:query')")
+    public CommonResult<PageResult<OperatePasswordRespVO>> getOperatePasswordPage(@Valid OperatePasswordPageReqVO pageReqVO) {
+        PageResult<OperatePasswordDO> pageResult = operatePasswordService.getOperatePasswordPage(pageReqVO);
+        return success(BeanUtils.toBean(pageResult, OperatePasswordRespVO.class));
+    }
+
+    @GetMapping("/export-excel")
+    @Operation(summary = "导出操作密码 Excel")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:export')")
+    @OperateLog(type = EXPORT,enable = false)
+    public void exportOperatePasswordExcel(@Valid OperatePasswordPageReqVO pageReqVO,
+              HttpServletResponse response) throws IOException {
+        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
+        List<OperatePasswordDO> list = operatePasswordService.getOperatePasswordPage(pageReqVO).getList();
+        // 导出 Excel
+        ExcelUtils.write(response, "操作密码.xls", "数据", OperatePasswordRespVO.class,
+                        BeanUtils.toBean(list, OperatePasswordRespVO.class));
+    }
+
+    @PostMapping("/check")
+    @Operation(summary = "校验密码")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:check')")
+    public CommonResult<Boolean> checkOperatePassword(@Valid @RequestBody OperatePasswordCheckAndResetReqVO reqVO) {
+        boolean res = operatePasswordService.checkPwd(reqVO);
+        return success(res);
+    }
+
+    @PutMapping("/reset-password")
+    @Operation(summary = "重置密码")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:reset-password')")
+    public CommonResult<Boolean> resetPassword(@Valid @RequestBody OperatePasswordCheckAndResetReqVO reqVO) {
+        operatePasswordService.resetPassword(reqVO.getType(),reqVO.getPassword());
+        return success(true);
+    }
+
+    @PutMapping("/update-password")
+    @Operation(summary = "修改用户个人密码")
+    @PreAuthorize("@ss.hasPermission('support:operate-password:update-password')")
+    public CommonResult<Boolean> updatePassword(@Valid @RequestBody OperatePasswordUpdateReqVO reqVO) {
+        operatePasswordService.updatePassword( reqVO);
+        return success(true);
+    }
+
+    @GetMapping("/validateExists")
+    @Operation(summary = "校验操作密码是否存在")
+    public CommonResult<Boolean> validateExists(@RequestParam("type") Integer type) {
+        boolean result = operatePasswordService.validateExists(type);
+        return success(result);
+    }
+
+}

+ 21 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordCheckAndResetReqVO.java

@@ -0,0 +1,21 @@
+package com.yc.ship.module.ota.controller.admin.password.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+import javax.validation.constraints.NotEmpty;
+import javax.validation.constraints.NotNull;
+
+@Schema(description = "管理后台 - 更新/重置操作密码 Request VO")
+@Data
+public class OperatePasswordCheckAndResetReqVO {
+
+    @Schema(description = "密码类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
+    @NotNull(message = "密码类型不能为空")
+    private Integer type;
+
+    @Schema(description = "密码", requiredMode = Schema.RequiredMode.REQUIRED, example = "123456")
+    @NotEmpty(message = "密码不能为空")
+    private String password;
+
+}

+ 36 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordPageReqVO.java

@@ -0,0 +1,36 @@
+package com.yc.ship.module.ota.controller.admin.password.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+import org.springframework.format.annotation.DateTimeFormat;
+
+import java.time.LocalDateTime;
+import com.yc.ship.framework.common.pojo.PageParam;
+import static com.yc.ship.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
+
+
+@Schema(description = "管理后台 - 操作密码分页 Request VO")
+@Data
+@EqualsAndHashCode(callSuper = true)
+@ToString(callSuper = true)
+public class OperatePasswordPageReqVO extends PageParam {
+
+    @Schema(description = "用户ID", example = "4075")
+    private Long userId;
+
+    @Schema(description = "密码类型", example = "1")
+    private Integer type;
+
+    @Schema(description = "密码")
+    private String password;
+
+    @Schema(description = "状态0-禁用,1-启用", example = "1")
+    private Integer status;
+
+    @Schema(description = "创建时间")
+    @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
+    private LocalDateTime[] createTime;
+
+}

+ 39 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordRespVO.java

@@ -0,0 +1,39 @@
+package com.yc.ship.module.ota.controller.admin.password.vo;
+
+import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
+import com.alibaba.excel.annotation.ExcelProperty;
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+@Schema(description = "管理后台 - 操作密码 Response VO")
+@Data
+@ExcelIgnoreUnannotated
+public class OperatePasswordRespVO {
+
+    @Schema(description = "主键", requiredMode = Schema.RequiredMode.REQUIRED, example = "5958")
+    @ExcelProperty("主键")
+    private Long id;
+
+    @Schema(description = "用户ID", example = "4075")
+    @ExcelProperty("用户ID")
+    private Long userId;
+
+    @Schema(description = "密码类型", example = "1")
+    @ExcelProperty("密码类型")
+    private Integer type;
+
+    @Schema(description = "密码")
+    @ExcelProperty("密码")
+    private String password;
+
+    @Schema(description = "状态0-禁用,1-启用", example = "1")
+    @ExcelProperty("状态0-禁用,1-启用")
+    private Integer status;
+
+    @Schema(description = "创建时间")
+    @ExcelProperty("创建时间")
+    private LocalDateTime createTime;
+
+}

+ 25 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordSaveReqVO.java

@@ -0,0 +1,25 @@
+package com.yc.ship.module.ota.controller.admin.password.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+@Schema(description = "管理后台 - 操作密码新增/修改 Request VO")
+@Data
+public class OperatePasswordSaveReqVO {
+
+    @Schema(description = "主键", requiredMode = Schema.RequiredMode.REQUIRED, example = "5958")
+    private Long id;
+
+    @Schema(description = "用户ID", example = "4075")
+    private Long userId;
+
+    @Schema(description = "密码类型", example = "1")
+    private Integer type;
+
+    @Schema(description = "密码")
+    private String password;
+
+    @Schema(description = "状态0-禁用,1-启用", example = "1")
+    private Integer status;
+
+}

+ 27 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/controller/admin/password/vo/OperatePasswordUpdateReqVO.java

@@ -0,0 +1,27 @@
+package com.yc.ship.module.ota.controller.admin.password.vo;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+import javax.validation.constraints.NotEmpty;
+import javax.validation.constraints.NotNull;
+
+@Schema(description = "管理后台 - 更新/重置操作密码 Request VO")
+@Data
+public class OperatePasswordUpdateReqVO {
+
+    @Schema(description = "密码类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
+    @NotNull(message = "密码类型不能为空")
+    private Integer type;
+
+    @Schema(description = "密码", requiredMode = Schema.RequiredMode.REQUIRED, example = "123456")
+    @NotEmpty(message = "密码不能为空")
+    private String oldPassword;
+
+
+    @Schema(description = "新密码", requiredMode = Schema.RequiredMode.REQUIRED, example = "654321")
+    @NotEmpty(message = "新密码不能为空")
+    private String newPassword;
+
+
+}

+ 46 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/dal/dataobject/password/OperatePasswordDO.java

@@ -0,0 +1,46 @@
+package com.yc.ship.module.ota.dal.dataobject.password;
+
+import com.baomidou.mybatisplus.annotation.KeySequence;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.yc.ship.framework.tenant.core.db.TenantBaseDO;
+import lombok.*;
+
+/**
+ * 操作密码 DO
+ *
+ * @author 管理员
+ */
+@TableName("operate_password")
+@KeySequence("operate_password_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
+@Data
+@EqualsAndHashCode(callSuper = true)
+@ToString(callSuper = true)
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class OperatePasswordDO extends TenantBaseDO {
+
+    /**
+     * 主键
+     */
+    @TableId
+    private Long id;
+    /**
+     * 用户ID
+     */
+    private Long userId;
+    /**
+     * 密码类型
+     */
+    private Integer type;
+    /**
+     * 密码
+     */
+    private String password;
+    /**
+     * 状态0-禁用,1-启用
+     */
+    private Integer status;
+
+}

+ 29 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/dal/mysql/password/OperatePasswordMapper.java

@@ -0,0 +1,29 @@
+package com.yc.ship.module.ota.dal.mysql.password;
+
+import com.yc.ship.framework.common.pojo.PageResult;
+import com.yc.ship.framework.mybatis.core.mapper.BaseMapperX;
+import com.yc.ship.framework.mybatis.core.query.LambdaQueryWrapperX;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordPageReqVO;
+import com.yc.ship.module.ota.dal.dataobject.password.OperatePasswordDO;
+import org.apache.ibatis.annotations.Mapper;
+
+
+/**
+ * 操作密码 Mapper
+ *
+ * @author 管理员
+ */
+@Mapper
+public interface OperatePasswordMapper extends BaseMapperX<OperatePasswordDO> {
+
+    default PageResult<OperatePasswordDO> selectPage(OperatePasswordPageReqVO reqVO) {
+        return selectPage(reqVO, new LambdaQueryWrapperX<OperatePasswordDO>()
+                .eqIfPresent(OperatePasswordDO::getUserId, reqVO.getUserId())
+                .eqIfPresent(OperatePasswordDO::getType, reqVO.getType())
+                .eqIfPresent(OperatePasswordDO::getPassword, reqVO.getPassword())
+                .eqIfPresent(OperatePasswordDO::getStatus, reqVO.getStatus())
+                .betweenIfPresent(OperatePasswordDO::getCreateTime, reqVO.getCreateTime())
+                .orderByDesc(OperatePasswordDO::getId));
+    }
+
+}

+ 6 - 5
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/distributor/DistributorServiceImpl.java

@@ -237,6 +237,7 @@ public class DistributorServiceImpl implements DistributorService {
             updateObj.setPassword(password);
         }
         DistributorRespVO distributorRespVO = distributorMapper.getById(updateReqVO.getId());
+        updateObj.setLoginName(distributorRespVO.getLoginName());
         updateReqVO.setTenantId(distributorRespVO.getAccountTenantId());
         //修改后台用户密码
         updateSystemUserPassword(updateReqVO);
@@ -248,9 +249,9 @@ public class DistributorServiceImpl implements DistributorService {
         // 校验存在
         validateDistributorExists(id);
         DistributorDO distributorDO = distributorMapper.selectById(id);
-//        if (distributorDO.getType() == 2) {
-//            tenantApi.deleteTenant(distributorDO.getAccountTenantId());
-//        }
+        if (distributorDO.getType() == 2) {
+            adminUserApi.deleteUser(distributorDO.getLoginName());
+        }
         // 删除
         distributorMapper.deleteById(id);
     }
@@ -302,7 +303,7 @@ public class DistributorServiceImpl implements DistributorService {
             }else if(status ==0){
                 status = 1;
             }
-//            adminUserApi.updateStatus(distributor.getLoginName(), status);
+            adminUserApi.updateStatus(distributor.getLoginName(), status);
         }
 
     }
@@ -428,7 +429,7 @@ public class DistributorServiceImpl implements DistributorService {
     }
 
     void updateSystemUserPassword(DistributorUpdatePasswordReqVO updateReqVO) {
-
+        adminUserApi.updatePwd(updateReqVO.getLoginName(),updateReqVO.getPassword());
     }
 
     @Override

+ 5 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/distributorrecharge/DistributorRechargeServiceImpl.java

@@ -46,6 +46,7 @@ import java.util.stream.Stream;
 import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
 import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception0;
 import static com.yc.ship.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
+import static com.yc.ship.framework.security.core.util.SecurityFrameworkUtils.getLoginUserNickname;
 import static com.yc.ship.module.ota.enums.ErrorCodeConstants.*;
 
 /**
@@ -97,7 +98,9 @@ public class DistributorRechargeServiceImpl implements DistributorRechargeServic
         distributorRecharge.setRechargeMode(1);
         distributorRecharge.setStatus(AuditStatusEnum.PENDING.getValue());
         Long userId = getLoginUserId();
+        String userName = getLoginUserNickname();
         distributorRecharge.setApplyUser(userId);
+        distributorRecharge.setApplyUserName(userName);
         distributorRecharge.setApplyTime(LocalDateTime.now());
         distributorRechargeMapper.insert(distributorRecharge);
         // 返回
@@ -165,7 +168,9 @@ public class DistributorRechargeServiceImpl implements DistributorRechargeServic
         rechargeDO.setStatus(reqVO.getAuditStatus());
         rechargeDO.setAuditTime(LocalDateTime.now());
         Long userId = getLoginUserId();
+        String userName = getLoginUserNickname();
         rechargeDO.setAuditUser(userId);
+        rechargeDO.setAuditUserName(userName);
         distributorRechargeMapper.updateById(rechargeDO);
     }
 

+ 88 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/password/OperatePasswordService.java

@@ -0,0 +1,88 @@
+package com.yc.ship.module.ota.service.password;
+
+
+import com.yc.ship.framework.common.pojo.PageResult;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordCheckAndResetReqVO;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordPageReqVO;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordSaveReqVO;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordUpdateReqVO;
+import com.yc.ship.module.ota.dal.dataobject.password.OperatePasswordDO;
+
+import javax.validation.Valid;
+
+/**
+ * 操作密码 Service 接口
+ *
+ * @author 管理员
+ */
+public interface OperatePasswordService {
+
+    /**
+     * 创建操作密码
+     *
+     * @param createReqVO 创建信息
+     * @return 编号
+     */
+    Long createOperatePassword(@Valid OperatePasswordSaveReqVO createReqVO);
+
+    /**
+     * 更新操作密码
+     *
+     * @param updateReqVO 更新信息
+     */
+    void updateOperatePassword(@Valid OperatePasswordSaveReqVO updateReqVO);
+
+    /**
+     * 删除操作密码
+     *
+     * @param id 编号
+     */
+    void deleteOperatePassword(Long id);
+
+    /**
+     * 获得操作密码
+     *
+     * @param id 编号
+     * @return 操作密码
+     */
+    OperatePasswordDO getOperatePassword(Long id);
+
+    /**
+     * 获得操作密码分页
+     *
+     * @param pageReqVO 分页查询
+     * @return 操作密码分页
+     */
+    PageResult<OperatePasswordDO> getOperatePasswordPage(OperatePasswordPageReqVO pageReqVO);
+
+    void resetPassword(Integer type, String password);
+
+    /**
+     * 判断密码是否匹配
+     *
+     * @param rawPassword 未加密的密码
+     * @param encodedPassword 加密后的密码
+     * @return 是否匹配
+     */
+    boolean isPasswordMatch(String rawPassword, String encodedPassword);
+
+    /**
+     * 校验密码是否正确
+     * @param reqVO
+     * @return
+     */
+    boolean checkPwd( OperatePasswordCheckAndResetReqVO reqVO);
+
+    /**
+     * 修改操作密码
+     * @param reqVO
+     */
+    void updatePassword(OperatePasswordUpdateReqVO reqVO);
+
+    /**
+     * 验证用户是否有该类型密码
+     * @param type
+     * @return
+     */
+    boolean validateExists(Integer type);
+}

+ 183 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/password/OperatePasswordServiceImpl.java

@@ -0,0 +1,183 @@
+package com.yc.ship.module.ota.service.password;
+
+import com.baomidou.mybatisplus.core.toolkit.IdWorker;
+import com.yc.ship.framework.common.pojo.PageResult;
+import com.yc.ship.framework.common.util.object.BeanUtils;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordCheckAndResetReqVO;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordPageReqVO;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordSaveReqVO;
+import com.yc.ship.module.ota.controller.admin.password.vo.OperatePasswordUpdateReqVO;
+import com.yc.ship.module.ota.dal.dataobject.password.OperatePasswordDO;
+import com.yc.ship.module.ota.dal.mysql.password.OperatePasswordMapper;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Service;
+import org.springframework.validation.annotation.Validated;
+
+import javax.annotation.Resource;
+
+import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception0;
+import static com.yc.ship.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
+
+
+/**
+ * 操作密码 Service 实现类
+ *
+ * @author 管理员
+ */
+@Service
+@Validated
+public class OperatePasswordServiceImpl implements OperatePasswordService {
+
+    @Resource
+    private OperatePasswordMapper operatePasswordMapper;
+    @Resource
+    private PasswordEncoder passwordEncoder;
+
+    @Override
+    public Long createOperatePassword(OperatePasswordSaveReqVO createReqVO) {
+        long loginUserId = getLoginUserId();
+        // 插入
+        OperatePasswordDO operatePassword = BeanUtils.toBean(createReqVO, OperatePasswordDO.class);
+        Long id = IdWorker.getId(operatePassword);
+        operatePassword.setId(id);
+        operatePassword.setUserId(loginUserId);
+        operatePassword.setDeleted(false);
+
+        try {
+            String password = RSAUtils.decryptByPrivateKey(operatePassword.getPassword(), RSAUtils.PRIVATE_KEY_LZ);
+            operatePassword.setPassword(encodePassword(password));
+        } catch (Exception e) {
+            throw exception0(11_028, "密码不正确");
+        }
+
+        operatePasswordMapper.insert(operatePassword);
+        // 返回
+        return operatePassword.getId();
+    }
+
+    @Override
+    public void updateOperatePassword(OperatePasswordSaveReqVO updateReqVO) {
+        // 校验存在
+        validateOperatePasswordExists(updateReqVO.getId());
+        // 更新
+        OperatePasswordDO updateObj = BeanUtils.toBean(updateReqVO, OperatePasswordDO.class);
+        operatePasswordMapper.updateById(updateObj);
+    }
+
+    @Override
+    public void deleteOperatePassword(Long id) {
+        // 校验存在
+        validateOperatePasswordExists(id);
+        // 删除
+        operatePasswordMapper.deleteById(id);
+    }
+
+    private void validateOperatePasswordExists(Long id) {
+        if (operatePasswordMapper.selectById(id) == null) {
+            throw exception0(11_028, "不存在");
+        }
+    }
+
+    @Override
+    public OperatePasswordDO getOperatePassword(Long id) {
+        return operatePasswordMapper.selectById(id);
+    }
+
+    @Override
+    public PageResult<OperatePasswordDO> getOperatePasswordPage(OperatePasswordPageReqVO pageReqVO) {
+        return operatePasswordMapper.selectPage(pageReqVO);
+    }
+
+    @Override
+    public void resetPassword(Integer type, String password) {
+        // 校验用户存在
+        long loginUserId = getLoginUserId();
+        OperatePasswordDO passwordDO = validateUserAndTypeExists(loginUserId, type);
+        if (passwordDO == null) {
+            throw exception0(11_028, "不存在");
+        }
+        try {
+            String passwordStr = RSAUtils.decryptByPrivateKey(password, RSAUtils.PRIVATE_KEY_LZ);
+            // 执行更新
+            passwordDO.setPassword(encodePassword(passwordStr)); // 加密密码
+            operatePasswordMapper.updateById(passwordDO);
+        } catch (Exception e) {
+            throw exception0(11_028, "操作失败");
+        }
+
+    }
+
+    @Override
+    public boolean validateExists(Integer type) {
+        Long userId = getLoginUserId();
+        OperatePasswordDO passwordDO = validateUserAndTypeExists(userId, type);
+        if (passwordDO == null) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    @Override
+    public void updatePassword(OperatePasswordUpdateReqVO reqVO) {
+        Long userId = getLoginUserId();
+        String oldPwd = "";
+        String newPwd = "";
+        try {
+            oldPwd = RSAUtils.decryptByPrivateKey(reqVO.getOldPassword(), RSAUtils.PRIVATE_KEY_LZ);
+            newPwd = RSAUtils.decryptByPrivateKey(reqVO.getNewPassword(), RSAUtils.PRIVATE_KEY_LZ);
+        } catch (Exception e) {
+            throw exception0(500,"密码解密失败");
+        }
+        OperatePasswordDO passwordDO = validatePassword(userId, reqVO.getType(), oldPwd);
+        // 执行更新
+        passwordDO.setPassword(encodePassword(newPwd)); // 加密密码
+        operatePasswordMapper.updateById(passwordDO);
+    }
+
+    @Override
+    public boolean checkPwd( OperatePasswordCheckAndResetReqVO reqVO) {
+        Long userId = getLoginUserId();
+        boolean flag = true;
+        try {
+            String password = RSAUtils.decryptByPrivateKey(reqVO.getPassword(), RSAUtils.PRIVATE_KEY_LZ);
+            this.validatePassword(userId, reqVO.getType(), password);
+        } catch (Exception e) {
+            flag = false;
+        }
+
+        return flag;
+    }
+
+    @Override
+    public boolean isPasswordMatch(String rawPassword, String encodedPassword) {
+        return passwordEncoder.matches(rawPassword, encodedPassword);
+    }
+
+    private OperatePasswordDO validatePassword(Long userId, Integer type, String oldPassword) {
+        OperatePasswordDO passwordDO = validateUserAndTypeExists(userId, type);
+        if (passwordDO == null) {
+            throw exception0(11_028, "不存在");
+        }
+        if (!isPasswordMatch(oldPassword, passwordDO.getPassword())) {
+            throw exception0(11_028, "操作失败");
+        }
+        return passwordDO;
+    }
+
+    private OperatePasswordDO validateUserAndTypeExists(Long userId, Integer type) {
+        OperatePasswordDO passwordDO = operatePasswordMapper.selectOne(OperatePasswordDO::getUserId, userId, OperatePasswordDO::getType, type);
+        return passwordDO;
+    }
+
+    /**
+     * 对密码进行加密
+     *
+     * @param password 密码
+     * @return 加密后的密码
+     */
+    private String encodePassword(String password) {
+        return passwordEncoder.encode(password);
+    }
+
+}

+ 547 - 0
ship-module-ota/ship-module-ota-biz/src/main/java/com/yc/ship/module/ota/service/password/RSAUtils.java

@@ -0,0 +1,547 @@
+package com.yc.ship.module.ota.service.password;
+
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.ArrayUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import java.io.*;
+import java.security.*;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author :yaochao
+ * @description :TODO
+ * @date :2022/5/6 15:42
+ */
+public class RSAUtils {
+
+    private static final Logger logger = LoggerFactory.getLogger(RSAUtils.class);
+
+
+    // MAX_DECRYPT_BLOCK应等于密钥长度/8(1byte=8bit),所以当密钥位数为2048时,最大解密长度应为256.
+    // 128 对应 1024,256对应2048
+    private static final int KEYSIZE = 2048;
+
+    // RSA最大加密明文大小
+    private static final int MAX_ENCRYPT_BLOCK = 117;
+
+    // RSA最大解密密文大小
+    private static final int MAX_DECRYPT_BLOCK = 256;
+
+    // 不仅可以使用DSA算法,同样也可以使用RSA算法做数字签名
+    private static final String KEY_ALGORITHM = "RSA";
+    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
+
+    public static final String DEFAULT_SEED = "$%^*%^()(ED47d784sde78"; // 默认种子
+
+    /**
+     * 目前固定公钥、私钥,有需求再改动
+     */
+    public static String PUBLIC_KEY_LZ = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdH\n" +
+            "nzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==";
+    public static String PRIVATE_KEY_LZ = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY\n" +
+            "7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKN\n" +
+            "PuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gA\n" +
+            "kM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWow\n" +
+            "cSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99Ecv\n" +
+            "DQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthh\n" +
+            "YhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3\n" +
+            "UP8iWi1Qw0Y=";
+
+    public static final String PUBLIC_KEY = "PublicKey";
+    public static final String PRIVATE_KEY = "PrivateKey";
+
+    /**
+     * 生成密钥
+     *
+     * @param seed 种子
+     * @return 密钥对象
+     * @throws Exception
+     */
+
+    public static Map<String, Key> initKey(String seed) throws Exception {
+        logger.info("生成密钥");
+        KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
+        SecureRandom secureRandom = new SecureRandom();
+        // 如果指定seed,那么secureRandom结果是一样的,所以生成的公私钥也永远不会变
+        secureRandom.setSeed(seed.getBytes());
+        // Modulus size must range from 512 to 1024 and be a multiple of 64
+        keygen.initialize(KEYSIZE, secureRandom);
+        KeyPair keys = keygen.genKeyPair();
+        PrivateKey privateKey = keys.getPrivate();
+        PublicKey publicKey = keys.getPublic();
+        Map<String, Key> map = new HashMap<>(2);
+        map.put(PUBLIC_KEY, publicKey);
+        map.put(PRIVATE_KEY, privateKey);
+        return map;
+    }
+
+    /**
+     * 生成默认密钥
+     *
+     * @return 密钥对象
+     * @throws Exception
+     */
+
+    public static Map<String, Key> initKey() throws Exception {
+        return initKey(DEFAULT_SEED);
+    }
+
+    /**
+     * 取得私钥
+     *
+     * @param keyMap
+     * @return
+     * @throws Exception
+     */
+    public static String getPrivateKey(Map<String, Key> keyMap) throws Exception {
+        Key key = (Key) keyMap.get(PRIVATE_KEY);
+        //        return encryptBASE64(key.getEncoded()); // base64加密私钥
+        return base64ToStr(key.getEncoded()); // base64加密私钥
+    }
+
+    private static String base64ToStr(byte[] encoded) {
+        return javax.xml.bind.DatatypeConverter.printBase64Binary(encoded);
+    }
+
+    /**
+     * 取得公钥
+     *
+     * @param keyMap
+     * @return
+     * @throws Exception
+     */
+    public static String getPublicKey(Map<String, Key> keyMap) throws Exception {
+        Key key = (Key) keyMap.get(PUBLIC_KEY);
+        //        return encryptBASE64(key.getEncoded()); // base64加密公钥
+        return base64ToStr(key.getEncoded()); // base64加密公钥
+    }
+
+    /**
+     * 用私钥对信息进行数字签名
+     *
+     * @param data       加密数据
+     * @param privateKey 私钥-base64加密的
+     * @return
+     * @throws Exception
+     */
+    public static String signByPrivateKey(byte[] data, String privateKey) throws Exception {
+        logger.info("用私钥对信息进行数字签名");
+        byte[] keyBytes = decryptBASE64(privateKey);
+        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
+        KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
+        PrivateKey priKey = factory.generatePrivate(keySpec);// 生成私钥
+        // 用私钥对信息进行数字签名
+        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
+        signature.initSign(priKey);
+        signature.update(data);
+        return encryptBASE64(signature.sign());
+
+    }
+
+    /**
+     * BASE64Encoder 加密
+     *
+     * @param data 要加密的数据
+     * @return 加密后的字符串
+     */
+    private static String encryptBASE64(byte[] data) {
+        //      BASE64Encoder encoder = new BASE64Encoder();
+        //      String encode = encoder.encode(data);
+        //      return encode;
+        return new String(Base64.encodeBase64(data));
+    }
+
+    private static byte[] decryptBASE64(String data) {
+        // BASE64Decoder 每76个字符换行
+        //      BASE64Decoder decoder = new BASE64Decoder();
+        //      byte[] buffer = decoder.decodeBuffer(data);
+        //      return buffer;
+        // codec 的 Base64 不换行
+        return Base64.decodeBase64(data);
+    }
+
+    public static boolean verifyByPublicKey(byte[] data, String publicKey, String sign)
+        throws Exception {
+        byte[] keyBytes = decryptBASE64(publicKey);
+        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
+        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
+        PublicKey pubKey = keyFactory.generatePublic(keySpec);
+        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
+        signature.initVerify(pubKey);
+        signature.update(data);
+        return signature.verify(decryptBASE64(sign)); // 验证签名
+    }
+
+    /**
+     * RSA公钥加密
+     *
+     * @param str       加密字符串
+     * @param publicKey 公钥
+     * @return 密文
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     * @throws NoSuchPaddingException
+     * @throws InvalidKeyException
+     * @throws UnsupportedEncodingException
+     * @throws BadPaddingException
+     * @throws IllegalBlockSizeException
+     * @throws Exception                    加密过程中的异常信息
+     */
+    public static String encryptByPublicKey(String str, String publicKey)
+        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException,
+        InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
+        UnsupportedEncodingException {
+        // base64编码的公钥
+        byte[] keyBytes = decryptBASE64(publicKey);
+        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM)
+            .generatePublic(new X509EncodedKeySpec(keyBytes));
+        // RSA加密
+        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
+        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
+        System.out.println(publicKey);
+        logger.info("provider: {}", cipher.getProvider().getClass().getName());
+        byte[] data = str.getBytes("UTF-8");
+        // 加密时超过117字节就报错。为此采用分段加密的办法来加密
+        byte[] enBytes = null;
+        for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) {
+            // 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
+            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_ENCRYPT_BLOCK));
+            enBytes = ArrayUtils.addAll(enBytes, doFinal);
+        }
+        System.out.println(enBytes.length);
+        String outStr = encryptBASE64(enBytes);
+        return outStr;
+    }
+
+    /**
+     * RSA私钥加密
+     *
+     * @param str        加密字符串
+     * @param privateKey 公钥
+     * @return 密文
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     * @throws NoSuchPaddingException
+     * @throws InvalidKeyException
+     * @throws UnsupportedEncodingException
+     * @throws BadPaddingException
+     * @throws IllegalBlockSizeException
+     * @throws Exception                    加密过程中的异常信息
+     */
+    public static String encryptByPrivateKey(String str, String privateKey)
+        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException,
+        InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
+        UnsupportedEncodingException {
+        // base64编码的公钥
+        byte[] keyBytes = decryptBASE64(privateKey);
+        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM)
+            .generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
+        // RSA加密
+        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
+        cipher.init(Cipher.ENCRYPT_MODE, priKey);
+
+        byte[] data = str.getBytes("UTF-8");
+        // 加密时超过117字节就报错。为此采用分段加密的办法来加密
+        byte[] enBytes = null;
+        for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) {
+            // 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
+            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_ENCRYPT_BLOCK));
+            enBytes = ArrayUtils.addAll(enBytes, doFinal);
+        }
+        String outStr = encryptBASE64(enBytes);
+        return outStr;
+    }
+
+    /**
+     * 读取公钥
+     *
+     * @param publicKeyPath
+     * @return
+     */
+    public static PublicKey readPublic(String publicKeyPath) {
+        if (publicKeyPath != null) {
+            try (FileInputStream bais = new FileInputStream(publicKeyPath)) {
+                CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
+                X509Certificate cert =
+                    (X509Certificate) certificatefactory.generateCertificate(bais);
+                return cert.getPublicKey();
+            } catch (CertificateException e) {
+                logger.error(e.getMessage(), e);
+            } catch (FileNotFoundException e) {
+                logger.error(e.getMessage(), e);
+            } catch (IOException e) {
+                logger.error(e.getMessage(), e);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 读取私钥
+     *
+     * @param privateKeyPath
+     * @return
+     */
+    public static PrivateKey readPrivate(String privateKeyPath, String privateKeyPwd) {
+        if (privateKeyPath == null || privateKeyPwd == null) {
+            return null;
+        }
+        try (InputStream stream = new FileInputStream(new File(privateKeyPath));) {
+            // 获取JKS 服务器私有证书的私钥,取得标准的JKS的 KeyStore实例
+            KeyStore store = KeyStore
+                .getInstance("JKS");// JKS,二进制格式,同时包含证书和私钥,一般有密码保护;PKCS12,二进制格式,同时包含证书和私钥,一般有密码保护。
+            // jks文件密码,根据实际情况修改
+            store.load(stream, privateKeyPwd.toCharArray());
+            // 获取jks证书别名
+            Enumeration<String> en = store.aliases();
+            String pName = null;
+            while (en.hasMoreElements()) {
+                String n = (String) en.nextElement();
+                if (store.isKeyEntry(n)) {
+                    pName = n;
+                }
+            }
+            // 获取证书的私钥
+            PrivateKey key = (PrivateKey) store.getKey(pName, privateKeyPwd.toCharArray());
+            return key;
+        } catch (Exception e) {
+            logger.error(e.getMessage(), e);
+        }
+        return null;
+    }
+
+    /**
+     * RSA私钥解密
+     *
+     * @param encryStr   加密字符串
+     * @param privateKey 私钥
+     * @return 铭文
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     * @throws NoSuchPaddingException
+     * @throws BadPaddingException
+     * @throws IllegalBlockSizeException
+     * @throws InvalidKeyException
+     * @throws Exception                 解密过程中的异常信息
+     */
+    public static String decryptByPrivateKey(String encryStr, String privateKey)
+        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException,
+        IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
+        UnsupportedEncodingException {
+        // base64编码的私钥
+        byte[] decoded = decryptBASE64(privateKey);
+        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM)
+            .generatePrivate(new PKCS8EncodedKeySpec(decoded));
+        // RSA解密
+        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
+        cipher.init(Cipher.DECRYPT_MODE, priKey);
+        System.out.println(privateKey);
+        logger.info("provider: {}", cipher.getProvider().getClass().getName());
+        // 64位解码加密后的字符串
+        byte[] data = decryptBASE64(encryStr);
+        System.out.println(data.length);
+        // 解密时超过128字节报错。为此采用分段解密的办法来解密
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < data.length; i += MAX_DECRYPT_BLOCK) {
+            System.out.println(i);
+            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_DECRYPT_BLOCK));
+            sb.append(new String(doFinal));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * RSA公钥解密
+     *
+     * @param encryStr  加密字符串
+     * @param publicKey 私钥
+     * @return 铭文
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     * @throws NoSuchPaddingException
+     * @throws BadPaddingException
+     * @throws IllegalBlockSizeException
+     * @throws InvalidKeyException
+     * @throws Exception                 解密过程中的异常信息
+     */
+    public static String decryptByPublicKey(String encryStr, String publicKey)
+        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException,
+        IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
+        // base64编码的私钥
+        byte[] decoded = decryptBASE64(publicKey);
+        RSAPublicKey priKey = (RSAPublicKey) KeyFactory.getInstance(KEY_ALGORITHM)
+            .generatePublic(new X509EncodedKeySpec(decoded));
+        // RSA解密
+        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
+        cipher.init(Cipher.DECRYPT_MODE, priKey);
+
+        // 64位解码加密后的字符串
+        byte[] data = decryptBASE64(encryStr);
+        // 解密时超过128字节报错。为此采用分段解密的办法来解密
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < data.length; i += MAX_DECRYPT_BLOCK) {
+            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_DECRYPT_BLOCK));
+            sb.append(new String(doFinal));
+        }
+
+        return sb.toString();
+    }
+
+    /**
+     * 加密
+     *
+     * @param key
+     * @param data
+     * @return
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeySpecException
+     * @throws NoSuchPaddingException
+     * @throws IllegalBlockSizeException
+     * @throws BadPaddingException
+     * @throws InvalidKeyException
+     * @throws IOException
+     */
+    public static String testEncrypt(String key, String data)
+        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
+        IllegalBlockSizeException, BadPaddingException, InvalidKeyException, IOException {
+        byte[] decode = Base64.decodeBase64(key);
+        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode);
+        KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM);
+        PrivateKey generatePrivate = kf.generatePrivate(pkcs8EncodedKeySpec);
+        Cipher ci = Cipher.getInstance(KEY_ALGORITHM);
+        ci.init(Cipher.ENCRYPT_MODE, generatePrivate);
+
+        byte[] bytes = data.getBytes();
+        int inputLen = bytes.length;
+        int offLen = 0;//偏移量
+        int i = 0;
+        ByteArrayOutputStream bops = new ByteArrayOutputStream();
+        while (inputLen - offLen > 0) {
+            byte[] cache;
+            if (inputLen - offLen > 117) {
+                cache = ci.doFinal(bytes, offLen, 117);
+            } else {
+                cache = ci.doFinal(bytes, offLen, inputLen - offLen);
+            }
+            bops.write(cache);
+            i++;
+            offLen = 117 * i;
+        }
+        bops.close();
+        byte[] encryptedData = bops.toByteArray();
+        String encodeToString = Base64.encodeBase64String(encryptedData);
+        return encodeToString;
+    }
+
+
+
+    /**
+     * 解密
+     *
+     * @param key
+     * @param data
+     * @return
+     * @throws NoSuchAlgorithmException
+     * @throws InvalidKeyException
+     * @throws NoSuchPaddingException
+     * @throws InvalidKeySpecException
+     * @throws BadPaddingException
+     * @throws IllegalBlockSizeException
+     * @throws IOException
+     */
+    public static String testDecrypt(String key, String data)
+        throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
+        InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, IOException {
+        byte[] decode = Base64.decodeBase64(key);
+        //      PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode); //java底层 RSA公钥只支持X509EncodedKeySpec这种格式
+        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode);
+        KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM);
+        PublicKey generatePublic = kf.generatePublic(x509EncodedKeySpec);
+        Cipher ci = Cipher.getInstance(KEY_ALGORITHM);
+        ci.init(Cipher.DECRYPT_MODE, generatePublic);
+
+        int inputLen = data.getBytes().length;
+        byte[] bytes = data.getBytes();
+        int offLen = 0;
+        int i = 0;
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+        while (inputLen - offLen > 0) {
+            byte[] cache;
+            if (inputLen - offLen > 128) {
+                cache = ci.doFinal(bytes, offLen, 128);
+            } else {
+                cache = ci.doFinal(bytes, offLen, inputLen - offLen);
+            }
+            byteArrayOutputStream.write(cache);
+            i++;
+            offLen = 128 * i;
+
+        }
+        byteArrayOutputStream.close();
+        byte[] byteArray = byteArrayOutputStream.toByteArray();
+        return new String(byteArray);
+    }
+
+    /**
+     * main方法测试 第一种用法:公钥加密,私钥解密。---用于加解密 第二种用法:私钥签名,公钥验签。---用于签名
+     *
+     * @param args
+     * @throws Exception
+     */
+    public static void main(String[] args) throws Exception {
+        String ss = "hello";
+        byte[] data = ss.getBytes();
+        Map<String, Key> keyMap = initKey();// 构建密钥
+        PublicKey publicKey = (PublicKey) keyMap.get(PUBLIC_KEY);
+        PrivateKey privateKey = (PrivateKey) keyMap.get(PRIVATE_KEY);
+        logger.info("私钥format:{}", privateKey.getFormat());
+        logger.info("公钥format:{}", publicKey.getFormat());
+        System.out.println(privateKey.getEncoded());
+        logger.info("私钥string:{}", getPrivateKey(keyMap));
+        logger.info("公钥string:{}", getPublicKey(keyMap));
+        // 产生签名
+        String sign = signByPrivateKey(data, getPrivateKey(keyMap));
+        logger.info("签名sign={}", sign);
+        // 验证签名
+        boolean verify1 = verifyByPublicKey(ss.getBytes(), getPublicKey(keyMap), sign);
+        logger.info("经验证数据和签名匹配:{} ", verify1);
+        boolean verify = verifyByPublicKey(data, getPublicKey(keyMap), sign);
+        logger.error("经验证数据和签名匹配:{} ", verify);
+        // logger.info("数字签名为"+sign);
+        String s = "单红宇测试,e8986ae53e76e7514ebc7e8a42e81e6cea5b6280fb5d3259d5f0a46f9f6e090c";
+        String encrypt = encryptByPrivateKey(s, PRIVATE_KEY_LZ);
+        ;
+        System.out.println("固定私钥加密结果为---:" + encrypt);
+        String decrypt = decryptByPublicKey(encrypt, PUBLIC_KEY_LZ);
+        System.out.println("固定公钥解密结果为---:" + decrypt);
+        String encryStr = encryptByPublicKey(s, getPublicKey(keyMap));
+        logger.info("字符串 {} 的公钥加密结果为:{}", s, encryStr);
+        String decryStr = decryptByPrivateKey(encryStr, getPrivateKey(keyMap));
+        logger.info("私钥解密结果为:{}", decryStr);
+        //        logger.info("========================================================================================");
+        //        String s2 = "单红宇测试222,e8986ae53e76e7514ebc7e8a42e81e6cea5b6280fb5d3259d5f0a46f9f6e090c";
+        //        String encryStr2 = encryptByPrivateKey(s, getPrivateKey(keyMap));
+        //        logger.info("字符串 {} 的私钥加密结果为:{}", s2, encryStr2);
+        //        String decryStr2 = decryptByPublicKey(encryStr2, getPublicKey(keyMap));
+        //        logger.info("公钥解密结果为:{}", decryStr2);
+
+    }
+
+}

+ 1 - 1
ship-server-web/src/main/resources/application.yaml

@@ -3,7 +3,7 @@ spring:
     name: yudao-server
 
   profiles:
-    active: test
+    active: local
 
   main:
     allow-circular-references: true # 允许循环依赖,因为项目是三层架构,无法避免这个情况。