SpringBoot 、Spring结合jasypt 敏感配置加密

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里面

posted @ 2018-10-29 19:02  码农界的苦逼猿  阅读(3081)  评论(0编辑  收藏  举报