前言
在使用springboot项目中,密码等配置文件通常是明文的,这样对于我们的数据来说有重大的安全隐患,今天来使用jasypt来进行加密配置
基本使用
1.添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2.添加测试类进行加密
先在application.yml文件中设置密码,前后缀,密码加密方式
#加密
jasypt:
encryptor:
# 盐值
password: 123
# 指定加密方式 可以去官网查看支持的类型
algorithm: PBEWithMD5AndDES
property:
# 标识为加密属性的前缀
prefix: ENC(
# 标识为加密属性的后缀
suffix: )
@SpringBootTest(classes = RuoYiApplication.class) //指向自己的启动类
@ActiveProfiles("druid-dev") //没有配置文件可以不填
@RunWith(SpringRunner.class)
public class EncryptorTest {
//引入加密工具
@Resource
private StringEncryptor stringEncryptor;
@Test
public void test() {
//进行加密
String encrypt = stringEncryptor.encrypt("root");
System.out.println(encrypt);
//你的数据库的密码
String password = stringEncryptor.encrypt("123321");
System.out.println(password);
}
}
3.将加密结果替换到application.yml文件
替换数据源
pring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&allowMultiQueries=true
username: ENC(你的秘钥)
password: ENC(你的秘钥)
将秘钥配置到外部文件中
1.增加配置类
在项目启动的config包下增加配置类来读取配置
public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor{
/**
* 设置路径数组,保证线上和本地都能读取到该文件
*/
private static final String LOCATIONS [] = {"/home/ruoyi/jasypt.properties","D:\\ruoyi\\jasypt.properties"};
@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
for(String fileLocation : LOCATIONS){
File file = new File(fileLocation);
if (file.exists()) {
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
Properties properties = loadProperties(file);
propertySources.addFirst(new PropertiesPropertySource("Config", properties));
return ;
}
}
}
private Properties loadProperties(File f) {
FileSystemResource resource = new FileSystemResource(f);
try {
return PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Failed to load local settings from " + f.getAbsolutePath(), ex);
}
}
}
2.添加读取的配置文件
在resources下的META-INF文件夹中新增spring.factories文件,添加以下内容
org.springframework.boot.env.EnvironmentPostProcessor=你的实际路径.config.LocalSettingsEnvironmentPostProcessor
3.在服务器和本地添加指定的文件jasypt.properties
jasypt.encryptor.password=盐值
JDK1.8之前版本注意避坑
使用jasypt3.0启动时报:Failed to bind properties under 'xxx.xxx.xxx' to java.lang.String
解决方案
更换加密方式为PBEWithMD5AndDES 配置iv-generator-classname: org.jasypt.iv.NoIvGenerator
jasypt:
encryptor:
property:
prefix: ENC(
suffix: )
#更换加密方式 指定类名
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator