【SpringBoot】SpringBoot下使用Jasypt工具类加密属性配置

410 阅读1分钟

本文已参与「新人创作礼」活动, 一起开启掘金创作之路。

概述

  • application.yml中的账号密码明文展示,存在安全隐患
  • 用Jasypt对配置文件的账号密码加密,增加系统的安全性

集成jasypt

方式一:直接加依赖

@SpringBootApplication@EnableAutoConfiguration
public class MyApplication {
    ...
}

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

方式二:使用全局启用注解

@EnableEncryptableProperties
public class MyApplication {
    ...
}

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

方式三:使用局部启用注解

@Configuration
@EncryptablePropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")
public class MyApplication {
    ...
}
<dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot</artifactId>
        <version>2.1.0</version>
</dependency>

编写工具类

/**
 * @version V1.0
 * @author: yqh
 * @date: 2021/11/08
 * @Description: Jasypt加密工具类
 */
public enum  JasyptEncryptUtil {
    /**
     * 唯一实例,使工具类单例化
     */
    INSTANCE;

    private static final  JasyptStatelessService jasyptStatelessService = new JasyptStatelessService();

    public static String encrypt(String input,String password,String algorithm){
        final String encrypt = jasyptStatelessService.encrypt(input, password, null, null, algorithm, null, null, null, null,
                null, null, null, null, null, null,
                null, null, null, null, null, null, null);
        return encrypt;
    }

    /**
     * 使用默认加密算法:PBEWithMD5AndDES
     * @param input 要加密的内容
     * @param password 密钥
     * @return
     */
    public static String encrypt(String input,String password){
        return encrypt(input,password,"PBEWithMD5AndDES");
    }

    public static void main(String[] args){
        System.out.println(encrypt("123456","idv2021"));
    }

}

配置jasypt

自定义前缀后缀

jasypt:
    encryptor:
    	property:
    		prefix: "LIN@["
      		suffix: "]"

则加密后在配置文件中的示例如:LIN@[uOTcNV1VT3tIWw5WPLX5pQ==]

配置秘钥(盐值)

普通方式(不安全)

jasypt:
    encryptor:
    	password: password

安全性较高的密钥配置方式:系统属性、命令行或是环境变量

命令行示例

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

环境变量示例

# 打开/etc/profile文件
vim /etc/profile

# 文件末尾插入
export JASYPT_PASSWORD = xxxx
java -jar xxx.jar --jasypt.encryptor.password=${JASYPT_PASSWORD} &