java接口加密解密

这里写目录标题

  • controller
  • 加解密工具类
  • 加密(本质是对@ResponseBody加密)
  • 解密(本质是对@RequestBody传参解密)
  • 注解

controller

@Controller
public class PathVariableController {@GetMapping(value = "/test")@ResponseBodypublic HashMap<String, Object> test() {HashMap<String, Object> map = new HashMap<>();map.put("data","successqqqqqq");map.put("code",200);map.put("msg","成功");return map ;}@PostMapping(value = "/us")@ResponseBodypublic HashMap<String, Object> us(@RequestBody User user) {System.out.println(user.getAge()+user.getName());HashMap<String, Object> map = new HashMap<>();map.put("data",user.getName());map.put("code",200);map.put("msg",user.getAge());//        map.put("name","lidapao里大炮");
//        map.put("age",18);return map ;}
}

加解密工具类

package org.example.demo.demos.web;import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.Key;
import java.util.Base64;public class DESUtil {/*** 偏移变量,固定占8位字节*/private final static String IV_PARAMETER = "12345678";/*** 密钥算法*/private static final String ALGORITHM = "DES";/*** 加密/解密算法-工作模式-填充模式*/private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";/*** 默认编码*/private static final String CHARSET = "utf-8";/*** 生成key** @param password* @return* @throws Exception*/private static Key generateKey(String password) throws Exception {DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);return keyFactory.generateSecret(dks);}/*** DES加密字符串** @param password 加密密码,长度不能够小于8位* @param data 待加密字符串* @return 加密后内容*/public static String encrypt(String password, String data) {if (password== null || password.length() < 8) {throw new RuntimeException("加密失败,key不能小于8位");}if (data == null)return null;try {Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));//JDK1.8及以上可直接使用Base64,JDK1.7及以下可以使用BASE64Encoder//Android平台可以使用android.util.Base64return new String(Base64.getEncoder().encode(bytes));} catch (Exception e) {e.printStackTrace();return data;}}/*** DES解密字符串** @param password 解密密码,长度不能够小于8位* @param data 待解密字符串* @return 解密后内容*/public static String decrypt(String password, String data) {if (password== null || password.length() < 8) {throw new RuntimeException("加密失败,key不能小于8位");}if (data == null)return null;try {Key secretKey = generateKey(password);Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);} catch (Exception e) {e.printStackTrace();return data;}}/*** DES加密文件** @param srcFile  待加密的文件* @param destFile 加密后存放的文件路径* @return 加密后的文件路径*/public static String encryptFile(String password, String srcFile, String destFile) {if (password== null || password.length() < 8) {throw new RuntimeException("加密失败,key不能小于8位");}try {IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, generateKey(password), iv);InputStream is = new FileInputStream(srcFile);OutputStream out = new FileOutputStream(destFile);CipherInputStream cis = new CipherInputStream(is, cipher);byte[] buffer = new byte[1024];int r;while ((r = cis.read(buffer)) > 0) {out.write(buffer, 0, r);}cis.close();is.close();out.close();return destFile;} catch (Exception ex) {ex.printStackTrace();}return null;}/*** DES解密文件** @param srcFile  已加密的文件* @param destFile 解密后存放的文件路径* @return 解密后的文件路径*/public static String decryptFile(String password, String srcFile, String destFile) {if (password== null || password.length() < 8) {throw new RuntimeException("加密失败,key不能小于8位");}try {File file = new File(destFile);if (!file.exists()) {file.getParentFile().mkdirs();file.createNewFile();}IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, generateKey(password), iv);InputStream is = new FileInputStream(srcFile);OutputStream out = new FileOutputStream(destFile);CipherOutputStream cos = new CipherOutputStream(out, cipher);byte[] buffer = new byte[1024];int r;while ((r = is.read(buffer)) >= 0) {cos.write(buffer, 0, r);}cos.close();is.close();out.close();return destFile;} catch (Exception ex) {ex.printStackTrace();}return null;}public static void main(String[] args) {String key = "98fbffd1064a4355b8abaacb6fa96f94";String data="bDyb3N+87Imt+LmOEklv+ttCM2Z/5pHnYbJKbQ41bvozUKMMSrScP/xhHCYUJBrKI/aIDaDs7BE=";//String data="Khrcd+W7L/+PkWYPB/2qrgL7G8agzQXJ2xWdU8q67sfpjBd+C9nwEFdqDiBpbtTGP8jjcUJnOYILEMPtbKH+6YiqhMcluTRlkoXrPePhfQFOa/69mrwXn42jZsx1g1mR7AqOwdoGoz2rIQRh5RAn3uFuaN9nonQ2sFhxb9f+YA/5umlWVc8v37t4RmrFv4PO0xlqNV4lkXgdj2AnvUqxfBIizKXRgxFdvyqwydiXEL2+sMMc1B/mJY1C8N1pK92St/rF9Bj94fZdewHL3pQklxfl3c1bVqXexIY/CjCrSwmhkTdKMWWC4+81Z9kPlNUDnas3b2Wi/OgoHJVuQIhXShu+KSqBSxWPkECNo6OX/L5zUUa45NOIUOqXVduZhxlvm1/CvzgqLUPlEaAWfIZWzw==";
//        System.out.println("加密前key:" + key);
//        System.out.println("加密前data:" + key);
//        String rc="{\"corpKey\":\"913205080884374764\"}";
//        String en = encrypt(key,rc);
//        System.out.println("加密后:" + en);String de = decrypt(key,data);System.out.println("解密后:" + de);}
}

加密(本质是对@ResponseBody加密)

package com.ruoyi.framework.config;import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Encrypt;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;import java.util.HashMap;
import java.util.Map;/*** 加解密接口处理*/
@RestControllerAdvice
public class EncodeAdvice implements ResponseBodyAdvice {private Logger log = LoggerFactory.getLogger(EncodeAdvice.class);@Overridepublic boolean supports(MethodParameter methodParameter, Class aClass) {return true;}@Nullable@Overridepublic Object beforeBodyWrite(@Nullable Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {boolean encode = true;// 出参 配置文件控制 默认打开String isEncrypt = RuoYiConfig.getIsEncrypt();if ("true".equals(isEncrypt)) {if (methodParameter.getMethod().isAnnotationPresent(Encrypt.class)) {Encrypt serializedField = methodParameter.getMethodAnnotation(Encrypt.class);encode = serializedField.encode();}if (encode) {log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");String secretPrivateKey = RuoYiConfig.getPrivateKey();ObjectMapper objectMapper = new ObjectMapper();try {String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);Map<String, String> data = new HashMap<>();String enData = DESUtil.encrypt("98fbffd1064a4355b8abaacb6fa96f94", result);// String enData2 = RsaUtils.encryptByPublicKey(RuoYiConfig.getPublicKey(), result);data.put("data", enData);// String s3 = RsaUtils.decrypt(RuoYiConfig.getPrivateKey(), enData);return data;} catch (Exception e) {e.printStackTrace();log.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密出现异常:" + e.getMessage());}}}return body;}
}

解密(本质是对@RequestBody传参解密)

package com.ruoyi.framework.config;import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Encrypt;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Map;@Slf4j
@RestControllerAdvice
public class DecodeAdvice implements RequestBodyAdvice {@Overridepublic boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {return true;}@Overridepublic HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {try {// 入参默认加密boolean isDecode = true;if (parameter.getMethod().isAnnotationPresent(Encrypt.class)) {Encrypt encrypt = parameter.getMethodAnnotation(Encrypt.class);isDecode = encrypt.decode();}if (isDecode) {log.info("对方法method :【" + parameter.getMethod().getName() + "】入参进行解密");if (inputMessage.getHeaders().containsKey("requestType")) {String requestType = inputMessage.getHeaders().get("requestType").get(0);if (requestType.equals("post")) {return new MyHttpInputMessage(inputMessage, requestType);} else if (requestType.equals("put")) {return new MyHttpInputMessage(inputMessage, requestType);// return inputMessage;} else {return inputMessage;}} else {return inputMessage;}} else {return inputMessage;}} catch (Exception e) {log.error("对方法method :【" + parameter.getMethod().getName() + "】入参解密失败");log.error(ExceptionUtil.getMessage(e));return inputMessage;}}@Overridepublic Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {return body;}@Overridepublic Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {return body;}class MyHttpInputMessage implements HttpInputMessage {private HttpHeaders headers;private InputStream body;/*** inputMessage 解密后重新赋值** @param inputMessage* @param requestType* @throws Exception*/public MyHttpInputMessage(HttpInputMessage inputMessage, String requestType) throws Exception {this.headers = inputMessage.getHeaders();if (requestType.equals("put")) {InputStream inputStream = inputMessage.getBody();String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);this.body = IOUtils.toInputStream(easpString(body), "utf-8");} else {this.body = IOUtils.toInputStream(easpString(IOUtils.toString(inputMessage.getBody(), "utf-8")), "utf-8");}}@Overridepublic InputStream getBody() {return body;}@Overridepublic HttpHeaders getHeaders() {return headers;}/*** @param requestData* @return*/public String easpString(String requestData) {if (requestData != null && !"".equals(requestData)) {Map<String, String> map = JSONObject.parseObject(requestData, Map.class);// 密文String isEncrypt = RuoYiConfig.getIsEncrypt();if (isEncrypt.equals("false")) {return requestData;}String data = map.get("dataBody");if (StringUtils.isEmpty(data)) {throw new RuntimeException("参数【requestData】缺失异常!");} else {String content;try {content = DESUtil.decrypt("98fbffd1064a4355b8abaacb6fa96f94", data);} catch (Exception e) {throw new RuntimeException("参数解析异常!");}return content;}}throw new RuntimeException("参数【requestData】不合法异常!");}}
}

注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Encrypt {/*** 接收参数是否解密 默认true* @param*/boolean decode() default true;/*** 返回体是否加密 默认true* @return*/boolean encode() default true;}

在这里插入图片描述

== 加解密的配置从yaml配置文件里读 ==

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/829351.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

IDEA pom.xml依赖警告

IDEA中&#xff0c;有时 pom.xml 中会出现如下提示&#xff1a; IDEA 2022.1 升级了检测易受攻击的 Maven 和 Gradle 依赖项&#xff0c;并建议修正&#xff0c;通过插件 Package Checker 捆绑到 IDE 中。 这并不是引用错误&#xff0c;不用担心。如果实在强迫症不想看到这个提…

使用 FFmpeg 实现录屏和录音

FFmpeg 是一个非常强大的开源工具&#xff0c;可以用来处理音频和视频。可以实现录屏和录音&#xff0c;也可以进行简单的剪辑。 要使用 FFmpeg 进行录屏和录音&#xff0c;需要首先确保系统已经安装了 FFmpeg。在大多数 Linux 发行版中&#xff0c;可以通过包管理器&#xff0…

用友政务财务系统FileDownload接口存在任意文件读取漏洞

声明&#xff1a; 本文仅用于技术交流&#xff0c;请勿用于非法用途 由于传播、利用此文所提供的信息而造成的任何直接或者间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c;文章作者不为此承担任何责任。 简介 用友政务财务系统是由用友软件开发的一款针对政府机…

62、回溯-N皇后

思路&#xff1a; N皇后问题要求在一个nn的棋盘上放置n个皇后&#xff0c;使得它们不能相互攻击。皇后可以攻击同一行、同一列&#xff0c;以及两个对角线方向上的其他皇后。解决这个问题意味着找到所有可能的棋盘配置&#xff0c;每个配置都符合上述条件。 1、初始化数据结构…

前端更优雅的使用 jsonp

前端更优雅的使用 jsonp 背景&#xff1a;最近项目中又使用到了 jsonp 这一项跨域的技术&#xff0c;&#xff08;主要还是受同源策略影响&#xff09;&#xff0c;下面有为大家提供封装好的函数及对应使用示例&#xff0c;欢迎大家阅读理解 文章目录 前端更优雅的使用 jsonp同…

【系统架构师】-选择题(四)

1、“41”视图 ①逻辑视图(Logical View)&#xff0c;设计的对象模型(使用面向对象的设计方法时)。 ②过程视图(Process View)&#xff0c;捕捉设计的并发和同步特征。系统集成师 ③物理视图(Physical View)&#xff0c;描述了软件到硬件的映射&#xff0c;反映了分布式特性。系…

【算法】人工蜂群算法,解决多目标车间调度问题,柔性车间调度问题

文章目录 复现论文什么是柔性作业车间调度问题&#xff1f;数据处理ABC算法编码解码种群初始化雇佣蜂操作IPOX交叉多点交叉 观察蜂操作侦察蜂操作算法流程 结果程序截图问询、帮助 复现论文 什么是柔性作业车间调度问题&#xff1f; 也叫多目标车间调度问题。 柔性作业车间调…

03 后端入参校验:自定义注解实现

03 后端入参校验&#xff1a;自定义注解实现 一、前言二、实现1、新建Spring Boot项目2、引入依赖3、新建注解类4、新建校验器5、全局异常处理器6、编写Controller7、新建实体类8、启动并测试 一、前言 在 Java 后端开发中&#xff0c;为了实现入参校验&#xff0c;常常会使用…

4月26(信息差)

&#x1f30d; 1170万台 华为跃升重回首位&#xff01;苹果跌至第五位 &#x1f384;工业软件大事件 —— OGG 1.0 发布&#xff0c;华为贡献全部源代码 ✨ 苹果发布 OpenELM&#xff1a;专为在设备端运行而设计的小型开源 AI 模型 1.FisheyeDetNet&#xff1a;首个基于鱼眼相…

GraspNet-1Billion 论文阅读

这里写自定义目录标题 GraspNet-1Billion总体数据集评价指标网络pointnet&#xff1a;Approach Network:Operation Network&#xff1a;Tolerance Network 摘要相关工作基于深度学习的抓取预测算法抓取数据集点云深度学习 GraspNet-1Billion CVPR2020 上海交大 论文和数据集地…

MATLAB中左边的大括号最后一行为什么会留很大的空白——解决

看了一些帖子说改字体&#xff0c;但是并没有什么用&#xff0c;在此给出亲测有效的方法&#xff1a;改变矩阵的行间距 先说一下问题 上图中留有大块空白 **解决办法&#xff1a;**光标放在矩阵上 格式——矩阵——更改矩阵&#xff0c;在矩阵设置中选中“行高相等”&#xff…

专项学习:软件开发

数据结构 &#xff08;一&#xff09;、字符串 当是数字的时候直接入栈 当是运算符号的时候 就将栈的最上面两个数拿出进行运算 后 再将结果进栈 记住&#xff08;栈顶元素永远在运算符号的右边&#xff09; &#xff08;二&#xff09;、数组 &#xff08;三&#xff09;、树…

k8s calico vxlan式详解

之前的文章讲了k8s ipip模式的使用以及流量路径&#xff0c;本篇文章主要是来讲解一下vxlan 模式下pod 流量是如何通信的。 一、ipip模式转vxlan 修改calico backend参数 将calico_backend参数由bird设置为vxlan,因为vxlan部署不使用bgp 修改calico controllers的configmap…

G1垃圾收集器详解

G1收集器 G1(Garbage-Frist)是一款面向服务器的垃圾收集器,主要针对配备多颗处理器及大容量内存的机器,以及高概率满足GC停顿时间要求的同时,还具备高吞吐量性能的特性. G1将Java堆划分为多个大小相等的独立区域(Region),JVM目标似乎不超过2048个Region(JVM源码里TARGET_REGIO…

STM32自己从零开始实操01:原理图

在听完老师关于 STM32 物联网项目的所有硬件课程之后&#xff0c;就是感觉自己云里雾里&#xff0c;明明课程都认真听完了&#xff0c;笔记也认真记录&#xff0c;但是就是感觉学到的知识还不是自己。 遂决定站在老师的肩膀上自己开始设计项目&#xff0c;将知识变成自己的&am…

WSL2无法ping通本地主机ip的解决办法

刚装完WSL2的Ubuntu子系统时&#xff0c;可能无法ping通本地主机的ip&#xff1a; WSL2系统ip&#xff1a; 本地主机ip&#xff1a; 在powershell里输入如下的命令&#xff1a; New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias &quo…

http基础了解

超文本传输协议&#xff08;HTTP&#xff09;是一个用于传输超媒体文档&#xff08;例如 HTML&#xff09;的应用层协议。它是为 Web 浏览器与 Web 服务器之间的通信而设计的&#xff0c;但也可以用于其他目的。HTTP 遵循经典的客户端—服务端模型&#xff0c;客户端打开一个连…

Nginx入门-01

必备知识 DNS域名解析 hostName主机名称其实就是我们的域名 www.baidu.com是一个域名 www.taobao.com也是一个域名 localhost也是一个域名 我们可以根据域名dns解析成ip地址 域名的存在就是为了方便我们的记忆&#xff0c;最终访问的时候还是要转换成服务器的IP地址进行…

Tomcat架构设计精髓分析-Connector高内聚低耦合设计

优秀的模块化设计通常都会采用高内聚、低耦合 高内聚是指相关度比较高的功能要尽可能集中&#xff0c;不要分散。低耦合是指两个相关的模块要尽可能减少依赖的部分和降低依赖的程序&#xff0c;不要让两个模块产中强依赖。 Tomca连接器需要实现的功能: 监听网络端口 接受网络…

STM32的GPIO输入和输出函数详解

系列文章目录 STM32单片机系列专栏 C语言术语和结构总结专栏 文章目录 1. GPIO模式 2. GPIO输出 2.1 RCC 2.2 GPIO 3. 代码示例 3.1 RCC时钟 3.2 GPIO初始化 3.3 GPIO输出函数 3.4 推挽输出和开漏输出 4. GPIO输入 4.1 输入模式 4.2 数据读取函数 5. C语言语法 1…