程序员子龙(Java面试 + Java学习) 程序员子龙(Java面试 + Java学习)
首页
学习指南
工具
开源项目
技术书籍

程序员子龙

Java 开发从业者
首页
学习指南
工具
开源项目
技术书籍
  • 基础

  • JVM

  • Spring

  • 并发编程

  • Mybatis

  • 网络编程

  • 数据库

  • 缓存

  • 设计模式

  • 分布式

  • 高并发

  • SpringBoot

    • SpringBoot 整合redis
    • SpringBoot 线程池
    • springboot下整合mybatis
    • spring boot 配置文件的加载顺序
    • springboot启动不加载bootstrap.yml文件的问题解决
    • SpringBoot设置动态定时任务
    • springboot整合hibernate
    • ApplicationRunner、InitializingBean、@PostConstruct使用详解
    • Spring Boot 优雅的参数校验方案
    • ELK处理 SpringBoot 日志,太优雅了!
    • SpringBoot配置数据源
    • Spring Boot 默认数据库连接池 —— HikariCP
    • 数据库连接池Hikari监控
    • Spring Boot中使用AOP统一处理Web请求日志
    • SpringBoot 三大开发工具,你都用过么?
    • Spring Boot 3.2 + CRaC = 王炸!
    • springboot启动的时候排除加载某些bean
    • spring boot中集成swagger
    • springboot项目引入这个包以后把原来的json报文改为了xml格式返回
    • SpringBoot中new对象不能自动注入对象和属性的问题
    • 使用 Spring Boot Actuator 监控应用
    • 记录一次springboot自动任务线上突然不执行问题排查过程
    • SpringBoot定时任务@Scheduled源码解析
    • Spring Boot + Lua = 王炸!
    • Spring Boot 实现定时任务动态管理
    • SpringBoot的@Async注解有什么坑?
    • druid 参数配置详解
    • Spring Boot HandlerMethodArgumentResolver 使用和场景
    • SpringBoot数据加解密
    • 解决controller层注入的service为null
    • 在 Spring Boot 中通过 RequestBodyAdvice 统一解码请求体
    • SpringBoot之使用Redisson实现分布式锁(含完整例子)
  • SpringCloudAlibaba

  • Nginx

  • 面试

  • 生产问题

  • 系统设计

  • 消息中间件

  • Java
  • SpringBoot
程序员子龙
2024-08-05

SpringBoot数据加解密

RSAUtil工具类:

	//前端公钥
	public static final String PUBLIC_KEY = "xxxxx";


//	public static final String PUBLIC_KEY = "xxxxxxxx";
	public static final String PRIVATE_KEY = "xxxxxxx";

	//前端私钥
//	public static final String PRIVATE_KEY = "xxxxxx";




	// RSA最大加密明文大小
	private static final int MAX_ENCRYPT_BLOCK = 117;

	// RSA最大解密密文大小
	private static final int MAX_DECRYPT_BLOCK = 128;

	/**
	 * RAS非对称加密,随机生成密钥对
	 *
	 * @return 密钥对
	 */
	public static Map<String, String> genKeyPair() {
		// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
		KeyPairGenerator keyPairGen = null;
		try {
			keyPairGen = KeyPairGenerator.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		// 初始化密钥对生成器,密钥大小为96-1024位
		assert keyPairGen != null;
		keyPairGen.initialize(1024, new SecureRandom());
		// 生成一个密钥对,保存在keyPair中
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
		// 将公钥和私钥保存到Map
		Map<String, String> res = new HashMap<String, String>(2) {{

		}};
		String pub = new String(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
		String pri = new String(Base64.getEncoder().encodeToString((privateKey.getEncoded())));
		System.out.println(pub);
		System.out.println(pri);
		return res;
	}


	/**
	 * RAS非对称加密: 公钥加密
	 *
	 * @param str       加密字符串
	 * @param publicKey 公钥
	 * @return 密文
	 */
	public static String encrypt(String str, String publicKey) {
		//base64编码的公钥
		byte[] decoded = Base64.getDecoder().decode(publicKey);
		RSAPublicKey pubKey;
		String outStr = null;

		try {
			pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, pubKey);

			// 分段加密
			// URLEncoder编码解决中文乱码问题
			byte[] data = URLEncoder.encode(str, "UTF-8").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);
			}

			outStr = Base64.getEncoder().encodeToString(enBytes);
		} catch (InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException |
				 NoSuchPaddingException | NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //RSA加密
		return outStr;
	}



	/**
	 * RSA私钥解密
	 *
	 * @param str        加密字符串
	 * @param privateKey 私钥
	 * @return 铭文
	 */
	public static String decrypt(String str, String privateKey)  {

		try {
			str = str.replaceAll(" ","");

			//base64编码的私钥
			byte[] decoded = Base64.getDecoder().decode(privateKey);
			RSAPrivateKey priKey;
			//RSA解密
			Cipher cipher;
			String outStr = null;


			priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
			cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, priKey);

			byte[] data = Base64.getDecoder().decode(str.getBytes("UTF-8"));

			// 返回UTF-8编码的解密信息
			int inputLen = data.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * 128;
			}
			byte[] decryptedData = out.toByteArray();
			out.close();
			return URLDecoder.decode(new String(decryptedData, "UTF-8"), "UTF-8");
		} catch (InvalidKeySpecException e) {
			throw new RuntimeException(e);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		} catch (NoSuchPaddingException e) {
			throw new RuntimeException(e);
		} catch (InvalidKeyException e) {
			throw new RuntimeException(e);
		} catch (IllegalBlockSizeException e) {
			throw new RuntimeException(e);
		} catch (BadPaddingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}



	public static void main(String[] args) {

//		 genKeyPair();

		String str = "jack";


			// 加密后的数据
			String encryptData = null;

			try {
				// 使用公钥加密
				encryptData = encrypt(str ,PUBLIC_KEY);
				System.out.println(encryptData);
			} catch (Exception e) {
				log.error("加密失败 {}", e);
			}

			// 解密后的数据
			String decryptData = null;
			try {
				// 使用私钥解密
				decryptData = decrypt(encryptData, PRIVATE_KEY);
				System.out.println(decryptData);
			} catch (Exception e) {
				e.printStackTrace();
			}


	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189

定义解密注解

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DecryptApi {
 
}
1
2
3
4
5
6

在get请求上添加注解

   @GetMapping("test")
    public void test(@DecryptApi String username, @DecryptApi String password){
        
      
    }
1
2
3
4
5

定义参数解析器

public class AbsHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
	
	
	
	private Logger logger=LoggerFactory.getLogger(AbsHandlerMethodArgumentResolver.class);
 
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		logger.info("正在调用执行:{}",parameter.getMember().getName());
		return parameter.hasParameterAnnotation(DecryptApi.class);
	}
 
	@Override
	public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		logger.info("对用户请求进行解析");

		Parameter parameter = methodParameter.getParameter();
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		String data = request.getParameter(parameter.getName());
		String decrypt = RSAUtil.decrypt(data, RSAUtil.PRIVATE_KEY);

		return decrypt;
	}
 
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

注册参数解析器

@Configuration
public class AbsWebMvcConfigurerAdapter extends WebMvcConfigurationSupport {
 
	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
             super.addArgumentResolvers(argumentResolvers);
	         argumentResolvers.add(new AbsHandlerMethodArgumentResolver());

    }


}
1
2
3
4
5
6
7
8
9
10
11
12

前端传参:

curl --location '127.0.0.1:9999/test?username=HXZDFybpqHLvpw7wSB5zjeJ9MbnPFdSOyp7CgCRMxTrI8xUrBrdIahTD%2FIEEiybik6OosGsrEzHiZpIKrMgzpD5FhquAklPNNi%2Bntkf6SVZLCOIWUoDV5jOVYnRSDzU4MigRpOCyiMy5T%2Fzyt%2FlXl%2BP7EBVwuivXQWN%2FM5K60ws%3D&password=HXZDFybpqHLvpw7wSB5zjeJ9MbnPFdSOyp7CgCRMxTrI8xUrBrdIahTD%2FIEEiybik6OosGsrEzHiZpIKrMgzpD5FhquAklPNNi%2Bntkf6SVZLCOIWUoDV5jOVYnRSDzU4MigRpOCyiMy5T%2Fzyt%2FlXl%2BP7EBVwuivXQWN%2FM5K60ws%3D'
1
上次更新: 2024/08/12, 14:38:19
Spring Boot HandlerMethodArgumentResolver 使用和场景
解决controller层注入的service为null

← Spring Boot HandlerMethodArgumentResolver 使用和场景 解决controller层注入的service为null→

最近更新
01
一个注解,优雅的实现接口幂等性
11-17
02
MySQL事务(超详细!!!)
10-14
03
阿里二面:Kafka中如何保证消息的顺序性?这周被问到两次了
10-09
更多文章>
Theme by Vdoing | Copyright © 2024-2024

    辽ICP备2023001503号-2

  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式