接口RSA2验签

由于没有找到网上比较全的资料,所以自己就找资料总结了一下,可以供大家参考,当然,这个写的比较简单,这个可以自己根据业务去修改,希望最大家有帮助

一、自定义注解

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Encryption {}

二、AOP

@Slf4j
@Aspect
@Component
public class EncryptionAspect {@Pointcut("@annotation(com.fly.springbootmybatis.annotation.Encryption)")public void encryption() {}@Before("encryption()")public void LogPrintln(JoinPoint point) throws JsonProcessingException {Object[] args = point.getArgs();ApiBaseRequest arg = (ApiBaseRequest) args[0];String sign = arg.getSign();String body = arg.getBiz_content();if (StringUtils.isNotBlank(sign) && StringUtils.isNotBlank(body)) {boolean isSign = RSA2Utils.verify256(body.getBytes(StandardCharsets.UTF_8),sign, SystemUtils.API_RSA2_SIGN_PUBLIC_KEY);if (!isSign) {throw new ApiException(ResultEnum.SIGN_ERROR);}} else {throw new ApiException(ResultEnum.SIGN_ERROR);}}
}

三、通用参数实体类

@Data
public class ApiBaseRequest implements Serializable {private static final long serialVersionUID = 1L;@NotBlank(message = "请求ID不能为空")private String appId;private String format;private String charset;private String version = "1.0";@NotBlank(message = "签名不能为空")private String sign;@NotBlank(message = "时间戳不能为空")private String timestamp;@NotBlank(message = "请求参数不能为空")private String biz_content;
}

四、全局异常拦截

/*** 全局处理异常类*/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {/*** 处理业务异常** @param e* @return*/@ResponseBody@ExceptionHandler(value = BusinessException.class)public AjaxResult businessExceptionHandler(BusinessException e) {log.error(e.getMessage());return AjaxResult.error(e.getCode(),e.getMessage());}/*** 处理接口异常** @param e* @return*/@ResponseBody@ExceptionHandler(value = ApiException.class)public AjaxResult ApiExceptionHandler(ApiException e) {log.error(e.getMessage());return AjaxResult.error(e.getCode(),e.getMessage());}@ResponseBody@ExceptionHandler(value = FileException.class)public AjaxResult fileExceptionHandler(FileException e) {log.error(e.getMessage());return AjaxResult.error(e.getCode(),e.getMessage());}/*** 请求方式不支持** @param e* @return*/@ResponseBody@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)public AjaxResult handleException(HttpRequestMethodNotSupportedException e) {log.error(e.getMessage());return AjaxResult.error(ResultEnum.NOT_REQUEST_METHOD);}/*** 处理JSR303验证异常** @param e* @return*/@ResponseBody@ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class, ValidateException.class})public AjaxResult handleVaildException(Exception e) {BindingResult bindingResult = null;if (e instanceof MethodArgumentNotValidException) {bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();} else if (e instanceof BindException) {bindingResult = ((BindException) e).getBindingResult();} else if (e instanceof ValidateException) {return AjaxResult.error(((ValidateException) e).getCode(),e.getMessage(),((ValidateException) e).getData());}Map<String, String> errorMap = new HashMap<>(16);List<FieldError> fieldErrors = bindingResult.getFieldErrors();fieldErrors.forEach(error -> errorMap.put(error.getField(), error.getDefaultMessage()));log.info("------参数校验失败:{}", errorMap);return AjaxResult.error(ResultEnum.ILLEGAL_PARAMETER.getCode(),ResultEnum.ILLEGAL_PARAMETER.getMsg(),errorMap);}/*** 处理上传文件过大异常* @param e* @return*/@ResponseBody@ExceptionHandler(value = MaxUploadSizeExceededException.class)public AjaxResult fileSizeExceededException(MaxUploadSizeExceededException e){log.error(e.getMessage());return AjaxResult.error(ResultEnum.FILE_MAX_LIMIT);}/*** 处理其他异常** @param e* @return*/@ExceptionHandler(value = Exception.class)public ModelAndView exceptionHandler(Exception e) {log.error(e.getMessage());ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName("5xx");return modelAndView;}
}

五、RSA2加密工具类

@Slf4j
public class RSA2Utils {// 算法类别private final static String SIGN_TYPE = "RSA";// 算法位数private final static Integer KEY_SIZE = 2048;private RSA2Utils(){};/*** 生成公私钥*/public static Map<String, String> getPublicPrivateKey() {Map<String, String> pubPriKey = new HashMap<>();KeyPair keyPair = KeyUtil.generateKeyPair(SIGN_TYPE, KEY_SIZE);String publicKeyStr = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());String privateKeyStr = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());pubPriKey.put("publicKey", publicKeyStr);pubPriKey.put("privateKey", privateKeyStr);return pubPriKey;}/*** 实例化公钥*/public static PublicKey getPublicKey(String publicKey) throws Exception {byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey.getBytes());X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE);return keyFactory.generatePublic(keySpec);}/*** 实例化私钥*/public static PrivateKey getPrivateKey(String privateKey) throws Exception {byte[] privateKeyBytes = Base64.getDecoder().decode(privateKey.getBytes());PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE);return keyFactory.generatePrivate(keySpec);}/*** 签名*/public static String sign256(byte[] signData, String priKey) {try {byte[] keyBytes = Base64.getDecoder().decode(priKey);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE);PrivateKey privateKey = keyFactory.generatePrivate(keySpec);Signature si = Signature.getInstance(SignAlgorithm.SHA256withRSA.getValue());si.initSign(privateKey);si.update(signData);byte[] sign = si.sign();return Base64.getEncoder().encodeToString(sign);} catch (Exception e) {throw new RuntimeException(e.getMessage());}}/*** 验签*/public static boolean verify256(byte[] dataBytes, String sign, String pubkey) {boolean flag = false;try {byte[] signByte = Base64.getDecoder().decode(sign);byte[] encodedKey = Base64.getDecoder().decode(pubkey);Signature verf = Signature.getInstance(SignAlgorithm.SHA256withRSA.getValue());KeyFactory keyFac = KeyFactory.getInstance(SIGN_TYPE);PublicKey puk = keyFac.generatePublic(new X509EncodedKeySpec(encodedKey));verf.initVerify(puk);verf.update(dataBytes);flag = verf.verify(signByte);} catch (Exception e) {throw new RuntimeException(e.getMessage());}return flag;}/*** RSA2公钥加密*/public static byte[] encyptByPublickey(byte[] data, String pubkey) throws Exception {Cipher cipher = Cipher.getInstance(SIGN_TYPE);cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(pubkey));return cipher.doFinal(data);}/*** RSA2私钥解密*/public static byte[] decryptByPrivateKey(byte[] content, String privateKey) throws Exception {Cipher cipher = Cipher.getInstance(SIGN_TYPE);cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKey));return cipher.doFinal(content);}
}

六、其他类

@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ResultEnum {// 数据操作错误定义NO_PERMISSION(403, "权限不足"),NO_AUTH(401, "未登录"),NOT_FOUND(404, "未找到该资源"),NOT_REQUEST_METHOD(405,"该请求方式不支持"),INTERNAL_SERVER_ERROR(500, "服务器异常请联系管理员"),SUCCESS(20000, "成功"),FAIL(10000,"失败"),FILE_MAX_LIMIT(10001,"单个文件上传不超过10MB,多个文件上传不超过100MB"),ILLEGAL_PARAMETER(10002,"非法参数"),CONVERSION_ERROR(10003,"参数转换错误"),FILE_READ_ERROR(10004,"文件读取失败"),SIGN_ERROR(10006,"验签失败"),REQUEST_ERROR(10007,"请求失效"),FREQUENT_REQUEST(10008,"请求过于频繁,请稍后再试");/*** 错误码*/private Integer code;/*** 错误信息*/private String msg;}
public class ApiException extends RuntimeException {private static final long serialVersionUID = 1L;/*** 状态码*/private Integer code;/*** 错误提示*/private String message;public ApiException() {}public ApiException(String message) {this.message = message;}public ApiException(Integer code, String message) {this.code = code;this.message = message;}public ApiException(ResultEnum resultEnum) {this.code = resultEnum.getCode();this.message = resultEnum.getMsg();}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}

Java实现接口RSA2校验相关推荐

  1. c语言实现java接口_五分钟带你了解Java是如何从容而优雅地实现接口数据校验

    本篇文章给大家分享平时开发中总结的一点小技巧!在工作中写过Java程序的朋友都知道,目前使用Java开发服务最主流的方式就是通过Spring MVC定义一个Controller层接口,并将接口请求或返 ...

  2. java 接口参数验证_SpringBoot实现通用的接口参数校验

    作者:cipher 来源:http://39sd.cn/560BA 本文介绍基于Spring Boot和JDK8编写一个AOP,结合自定义注解实现通用的接口参数校验. 缘由 目前参数校验常用的方法是在 ...

  3. java接口如何接受语音参数_Java 是如何优雅地实现接口数据校验的?

    作者 | 无敌码农  责编 | 张文头图 | CSDN 下载自东方 IC来源 | 无敌码农(ID:jiangqiaodege)本篇文章给大家分享平时开发中总结的一点小技巧!在工作中写过 Java 程序 ...

  4. Java 是如何优雅地实现接口数据校验的?

    作者 | 无敌码农  责编 | 张文 头图 | CSDN 下载自东方 IC 来源 | 无敌码农(ID:jiangqiaodege) 本篇文章给大家分享平时开发中总结的一点小技巧! 在工作中写过 Jav ...

  5. AliPay - Java支付宝接口开发(三)

    一.前言 AliPay - Java支付宝接口开发(一) AliPay - Java支付宝接口开发(二) 二.支付宝沙箱环境集成Web项目 1.将支付宝Demo中的相关文件复制到我们的项目中 1.1 ...

  6. Springboot + redis + 注解 + 拦截器来实现接口幂等性校验

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:wangzaiplus www.jianshu.com/p/ ...

  7. SpringBoot实现通用的接口参数校验

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试资料 作者:cipher juejin.im/post/5af3c25b ...

  8. springboot + redis + 注解 + 拦截器 实现接口幂等性校验

    点击上方"方志朋",选择"设为星标" 做积极的人,而不是积极废人 来源:https://www.jianshu.com/p/6189275403ed 一.概念 ...

  9. redis 判断存在性_实战 | springboot+redis+拦截器 实现接口幂等性校验

    来源:https://www.jianshu.com/p/6189275403ed 一.概念 幂等性, 通俗的说就是一个接口, 多次发起同一个请求, 必须保证操作只能执行一次 比如: 订单接口, 不能 ...

最新文章

  1. pushpop指令的操作数必须是字操作数_指令格式
  2. 只需3分钟,就能轻松创建 一个SpreadJS的React项目
  3. 多线激光雷达~三维建图
  4. 2019最新 iOS Native项目集成Unity3D
  5. set,env,和export的区别
  6. Codeforces Beta Round #11 A. Increasing Sequence 贪心
  7. deepfake ai智能换脸_AI 换脸、声音篡改等,明确写入新版民法典!
  8. git 删除本地仓库中的分支_git常用命令行 新建分支 删除分支 提交
  9. 毕业生,管好你的档案和户口
  10. jquery-购物车js
  11. 全网首发:ProGuard如何混淆多个包
  12. UOJ449 集训队作业2018 喂鸽子
  13. 奇安信天擎的退出以及卸载
  14. 名词从句、定语从句、状语从句的位置及图示
  15. 如何测linux传输文件的速度,如何测试linux服务器的上传下载速度
  16. 穿山甲广告切后台点Icon进入后广告消失或游戏重启的解决方法
  17. 使用opencv调用摄像头然后录制视频和保存文件
  18. http://coolshell.cn/
  19. 搭建公司内部论坛 只需简单三步 1 (安装Discuz)
  20. 深度解密Go语言之关于 interface 的 10 个问题

热门文章

  1. 安装框架断路器要注意什么?该如何选择断路器?
  2. BZOJ2246 [SDOI2011]迷宫探险 【记忆化搜索dp + 概率】
  3. java语言程序设计视频_[VIP视频]【A0152】Java语言程序设计进阶高级进阶视频教程 网易云课堂 百度网盘 云盘...
  4. PHP版物流快递公司轨迹查询实现-中小快递公司适用
  5. 原来我还可以这样活:拆掉思维里的墙
  6. Django企业开发读书笔记(及官方文档学习笔记) 老男孩2019Go语言视频学习
  7. wangEditor上传本地视频
  8. 内存屏障(cpu内存屏障 与java内存屏障)
  9. 【Gatsby】Gatsby模式以及基本操作
  10. 列向量,列空间,零向量,零空间