SpringBoot使用jasypt 给配置文件加密

165 阅读1分钟

SpringBoot使用jasypt

引入依赖

加密方面只需要引入这个

			<dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>3.0.4</version>
        </dependency>

因为要用到测试

再加上这个

 				<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

定义秘钥的几种方法

秘钥的定义 : jasypt.encryptor.password=yourpassword

  1. 这个你可以卸载yml配置文件里面,

  2. 你也可以写在idea的启动参数上面,

  3. 也可以在运维部署的时候再java -jar 加参数的方式加上去

千万记得你不要把这个秘钥暴露出去,不然别人也能破解你的加密信息

加密解密

先获取加解密对象

    @Autowired
    private StringEncryptor encryptor;

加密:encryptor.decrypt(code);

解密:encryptor.decrypt(code);

个人工具类分享

核心就是使用Spring的配置环境变量去动态获取参数

@Autowired
ConfigurableEnvironment env;

快速给配置文件的所有参数加密

 private void encodeFileByFileName(String yourFileName) {
        MutablePropertySources propertySources = env.getPropertySources();
        Iterator<PropertySource<?>> iterator =
                propertySources.iterator();

        while (iterator.hasNext()) {
            PropertySource<?> next = iterator.next();
            String name = next.getName();
            if (!name.contains(yourFileName)) {
                continue;
            }
            Map<String, Object> keyValues = (Map<String, Object>) next.getSource();
            keyValues.forEach((key, value) -> {
                log.info("变量:{}===>ENC({})",key,encryptor.encrypt(value.toString()));
            });
        }
    }

快速给所有加密的参数解密


private void decodeFileByFileName(String yourFileName) {
    MutablePropertySources propertySources = env.getPropertySources();
    Iterator<PropertySource<?>> iterator =
            propertySources.iterator();

    while (iterator.hasNext()) {
        PropertySource<?> next = iterator.next();
        String name = next.getName();
        if (!name.contains(yourFileName)) {
            continue;
        }
        Map<String, Object> keyValues = (Map<String, Object>) next.getSource();
        keyValues.forEach((key, value) -> {
            String valueStr = value.toString();
            if (valueStr.startsWith("ENC(")){
                log.info("变量:{}===>{}",key,encryptor.decrypt(valueStr.substring(4,valueStr.length()-1)));
            }

        });
    }
}