写一个工具类 EncryptUtil.java
,完成加密解密方法
// 加密
public static String encode(String value){
if(StringUtils.isNotBlank(value)){
Base64 base64 = new Base64();
return new String(base64.encode(value.getBytes()));
}
return null;
}
// 解密
public static String decode(String value){
if(StringUtils.isNotBlank(value)){
Base64 base64 = new Base64();
return new String(base64.decode(value.getBytes()));
}
return null;
}
在配置文件application.yml
里,使用加密后的值,加个特殊的前缀,例如SEC@
spring:
datasource:
url: jdbc:mysql://192.168.0.111:3306/test
username: SEC@cm9vdA==
password: SEC@TXlzcWxAMTIz
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
在pom.xml
中添加jasypt-spring-boot-starter
依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
写一个Configuration
bean,实现jasypt
提供的EncryptablePropertyResolver
接口,在resolvePropertyValue(String value)
方法中将配置文件中前缀为SEC@
的加了密的value截取出来,使用之前写好的解密方法进行解密。
import com.swcares.attms.util.EncryptUtil;
import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EncryptionPropertyConfig {
@Bean(name = "encryptablePropertyResolver")
public EncryptablePropertyResolver encryptablePropertyResolver() {
return new EncryptionPropertyResolver();
}
class EncryptionPropertyResolver implements EncryptablePropertyResolver {
@Override
public String resolvePropertyValue(String value) {
if (value.startsWith("SEC@")) {
String propertyValue = value.substring(4);
return EncryptUtil.decode(propertyValue);
}
return value;
}
}
}
之前写过一个Spring项目数据库密码加密,是普通的Spring项目的实现,原理都一样,加个密再用,至少比明文密码安全一点。
The end.