1. 增加依赖
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt-spring31</artifactId>
<version>1.9.2</version>
</dependency>
2. 编写EncryptPropertyPlaceholderAutoConfiguration类如下
package pn.lyndon.jasypt.configuration;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
import org.jasypt.spring31.properties.EncryptablePropertySourcesPlaceholderConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.Ordered;
import org.springframework.core.io.ClassPathResource;
/**
* Description:
*
* @author Administrator
* @create 2019-06-04 23:52
*/
@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class EncryptPropertyPlaceholderAutoConfiguration {
private static final String DB_SOURCE_CONFIG_FILE = "db.properties";
private static final String PASSWORD = "security";
@Bean
@ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
EncryptablePropertySourcesPlaceholderConfigurer
configurer = new EncryptablePropertySourcesPlaceholderConfigurer(standardPBEStringEncryptor());
configurer.setLocation(new ClassPathResource(DB_SOURCE_CONFIG_FILE));
return configurer;
}
@Bean
@ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
public static StandardPBEStringEncryptor standardPBEStringEncryptor() {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//TODO:
encryptor.setConfig(environmentStringPBEConfig());
return encryptor;
}
@Bean
@ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
public static EnvironmentStringPBEConfig environmentStringPBEConfig() {
EnvironmentStringPBEConfig environmentStringPBEConfig = new EnvironmentStringPBEConfig();
environmentStringPBEConfig.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
environmentStringPBEConfig.setPassword(PASSWORD);
return environmentStringPBEConfig;
}
public static void main(String[] args) {
StandardPBEStringEncryptor myStandardPBEStringEncryptor = standardPBEStringEncryptor();
String encryptUser = myStandardPBEStringEncryptor.encrypt("LyndonZhao");
System.out.println("encryptUser=" + encryptUser);
String encryptPassword = myStandardPBEStringEncryptor.encrypt("1q2w3e4r");
System.out.println("encryptPassword=" + encryptPassword);
}
}
3. db.properties配置
db.user=ENC(7h8LaiLxUVInVZAZk0SAMEdMjzWh15Tb)
db.password=ENC(wRU4IJc6bs6nccYcX6VVzlZ197/JTYtJ)