yaml配置文件加密

黄鹏宇 756 2022-08-23

一、需求

对yml文件中敏感信息进行加密

二、实现

使用jasypt

流程

1. 引包

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

2. 加盐加密敏感数据

2.1 第一种方式:在yaml中写入秘钥
jasypt:
  encryptor:
    password: customPwd #这里是自定义的密钥
2.2 第二种方式:命令行中传入秘钥

java -jar xxx.jar --jasypt.encryptor.password=customPwd

2.3 使用秘钥对敏感数据进行加密
    /**
     * 加密
     *
     * @param plaintext 明文    
     * @return
     */
    public static String encrypt(String plaintext) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        // 指定算法
        config.setAlgorithm("PBEWithMD5AndDES");
        // 指定秘钥,和yml配置文件中保持一致
        config.setPassword("customPwd");
        encryptor.setConfig(config);
        // 生成加密数据
        return encryptor.encrypt(plaintext);
    }

返回值即为加密后的信息

3. 在yaml中替换

使用 ENC() 将需要解密的字段包起来,比如:

datasource:
    username: ENC(JOr561eYOoZeaRhOrKINPT5nKGRShUtmpXHZPpC2fEKdp47VxbWTT8nTAvY3hxGL)
    password: ENC(j2iR9mfiX+Q2E2rNXIsrVb7KkLyLbtkYkNNh4uo0ek0jrC/HiLQnvrle8rPhi9f0E+SUIEuT7vmzl+8NQxZjPA==)

4. 启动时通过2.1或2.2传入秘钥,正常启动