jasypt 集成spring、spring boot 加密

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014421556/article/details/78832427

简介

1、应用场景
针对properties和xml配置文件的敏感内容进行加密处理(比如数据库连接密码,通讯秘钥)
2、jasypt是一个java实现的安全框架

spring 配置

1、使用spring mvc集成,可继承 PropertyPlaceholderConfigurer子类
public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        //针对数据库连接密码加密
        if (propertyName.equalsIgnoreCase("spring.datasource.password")) {
            propertyValue = propertyValue.replace("eszxdr", "");
        }
        return super.convertProperty(propertyName, propertyValue);
    }
}
2、实例化自定义的PropertyPlaceholderConfigurer对象
使用xml方式配置
<bean id="propertyConfigurer" class="com.spring.boot.test.util.MyPropertPlaceholderConfigurer">
    <property name="locations">
        <list>
        <value>classpath:application.poperties</value>
        </list>
    </property>
</bean>
使用java配置方式
@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(){
    PropertyPlaceholderConfigurer placeholderConfigurer=new MyPropertyPlaceholderConfigurer();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource resource = resolver.getResource("classpath:application.properties");
    placeholderConfigurer.setLocation(resource);
    return placeholderConfigurer;
}
3、以上方式不支持yaml文件,无法使用spring boot,因为使用spring boot 数据库连接会在PropertyPlaceHolderConfigurer之前初始化

spring boot 配置

1、使用国外提供的集成工具包,github地址: https://github.com/ulisesbocchio/jasypt-spring-boot,该工具包支持yam和properties配置文件参数加密操作
2、jasypt 采用的算法默认是 PBEWithMD5AndDES, 该算法对同一明文每次生成的密文是不一样的
3、集成步骤
3.1 引入工具包依赖
java8
<dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot-starter</artifactId>
        <version>1.14</version>
</dependency>
java7
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>1.5-java7</version>
</dependency>
java6
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>1.5-java6</version>
</dependency>
3.2 配置密码
jasypt.encryptor.password=eszxdrtfc!!!
3.3 启动类配置注解  @EnableEncryptableProperties 以启动该功能
3.4 配置密文,使用加密命令生成密文,放在配置文件中
spring.datasource.password=ENC(P7xVJnbrn/MCzyVEOejTRwrrerer)

加密解密命令

java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="bWgq4JW/jLTBJ5kuUrR0e3s0JWEt5E7W" password=ACMP10171215 algorithm=PBEWithMD5AndDES
	  
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="bWgq4JW/jLTBJ5kuUrR0e3s0JWEt5E7W" password=ACMP10171215 algorithm=PBEWithMD5AndDES

猜你喜欢

转载自blog.csdn.net/u014421556/article/details/78832427
今日推荐