SpringBoot 、Spring結合jasypt 敏感配置加密
由於配置中經常會涉及到許多敏感信息,考慮安全性可以做加密處理
Spring Boot中使用 jasypt 加密參數
1.添加maven依賴
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.8</version>
</dependency>
2. 生成加密參數
@Autowired
StringEncryptor encryptor;
@Test
public void getPass() {
//用戶名
String name = encryptor.encrypt("root");
//密碼
String password = encryptor.encrypt("root");
LOGGER.info("name={}", name);
LOGGER.info("password={}", password);
}
輸出示例
name=gf4AFiOfQ7sWWZMSPRgtOw==
password=hN2Ix9jNNt3U52AuVmL1gg==
3.配置加密參數
#加密密碼
spring.datasource.username=ENC(gf4AFiOfQ7sWWZMSPRgtOw==)
spring.datasource.password=ENC(hN2Ix9jNNt3U52AuVmL1gg==)
注意:加密后的字符串需要放到ENC里面
2.Spring 中使用 jasypt 加密參數
1. 添加maven依賴
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.8</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt-spring31</artifactId>
<version>1.9.0</version>
<scope>compile</scope>
</dependency>
2. 生成加密參數
public static void main(String[] args) {
BasicTextEncryptor encryptor = new BasicTextEncryptor();
//加密鹽
encryptor.setPassword("dev");
//用戶名
String name = encryptor.encrypt("fshows");
//密碼
String password = encryptor.encrypt("Fshows12#$");
LOGGER.info("name={}", name);
LOGGER.info("password={}", password);
}
3.Spring context 配置
<bean id="environmentVariablesConfiguration"
class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
<property name="algorithm" value="PBEWithMD5AndDES"/>
<property name="passwordEnvName" value="APP_ENCRYPTION_PASSWORD"/>
<!-- 需要與生成加密參數時使用的鹽保持一致 -->
<property name="password" value="dev"/>
</bean>
<bean id="configurationEncryptor"
class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
<property name="config" ref="environmentVariablesConfiguration"/>
</bean>
<bean id="propertyConfigurer"
class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">
<constructor-arg ref="configurationEncryptor"/>
<property name="locations">
<list>
<value>classpath:application-dev.properties</value>
</list>
</property>
</bean>
添加以上配置后
配置文件中加密了的參數會被解密出來。
4.配置加密參數
#加密密碼
spring.datasource.username=ENC(gf4AFiOfQ7sWWZMSPRgtOw==)
spring.datasource.password=ENC(hN2Ix9jNNt3U52AuVmL1gg==)
注意:加密后的字符串需要放到ENC里面