引入jasypt
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
生成要加密的字符串
將數(shù)據(jù)庫(kù)的用戶名和密碼進(jìn)行加密
public static void main(String[] args) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//加密所需的密鑰
textEncryptor.setPassword("G0CvDz7oJn6");
//要加密的數(shù)據(jù)(數(shù)據(jù)庫(kù)的用戶名或密碼)
String username = textEncryptor.encrypt("root");
String password = textEncryptor.encrypt("root123");
System.out.println("username:"+username);
System.out.println("password:"+password);
}
輸出信息為:
username:i8QgEN4uOy2E1rHzrpSTYA==
password:6eaMh/RX5oXUVca9ignvtg==
或者使用Maven下載好的jar包加密\Maven\org\jasypt\jasypt\1.9.2\jasypt-1.9.2.jar
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=G0CvDz7oJn6 algorithm=PBEWithMD5AndDES input=root
輸出信息為:
----ENVIRONMENT-----------------
Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.171-b11
----ARGUMENTS-------------------
input: root
algorithm: PBEWithMD5AndDES
password: G0CvDz7oJn6
----OUTPUT----------------------
Gvkoz+sbFWiRe3ECtizV1A==
拷貝-OUTPUT-下的結(jié)果即可
配置properties文件
將生成的加密串配置ENC(加密串)到application.properties中
# 加密所需的密鑰
jasypt.encryptor.password=G0CvDz7oJn6
# 默認(rèn)加密方式PBEWithMD5AndDES,可以更改為PBEWithMD5AndTripleDES
# jasypt.encryptor.algorithm=PBEWithMD5AndDES
spring.datasource.username=ENC(6eaMh/RX5oXUVca9ignvtg==)
spring.datasource.password=ENC(6eaMh/RX5oXUVca9ignvtg==)
加密方式對(duì)應(yīng)的類為BasicTextEncryptor和StrongTextEncryptor
public BasicTextEncryptor() {
super();
this.encryptor = new StandardPBEStringEncryptor();
this.encryptor.setAlgorithm("PBEWithMD5AndDES");
}
public StrongTextEncryptor() {
super();
this.encryptor = new StandardPBEStringEncryptor();
this.encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
}
類圖
部署時(shí)配置密鑰值
為了防止密鑰泄露,反解出密碼.可以在項(xiàng)目部署的時(shí)候使用命令傳入密鑰值
java -jar -Djasypt.encryptor.password=G0CvDz7oJn6 xxx.jar
或者在服務(wù)器的環(huán)境變量里配置,進(jìn)一步提高安全性
打開/etc/profile文件
vim /etc/profile
文件末尾插入
export JASYPT_PASSWORD = G0CvDz7oJn6
編譯
source /etc/profile
運(yùn)行
java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar