在实际开发中,若出于安全考虑不想暴露一些敏感的配置,如数据库密码等,就需要对配置文件进行加密,这个开源工具就很好帮我们实现这个需求
思路就是把配置文件中的值手动加密填上去,然后生产环境的秘钥通过运行参数传递,开发测试环境可以直接把秘钥写在配置文件
- 引入依赖 非Spring Boot的使用方式可查阅官方文档
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.spring.boot.version}</version>
</dependency>
- yml 加入配置
# 配置秘钥
jasypt:
encryptor:
password: ${jasypt.encryptor.password:defaultPwd}
# 需要加密的字段(明文:123456),需要使用ENC() 包裹
db:
password: ENC(bVv/e16L6qPO+1pqEPMUYT5uW1EjsERTCoIliqABM+YMr6WURdxPy26La8wHCxgF)
- 测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = OrderApplication.class)
public class DemoApplicationTest {
@Autowired
ConfigurableEnvironment environment;
@Autowired
StringEncryptor stringEncryptor;
static {
//指定运行环境密码
System.setProperty("jasypt.encryptor.password", "password");
}
@Test
public void testEnvironmentProperties() {
//解密密文
System.out.println(environment.getProperty("db.password"));
}
@Test
public void encrypt() {
//此处得到加密后的文本,放入yml
System.out.println("密文: " + stringEncryptor.encrypt("123456"));
}
}