在Spring boot開發(fā)中薯嗤,需要在application.yml文件里配置數(shù)據(jù)庫的連接信息豪墅,或者在啟動時傳入數(shù)據(jù)庫密碼,如果不加密铣口,傳明文滤钱,數(shù)據(jù)庫就直接暴露了,相當(dāng)于"裸奔"了脑题,因此需要進行加密處理才行件缸。
第一步:引入jar包【版本隨意】
如果使用@SpringBootApplication注解啟動的項目,只需增加maven依賴:
pom添加依賴
<!-- 數(shù)據(jù)庫加密配置-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
我們對信息加解密是使用這個jar包的:
1638242146(1).png
第二步:獲取加密串
package com.test;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.Test;
public class JasyptTest {
@Test
public void testEncrypt() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法叔遂,這個算法是默認的
config.setPassword("密鑰"); // 加密的密鑰他炊,必須為ASCll碼
standardPBEStringEncryptor.setConfig(config);
String plainText = "明文字符串"; //如:數(shù)據(jù)庫密碼
String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
System.out.println(encryptedText);
}
@Test
public void testDe() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("密鑰");
standardPBEStringEncryptor.setConfig(config);
String encryptedText = "加密串"; //執(zhí)行上面方法得到的加密串
String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
System.out.println(plainText);
}
}
第三步:配置數(shù)據(jù)庫信息
加密串拿到了,現(xiàn)在來修改application.yml的配置已艰,我們把加密串放在ENC(加密串)即可:
spring:
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: 數(shù)據(jù)庫地址
username: 用戶名
password: ENC(密碼加密串)
第四步:配置自動解密密鑰
啟動時需要配置 秘鑰
方案一:在yml中加這個密鑰的配置痊末,在項目啟動的時候,會根據(jù)密鑰自動解密ENC(加密串)所代表的數(shù)據(jù)信息:
jasypt:
encryptor:
password: 密鑰
..........................................
方案二:將秘鑰加入啟動參數(shù)
image
image.png
image
發(fā)布:應(yīng)用發(fā)布Linux系統(tǒng)的Tomcat配置
打開tomcat的bin目錄下的catalina.sh文件哩掺,添加jasypt鹽值
image.png
配置如下
JAVA_OPTS="-Djasypt.encryptor.password=dkycs"
[圖片上傳中...(image.png-c4abb9-1641289038991-0)]
image.png
【注】github上參考項目地址:https://github.com/chyanwu/erp-framework