SpringBoot利用jasypt實現(xiàn)配置文件加密的完整指南
在實際開發(fā)中,若出于安全考慮不想暴露一些敏感的配置,如數(shù)據(jù)庫密碼等,就需要對配置文件進行加密,這個開源工具就很好幫我們實現(xiàn)這個需求
思路就是把配置文件中的值手動加密填上去,然后生產(chǎn)環(huán)境的秘鑰通過運行參數(shù)傳遞,開發(fā)測試環(huán)境可以直接把秘鑰寫在配置文件
1.引入依賴
非Spring Boot的使用方式可查閱官方文檔
github.com/ulisesbocchio/jasypt-spring-boot
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>${jasypt.spring.boot.version}</version> </dependency>
2.yml 加入配置
# 配置秘鑰 jasypt: encryptor: password: ${jasypt.encryptor.password:defaultPwd} # 需要加密的字段(明文:123456),需要使用ENC() 包裹 db: password: ENC(bVv/e16L6qPO+1pqEPMUYT5uW1EjsERTCoIliqABM+YMr6WURdxPy26La8wHCxgF)
3.測試
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = OrderApplication.class) public class DemoApplicationTest { @Autowired ConfigurableEnvironment environment; @Autowired StringEncryptor stringEncryptor; static { //指定運行環(huán)境密碼 System.setProperty("jasypt.encryptor.password", "password"); } @Test public void testEnvironmentProperties() { //解密密文 System.out.println(environment.getProperty("db.password")); } @Test public void encrypt() { //此處得到加密后的文本,放入yml System.out.println("密文: " + stringEncryptor.encrypt("123456")); } }
方法補充
SpringBoot配置文件加密
依賴
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.2</version> </dependency>
設置秘鑰
jasypt.encryptor.password=秘鑰 開發(fā)環(huán)境可以直接在配置文件中指定,生產(chǎn)環(huán)境可以使用啟動命理 --jasypt.encryptor.password=XXX 進行配置 ####加密解密
package com.itdfq.springboot; import org.jasypt.encryption.StringEncryptor; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; /** * @author duanfangqin 2022/7/11 10:56 * @implNote */ @SpringBootTest public class JasyptTest { @Autowired private StringEncryptor stringEncryptor; @Test public void encrypt(){ System.out.println(stringEncryptor.encrypt("qweasd123")); } @Test public void decrypt(){ System.out.println(stringEncryptor.decrypt("zI16ovOHuYiPIQaFx9cVlJF30bg5h3ql")); } }
配置文件密碼設置
#Redis服務器地址 spring.redis.host=119.3.234.108 #服務器密碼 spring.redis.password=ENC(nwElWn8r6aqVHDdAStIRiEXPAiE57qUF)
ENC(加密之后的密碼)
到此這篇關于SpringBoot利用jasypt實現(xiàn)配置文件加密的完整指南的文章就介紹到這了,更多相關SpringBoot jasypt配置文件加密內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java 關于eclipse導入項目發(fā)生的問題及解決方法(推薦)
下面小編就為大家分享一篇Java 關于eclipse導入項目發(fā)生的問題及解決方法(推薦),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12JavaWeb應用實例:用servlet實現(xiàn)oracle 基本增刪改查
本篇文章主要介紹了JavaWeb應用實例:用servlet實現(xiàn)oracle 基本增刪改查,非常具有實用價值,需要的朋友可以參考下。2017-01-01