spring boot 配置文件中密码加密

spring boot 的配置文件中,一般会配置一些中间件的密码,比如:redis,mq,数据库,这对于安全性有要求的公司,不允许这么操作。想对项目代码改动较小的话,可以试试jasypt.

本文以3.0为例,2.0版本会有所不一样,在加密算法上.

1、在maven的pom.xml中加入依赖

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

2、修改application.yml配置文件

spring:
  main:
    allow-bean-definition-overriding: true
  profiles:
    active: dev

jasypt:
  encryptor:
    password: EbfYkitulv73I2p0mXI50JMXoaxZTKJ0
    algorithm: PBEWithMD5AndDES
    iv-generator-classname: org.jasypt.iv.NoIvGenerator

password为密钥,algorithm为加盐值

3、密码加密

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

/**
 * @Author huangxiong
 * @Date 2021/3/16
 * @Description
 **/
public class Encryptor {
    private static final String ALGORITHM_INFO = "PBEWithMD5AndDES";
    private static final String PASSWORD_INFO = "EbfYkitulv73I2p0mXI50JMXoaxZTKJ0";
    public static void main(String[] args) {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        //配置文件中配置如下的算法
        standardPBEStringEncryptor.setAlgorithm(ALGORITHM_INFO);
        //配置文件中配置的password
        standardPBEStringEncryptor.setPassword(PASSWORD_INFO);
        //解密后的文本
        System.out.println("redis=" + standardPBEStringEncryptor.encrypt("redis密码"));
        System.out.println("mysql=" + standardPBEStringEncryptor.encrypt("数据库密码"));
        System.out.println("mq=" + standardPBEStringEncryptor.encrypt("mq密码"));
    }
}

password为密钥,algorithm为加盐值,对应第二步配置的值

4、将输出的密码,加到配置文件里,比如:

redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: ENC(gRxhQxtee4jUp+fvYE+hTgyDWyfyXarb)

ENC里面为加密后的值

 

(PS:如果不成功,可以试试在项目的启动main函数中,加入@EnableEncryptableProperties注解)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章