1、介绍
jasypt-spring-boot
jasypt可以在springboot注入property和yml配置文件中的值之前,将配置文件中的值先预先处理的工具。可以用来实现对数据库账号密码等敏感信息密文解密的功能。
2、Maven依赖
1 2 3 4 5
| <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
|
3、注册解密Bean
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
| @Configuration public class EncryptionPropertyConfig {
@Bean(name="encryptablePropertyResolver") public EncryptablePropertyResolver encryptablePropertyResolver() { return new EncryptionPropertyResolver(); } class EncryptionPropertyResolver implements EncryptablePropertyResolver {
@Override public String resolvePropertyValue(String value) { if(StringUtils.isBlank(value)) { return value; } if(value.startsWith("DES@")) { return resolveDESValue(value.substring(4)); } return value; } private String resolveDESValue(String value) { return DESUtil.getDecryptString(value); }
} }
|
4、测试
4.1、property配置文件
1 2 3 4 5 6
| # 127.0.0.1的密文为e3zcSlYS29N0Y3i+mVdkgQ== datasource.host=DES@e3zcSlYS29N0Y3i+mVdkgQ== # 3306的密文为S6mBLsaSBEw= datasource.port=DES@S6mBLsaSBEw= datasource.database=test datasource.url=jdbc:mysql://${datasource.host}:${datasource.port}/${datasource.database}?useUnicode=true&characterEncoding=utf8
|
4.2、注入
1 2 3 4 5 6 7 8 9 10 11 12 13
| @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class ApplicationTests {
@Value("${datasource.url}") private String url; @Test public void testJasypt() { System.out.println(url); } }
|
4.3、输出
1
| jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
|