SpringBoot配置文件加密

1 场景

SpringBoot的项目发布时,线上生产的线上配置文件中ip密码等敏感信息如果明文配置会暴出来。虽然数据库可以限制访问的IP来杜绝密码泄露出去后代码的非法访问问题。但是有些外部邮箱密码第三方访问接口密钥等不可控的外部接口,无法限制访问者的IP,仍然有安全问题。

2 加密方式

这里采用jasypt对SpringBoot中的配置文件信息进行加密。

配置文件中的密码信息为加密后的字符串,通过在启动时指定jasypt私钥,来进行自动解密运维人员保管维护解密的私钥

加密步骤:

(1)配置jasypt密钥,对密码进行加密

(2)将加密后的字符串以ENC(xxxx)的格式配置在配置文件中

(3)启动jar后,在idea启动参数中加上--jasypt.encryptor.password=xxxxxx指定jasypt密钥

SpringBoot配置文件加密_第1张图片

3 加密过程

  maven依赖

    com.github.ulisesbocchio
    jasypt-spring-boot-starter
    2.1.2

生产环境采用启动参数的形式传入:--jasypt.encryptor.password=xxxxxx

如:

java -jar xxx.jar --jasypt.encryptor.password=xxxxxx
加密

对字符串进行加密:

package com.zx.springboot.util;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

public class EncryptorUtil {

    public static void main(String[] args) {
        // 加密内容
        String secretKey = "root";
        // 项目启动的密钥
        String password = "xxxxxx";

        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setPassword(password);

        String encryptedKey = encryptor.encrypt(secretKey);
        // 输出: 3qJuG7KpuRwXhy2DfcosDw==
        System.out.println("Encrypted Key: " + encryptedKey);
    }
}
3.4 配置密文

将密码加密后生成的密文,以ENC(xxxx)的形式配置在配置文件中。

如下:

spring:
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://xxx.xxx.xxx.xxx:xxx/xxx
        username: ENC(3qJuG7KpuRwXhy2DfcosDw==)
        password: password

你可能感兴趣的:(SpringBoot配置文件加密)