网站首页 > 博客文章 正文
前言
不知道在上一篇文章中你有没有发现,jdbc.properties中的数据库密码配置是这样写的:
jdbc.password=5EF28C5A9A0CE86C2D231A526ED5B388
其实这不是真正的密码,而是经过AES加密的。
AES的Java实现
AES(高级加密标准)是美国联邦政府采用的一种区块加密标准,其替代原先的
DES加密算法,成为对称密钥加密中最流行的算法之一。
AES加密解密的实现就不具体介绍了,这里直接给出源码:
package com.demo.project.monitor.util;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class AESEncryption {
private String password = "Password";
public AESEncryption(){
}
public AESEncryption(String password){
this.password = password;
}
/**
* 加密
* @param content 加密内容
* @return
*/
public String encrypt(String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result); // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**解密
* @param content 解密内容
* @return
*/
public String decrypt(String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(parseHexStr2Byte(content));
return new String(result); // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将二进制转换成16进制
* @param buf
* @return
*/
private String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
* @param hexStr
* @return
*/
private byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
解密配置文件
既然配置文件部分内容已经进行了加密处理,那我们在填充上下文的占位符时就要对其进行解密,获得真正的密码,还记得之前我们在加载配置文件的时候使用的类PropertyPlaceholderConfigurer吗?我们可以通过对它的resolvePlaceholder方法进行重写来实现。
实现过程
首先创建一个继承自PropertyPlaceholderConfigurer的类EncryptPropertyPlaceholderConfigurer,然后重写它的方法:
package com.demo.project.monitor.util;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.Properties;
/**
* 解密配置文件敏感内容
*/
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected String resolvePlaceholder(String placeholder, Properties props) {
String result = props.getProperty(placeholder);
if(placeholder.endsWith("jdbc.password")){
AESEncryption aes = new AESEncryption();
String decrypt = aes.decrypt(result);
result = decrypt == null ? result : decrypt;
}
return result;
}
}
接着在spring上下文中将原来的beanorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer修改为我们创建的类即可:
<bean class="com.demo.project.monitor.util.EncryptPropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
<property name="ignoreResourceNotFound" value="false"/>
</bean>
这样spring在填充占位符的时候就会进行判断,对加密后的敏感信息进行解密处理,得到真实的内容。
- 上一篇: 5种高大上的yml文件读取方式,你知道吗?
- 下一篇: Spring中经典的9种设计模式,一定要记牢
猜你喜欢
- 2024-09-26 基于 redis 和 ehcache 的两级缓存组件 uncode-cache
- 2024-09-26 melon-idfactory主键工厂,提供ID生成服务,保证ID的唯一性。
- 2024-09-26 Spring Boot中的Properties(springboot property)
- 2024-09-26 Spring-基础笔记(一)(spring详细教程)
- 2024-09-26 带你读源码2——Spring源码分析之容器的刷新 - refresh()
- 2024-09-26 super-diamond 结合springboot的使用经验(用过的都说好)
- 2024-09-26 还在为数据同步而苦恼吗?手把手教你实现canal数据同步(一)
- 2024-09-26 源码分析:Spring是如何获取容器中的Bean?
- 2024-09-26 五种方式让你在java中读取properties文件内容
- 2024-09-26 图表显示日志离线信息(图表显示日志离线信息什么意思)
你 发表评论:
欢迎- 最近发表
-
- 给3D Slicer添加Python第三方插件库
- Python自动化——pytest常用插件详解
- Pycharm下安装MicroPython Tools插件(ESP32开发板)
- IntelliJ IDEA 2025.1.3 发布(idea 2020)
- IDEA+Continue插件+DeepSeek:开发者效率飙升的「三体组合」!
- Cursor:提升Python开发效率的必备IDE及插件安装指南
- 日本旅行时想借厕所、买香烟怎么办?便利商店里能解决大问题!
- 11天!日本史上最长黄金周来了!旅游万金句总结!
- 北川景子&DAIGO缘定1.11 召开记者会宣布结婚
- PIKO‘PPAP’ 洗脑歌登上美国告示牌
- 标签列表
-
- ifneq (61)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)