Jasypt安全框架提供了Spring的集成,主要是实现
PlaceholderConfigurerSupport类或者其子类。
在Sring 3.1之后,则推荐使用PropertySourcesPlaceholderConfigurer类作为属性替换配置类,这里Spring集成Jasypt则使用Jasypt对属性替换配置类的实现。EncryptablePropertySourcesPlaceholderConfigurer。
在Spring中集成比较容易,而且Jasypt官方也给出了配置Bean的方式和使用Jasypt标签的XML方式,而Spring boot集成就稍微有点不一样,需要创建一个自动配置类,并且创建一个注入PlaceholderConfigurerSupport的jasypt实现了的Bean .
下面是一个使用示例:
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JasyptConfig {
@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("tydic!@#");
config.setAlgorithm("PBEWithMD5AndDES");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
return encryptor;
}
}
配置文件的写入和Spring XML的基本类似。application.yml相当于applicationContext.xml,security.properties就是要进行属性替换的配置文件。
application.yml:
spring: datasource: url: jdbc:mysql://localhost:3306/abc?useSSL=false username: root password: ${jdbc.password}
security.properties:
jdbc.password=ENC(jWgGELCkuxRuCI2Aqa6cF9VCxYpuKEZr)
注意:在启动类中需配置注解才能生效
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.PropertySource;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
@SpringBootApplication
@EnableEncryptableProperties
@PropertySource(value = {"file:security.properties"})
public class SpringbootApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}