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註解)