springboot項(xiàng)目數(shù)據(jù)庫密碼如何加密
前言
在我們?nèi)粘i_發(fā)中,我們可能很隨意把數(shù)據(jù)庫密碼直接明文暴露在配置文件中,在開發(fā)環(huán)境可以這么做,但是在生產(chǎn)環(huán)境,是相當(dāng)不建議這么做,畢竟安全無小事,誰也不知道哪天密碼就莫名其妙泄露了。今天就來聊聊在springboot項(xiàng)目中如何對數(shù)據(jù)庫密碼進(jìn)行加密
正文
方案一、使用druid數(shù)據(jù)庫連接池對數(shù)據(jù)庫密碼加密
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: 生成的方式有兩種,一種利用命令行生成,一種直接寫個(gè)工具類生成。本文示例直接采用工具類生成
工具類代碼如下
/**
* 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ù)庫的配置文件內(nèi)容信息
a 、 修改密碼
把密碼替換成用DruidEncryptorUtils這個(gè)工具類生成的密碼
password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}
b、 filter開啟config
filter:
config:
enabled: true
c、配置connectionProperties屬性
connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}
ps: spring.datasource.publickey為工具類生成的公鑰
附錄: 完整數(shù)據(jù)庫配置
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)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置檢測連接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 設(shè)置白名單,不填則允許所有訪問
allow:
url-pattern: /druid/*
# 控制臺管理用戶名和密碼
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對數(shù)據(jù)庫密碼加密
1、pom.xml引入jasypt包
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.verison}</version>
</dependency>
2、利用jasypt提供的工具類對明文密碼進(jìn)行加密
加密工具類如下
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ù)庫的配置文件內(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)槲夜ぞ哳愂褂玫氖羌咏饷艿墓ぞ哳愂荁asicTextEncryptor,其對應(yīng)配置加解密就是PBEWithMD5AndDES和org.jasypt.iv.NoIvGenerator
ps: 在生產(chǎn)環(huán)境中,建議使用如下方式配置密鑰,避免密鑰泄露
java -jar -Djasypt.encryptor.password=lybgeek
附錄: 完整數(shù)據(jù)庫配置
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)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置檢測連接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 設(shè)置白名單,不填則允許所有訪問
allow:
url-pattern: /druid/*
# 控制臺管理用戶名和密碼
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、自定義加解密工具類
/**
* 利用hutool封裝的加解密工具,以AES對稱加密算法為例
*/
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、編寫后置處理器
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ù)庫的配置文件內(nèi)容信息
a 、 修改密碼
把密碼替換成用自定義加密工具類生成的加密密碼
password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}
b 、 指定密鑰和開啟加密功能
custom:
encrypt:
enabled: true
secret-key: 2f8ba810011e0973728afa3f28a0ecb6
ps: 同理secret-key最好也不要直接暴露在配置文件中,可以用-Dcustom.encrypt.secret-key指定
附錄: 完整數(shù)據(jù)庫配置
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)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置檢測連接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 設(shè)置白名單,不填則允許所有訪問
allow:
url-pattern: /druid/*
# 控制臺管理用戶名和密碼
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可以對密碼加密,也可以對其他內(nèi)容加密。而druid只能對數(shù)據(jù)庫密碼加密。至于自定義的方案,屬于練手,畢竟開源已經(jīng)有的東西,就不要再自己造輪子了。
最后還有一個(gè)注意點(diǎn)就是jasypt如果是高于2版本,且以低于3.0.3,會導(dǎo)致配置中心,比如apollo或者nacos的動(dòng)態(tài)刷新配置失效(最新版的3.0.3官方說已經(jīng)修復(fù)了這個(gè)問題)。

如果有使用配置中心的話,jasypt推薦使用3版本以下,或者使用3.0.3版本
demo鏈接
到此這篇關(guān)于springboot項(xiàng)目數(shù)據(jù)庫密碼如何加密的文章就介紹到這了,更多相關(guān)springboot數(shù)據(jù)庫密碼加密內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Idea導(dǎo)入多個(gè)maven項(xiàng)目到同一目錄下的方法示例
這篇文章主要介紹了Idea導(dǎo)入多個(gè)maven項(xiàng)目到同一目錄下,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Java基于servlet監(jiān)聽器實(shí)現(xiàn)在線人數(shù)監(jiān)控功能的方法
這篇文章主要介紹了Java基于servlet監(jiān)聽器實(shí)現(xiàn)在線人數(shù)監(jiān)控功能的方法,結(jié)合實(shí)例形式分析了ServletContextListener監(jiān)聽功能的相關(guān)使用步驟與操作技巧,需要的朋友可以參考下2018-01-01
SpringBoot項(xiàng)目使用mybatis-plus代碼生成的實(shí)例詳解
mybatis-plus是mybatis的增強(qiáng),不對mybatis做任何改變,涵蓋了代碼生成,自定義ID生成器,快速實(shí)現(xiàn)CRUD,自動(dòng)分頁,邏輯刪除等功能。本文就來講講SpringBoot項(xiàng)目如何使用mybatis-plus實(shí)現(xiàn)代碼生成,需要的可以了解一下2022-10-10
SpringBoot 如何使用RestTemplate來調(diào)用接口
這篇文章主要介紹了SpringBoot 如何使用RestTemplate來調(diào)用接口方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
Spring Security基于散列加密方案實(shí)現(xiàn)自動(dòng)登錄功能
為了提高項(xiàng)目的用戶體驗(yàn),我們可以在項(xiàng)目中添加自動(dòng)登錄功能,當(dāng)然也要給用戶提供退出登錄的功能。接下來學(xué)習(xí)下Spring Security基于散列加密方案實(shí)現(xiàn)自動(dòng)登錄功能,一起看看吧2021-09-09

