springboot項(xiàng)目數(shù)據(jù)庫(kù)密碼如何加密
前言
在我們?nèi)粘i_(kāi)發(fā)中,我們可能很隨意把數(shù)據(jù)庫(kù)密碼直接明文暴露在配置文件中,在開(kāi)發(fā)環(huán)境可以這么做,但是在生產(chǎn)環(huán)境,是相當(dāng)不建議這么做,畢竟安全無(wú)小事,誰(shuí)也不知道哪天密碼就莫名其妙泄露了。今天就來(lái)聊聊在springboot項(xiàng)目中如何對(duì)數(shù)據(jù)庫(kù)密碼進(jìn)行加密
正文
方案一、使用druid數(shù)據(jù)庫(kù)連接池對(duì)數(shù)據(jù)庫(kù)密碼加密
1、pom.xml引入druid包
為了方便其他的操作,這邊直接引入druid的starter
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
2、利用com.alibaba.druid.filter.config.ConfigTools生成公私鑰
ps: 生成的方式有兩種,一種利用命令行生成,一種直接寫(xiě)個(gè)工具類(lèi)生成。本文示例直接采用工具類(lèi)生成
工具類(lèi)代碼如下
/**
* alibaba druid加解密規(guī)則:
* 明文密碼+私鑰(privateKey)加密=加密密碼
* 加密密碼+公鑰(publicKey)解密=明文密碼
*/
public final class DruidEncryptorUtils {
private static String privateKey;
private static String publicKey;
static {
try {
String[] keyPair = ConfigTools.genKeyPair(512);
privateKey = keyPair[0];
System.out.println(String.format("privateKey-->%s",privateKey));
publicKey = keyPair[1];
System.out.println(String.format("publicKey-->%s",publicKey));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
}
/**
* 明文加密
* @param plaintext
* @return
*/
@SneakyThrows
public static String encode(String plaintext){
System.out.println("明文字符串:" + plaintext);
String ciphertext = ConfigTools.encrypt(privateKey,plaintext);
System.out.println("加密后字符串:" + ciphertext);
return ciphertext;
}
/**
* 解密
* @param ciphertext
* @return
*/
@SneakyThrows
public static String decode(String ciphertext){
System.out.println("加密字符串:" + ciphertext);
String plaintext = ConfigTools.decrypt(publicKey,ciphertext);
System.out.println("解密后的字符串:" + plaintext);
return plaintext;
}
3、修改數(shù)據(jù)庫(kù)的配置文件內(nèi)容信息
a 、 修改密碼
把密碼替換成用DruidEncryptorUtils這個(gè)工具類(lèi)生成的密碼
password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}
b、 filter開(kāi)啟config
filter:
config:
enabled: true
c、配置connectionProperties屬性
connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}
ps: spring.datasource.publickey為工具類(lèi)生成的公鑰
附錄: 完整數(shù)據(jù)庫(kù)配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: ${DATASOURCE_URL:jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai}
username: ${DATASOURCE_USERNAME:root}
password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}
publickey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIvP9xF4RCM4oFiu47NZY15iqNOAB9K2Ml9fiTLa05CWaXK7uFwBImR7xltZM1frl6ahWAXJB6a/FSjtJkTZUJECAwEAAQ==
druid:
# 初始連接數(shù)
initialSize: 5
# 最小連接池?cái)?shù)量
minIdle: 10
# 最大連接池?cái)?shù)量
maxActive: 20
# 配置獲取連接等待超時(shí)的時(shí)間
maxWait: 60000
# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置檢測(cè)連接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 設(shè)置白名單,不填則允許所有訪問(wèn)
allow:
url-pattern: /druid/*
# 控制臺(tái)管理用戶(hù)名和密碼
login-username:
login-password:
filter:
stat:
enabled: true
# 慢SQL記錄
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
config:
enabled: true
connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}
方案二:使用jasypt對(duì)數(shù)據(jù)庫(kù)密碼加密
1、pom.xml引入jasypt包
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.verison}</version>
</dependency>
2、利用jasypt提供的工具類(lèi)對(duì)明文密碼進(jìn)行加密
加密工具類(lèi)如下
public final class JasyptEncryptorUtils {
private static final String salt = "lybgeek";
private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
static {
basicTextEncryptor.setPassword(salt);
}
private JasyptEncryptorUtils(){}
/**
* 明文加密
* @param plaintext
* @return
*/
public static String encode(String plaintext){
System.out.println("明文字符串:" + plaintext);
String ciphertext = basicTextEncryptor.encrypt(plaintext);
System.out.println("加密后字符串:" + ciphertext);
return ciphertext;
}
/**
* 解密
* @param ciphertext
* @return
*/
public static String decode(String ciphertext){
System.out.println("加密字符串:" + ciphertext);
ciphertext = "ENC(" + ciphertext + ")";
if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)){
String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext,basicTextEncryptor);
System.out.println("解密后的字符串:" + plaintext);
return plaintext;
}
System.out.println("解密失敗");
return "";
}
}
3、修改數(shù)據(jù)庫(kù)的配置文件內(nèi)容信息
a、 用ENC包裹用JasyptEncryptorUtils 生成的加密串
password: ${DATASOURCE_PWD:ENC(P8m43qmzqN4c07DCTPey4Q==)}
b、 配置密鑰和指定加解密算法
jasypt:
encryptor:
password: lybgeek
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
因?yàn)槲夜ぞ哳?lèi)使用的是加解密的工具類(lèi)是BasicTextEncryptor,其對(duì)應(yīng)配置加解密就是PBEWithMD5AndDES和org.jasypt.iv.NoIvGenerator
ps: 在生產(chǎn)環(huán)境中,建議使用如下方式配置密鑰,避免密鑰泄露
java -jar -Djasypt.encryptor.password=lybgeek
附錄: 完整數(shù)據(jù)庫(kù)配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: ${DATASOURCE_URL:ENC(kT/gwazwzaFNEp7OCbsgCQN7PHRohaTKJNdGVgLsW2cH67zqBVEq7mN0BTIXAeF4/Fvv4l7myLFx0y6ap4umod7C2VWgyRU5UQtKmdwzQN3hxVxktIkrFPn9DM6+YahM0xP+ppO9HaWqA2ral0ejBCvmor3WScJNHCAhI9kHjYc=)}
username: ${DATASOURCE_USERNAME:ENC(rEQLlqM5nphqnsuPj3MlJw==)}
password: ${DATASOURCE_PWD:ENC(P8m43qmzqN4c07DCTPey4Q==)}
druid:
# 初始連接數(shù)
initialSize: 5
# 最小連接池?cái)?shù)量
minIdle: 10
# 最大連接池?cái)?shù)量
maxActive: 20
# 配置獲取連接等待超時(shí)的時(shí)間
maxWait: 60000
# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置檢測(cè)連接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 設(shè)置白名單,不填則允許所有訪問(wèn)
allow:
url-pattern: /druid/*
# 控制臺(tái)管理用戶(hù)名和密碼
login-username:
login-password:
filter:
stat:
enabled: true
# 慢SQL記錄
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
jasypt:
encryptor:
password: lybgeek
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
方案三:自定義實(shí)現(xiàn)
實(shí)現(xiàn)原理: 利用spring后置處理器修改DataSource
1、自定義加解密工具類(lèi)
/**
* 利用hutool封裝的加解密工具,以AES對(duì)稱(chēng)加密算法為例
*/
public final class EncryptorUtils {
private static String secretKey;
static {
secretKey = Hex.encodeHexString(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());
System.out.println("secretKey-->" + secretKey);
System.out.println("--------------------------------------------------------------------------------------");
}
/**
* 明文加密
* @param plaintext
* @return
*/
@SneakyThrows
public static String encode(String plaintext){
System.out.println("明文字符串:" + plaintext);
byte[] key = Hex.decodeHex(secretKey.toCharArray());
String ciphertext = SecureUtil.aes(key).encryptHex(plaintext);
System.out.println("加密后字符串:" + ciphertext);
return ciphertext;
}
/**
* 解密
* @param ciphertext
* @return
*/
@SneakyThrows
public static String decode(String ciphertext){
System.out.println("加密字符串:" + ciphertext);
byte[] key = Hex.decodeHex(secretKey.toCharArray());
String plaintext = SecureUtil.aes(key).decryptStr(ciphertext);
System.out.println("解密后的字符串:" + plaintext);
return plaintext;
}
/**
* 明文加密
* @param plaintext
* @return
*/
@SneakyThrows
public static String encode(String secretKey,String plaintext){
System.out.println("明文字符串:" + plaintext);
byte[] key = Hex.decodeHex(secretKey.toCharArray());
String ciphertext = SecureUtil.aes(key).encryptHex(plaintext);
System.out.println("加密后字符串:" + ciphertext);
return ciphertext;
}
/**
* 解密
* @param ciphertext
* @return
*/
@SneakyThrows
public static String decode(String secretKey,String ciphertext){
System.out.println("加密字符串:" + ciphertext);
byte[] key = Hex.decodeHex(secretKey.toCharArray());
String plaintext = SecureUtil.aes(key).decryptStr(ciphertext);
System.out.println("解密后的字符串:" + plaintext);
return plaintext;
}
}
2、編寫(xiě)后置處理器
public class DruidDataSourceEncyptBeanPostProcessor implements BeanPostProcessor {
private CustomEncryptProperties customEncryptProperties;
private DataSourceProperties dataSourceProperties;
public DruidDataSourceEncyptBeanPostProcessor(CustomEncryptProperties customEncryptProperties, DataSourceProperties dataSourceProperties) {
this.customEncryptProperties = customEncryptProperties;
this.dataSourceProperties = dataSourceProperties;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof DruidDataSource){
if(customEncryptProperties.isEnabled()){
DruidDataSource druidDataSource = (DruidDataSource)bean;
System.out.println("--------------------------------------------------------------------------------------");
String username = dataSourceProperties.getUsername();
druidDataSource.setUsername(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),username));
System.out.println("--------------------------------------------------------------------------------------");
String password = dataSourceProperties.getPassword();
druidDataSource.setPassword(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),password));
System.out.println("--------------------------------------------------------------------------------------");
String url = dataSourceProperties.getUrl();
druidDataSource.setUrl(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),url));
System.out.println("--------------------------------------------------------------------------------------");
}
}
return bean;
}
}
3、修改數(shù)據(jù)庫(kù)的配置文件內(nèi)容信息
a 、 修改密碼
把密碼替換成用自定義加密工具類(lèi)生成的加密密碼
password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}
b 、 指定密鑰和開(kāi)啟加密功能
custom:
encrypt:
enabled: true
secret-key: 2f8ba810011e0973728afa3f28a0ecb6
ps: 同理secret-key最好也不要直接暴露在配置文件中,可以用-Dcustom.encrypt.secret-key指定
附錄: 完整數(shù)據(jù)庫(kù)配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
url: ${DATASOURCE_URL:dcb268cf3a2626381d2bc5c96f94fb3d7f99352e0e392362cb818a321b0ca61f3a8dad3aeb084242b745c61a1d3dc244ed1484bf745c858c44560dde10e60e90ac65f77ce2926676df7af6b35aefd2bb984ff9a868f1f9052ee9cae5572fa015b66a602f32df39fb1bbc36e04cc0f148e4d610a3e5d54f2eb7c57e4729c9d7b4}
username: ${DATASOURCE_USERNAME:61db3bf3c6d3fe3ce87549c1af1e9061}
password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}
druid:
# 初始連接數(shù)
initialSize: 5
# 最小連接池?cái)?shù)量
minIdle: 10
# 最大連接池?cái)?shù)量
maxActive: 20
# 配置獲取連接等待超時(shí)的時(shí)間
maxWait: 60000
# 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置檢測(cè)連接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 設(shè)置白名單,不填則允許所有訪問(wèn)
allow:
url-pattern: /druid/*
# 控制臺(tái)管理用戶(hù)名和密碼
login-username:
login-password:
filter:
stat:
enabled: true
# 慢SQL記錄
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
custom:
encrypt:
enabled: true
secret-key: 2f8ba810011e0973728afa3f28a0ecb6
總結(jié)
上面三種方案,個(gè)人比較推薦用jasypt這種方案,因?yàn)樗粌H可以對(duì)密碼加密,也可以對(duì)其他內(nèi)容加密。而druid只能對(duì)數(shù)據(jù)庫(kù)密碼加密。至于自定義的方案,屬于練手,畢竟開(kāi)源已經(jīng)有的東西,就不要再自己造輪子了。
最后還有一個(gè)注意點(diǎn)就是jasypt如果是高于2版本,且以低于3.0.3,會(huì)導(dǎo)致配置中心,比如apollo或者nacos的動(dòng)態(tài)刷新配置失效(最新版的3.0.3官方說(shuō)已經(jīng)修復(fù)了這個(gè)問(wèn)題)。

如果有使用配置中心的話,jasypt推薦使用3版本以下,或者使用3.0.3版本
demo鏈接
到此這篇關(guān)于springboot項(xiàng)目數(shù)據(jù)庫(kù)密碼如何加密的文章就介紹到這了,更多相關(guān)springboot數(shù)據(jù)庫(kù)密碼加密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatisplus 的SQL攔截器實(shí)現(xiàn)關(guān)聯(lián)查詢(xún)功能
大家都知道m(xù)ybatisplus不支持關(guān)聯(lián)查詢(xún),后來(lái)學(xué)習(xí)研究發(fā)現(xiàn)mybatisplus的SQL攔截器可以實(shí)現(xiàn)這一操作,下面小編給大家分享我的demo實(shí)現(xiàn)基本的關(guān)聯(lián)查詢(xún)功能沒(méi)有問(wèn)題,對(duì)mybatisplus關(guān)聯(lián)查詢(xún)相關(guān)知識(shí)感興趣的朋友一起看看吧2021-06-06
Java深入數(shù)據(jù)結(jié)構(gòu)理解掌握抽象類(lèi)與接口
在類(lèi)中沒(méi)有包含足夠的信息來(lái)描繪一個(gè)具體的對(duì)象,這樣的類(lèi)稱(chēng)為抽象類(lèi),接口是Java中最重要的概念之一,它可以被理解為一種特殊的類(lèi),不同的是接口的成員沒(méi)有執(zhí)行體,是由全局常量和公共的抽象方法所組成,本文給大家介紹Java抽象類(lèi)和接口,感興趣的朋友一起看看吧2022-05-05
Java使用PDFBox實(shí)現(xiàn)操作PDF文檔
這篇文章主要為大家詳細(xì)介紹了Java如何使用PDFBox實(shí)現(xiàn)操作PDF文檔,例如添加本地圖片、添加網(wǎng)絡(luò)圖片、圖片寬高自適應(yīng)、圖片水平垂直居中對(duì)齊等功能,需要的可以了解下2024-03-03
SpringQuartz集群支持JDBC存儲(chǔ)與分布式執(zhí)行的最佳實(shí)踐
SpringQuartz集群通過(guò)JDBC存儲(chǔ)和分布式執(zhí)行機(jī)制,有效解決了單點(diǎn)故障和擴(kuò)展性問(wèn)題,本文將詳細(xì)介紹SpringQuartz集群支持的實(shí)現(xiàn)原理、配置方法和最佳實(shí)踐,助力開(kāi)發(fā)者構(gòu)建穩(wěn)定可靠的分布式調(diào)度系統(tǒng),感興趣的朋友一起看看吧2025-04-04
spring帶bean和config如何通過(guò)main啟動(dòng)測(cè)試
這篇文章主要介紹了spring帶bean和config,通過(guò)main啟動(dòng)測(cè)試,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
教你怎么用java實(shí)現(xiàn)客戶(hù)端與服務(wù)器一問(wèn)一答
這篇文章主要介紹了教你怎么用java實(shí)現(xiàn)客戶(hù)端與服務(wù)器一問(wèn)一答,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
elasticsearch集群查詢(xún)超10000的解決方案
ES為了避免用戶(hù)的過(guò)大分頁(yè)請(qǐng)求造成ES服務(wù)所在機(jī)器內(nèi)存溢出,默認(rèn)對(duì)深度分頁(yè)的條數(shù)進(jìn)行了限制,默認(rèn)的最大條數(shù)是10000條,這篇文章主要給大家介紹了關(guān)于elasticsearch集群查詢(xún)超10000的解決方案,需要的朋友可以參考下2024-08-08
簡(jiǎn)單講解java中throws與throw的區(qū)別
這篇文章主要介紹了簡(jiǎn)單講解java中throws與throw的區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07

