基於SpringCloud的Microservices架構實戰案例-配置文件屬性內容加解密java
使用過SpringBoot配置文件的朋友都知道,資源文件中的內容一般狀況下是明文顯示,安全性就比較低一些。打開application.properties或application.yml,好比mysql登錄密碼,redis登錄密碼以及第三方的密鑰等等盡收眼底,這裏介紹一個加解密組件,提升一些屬性配置的安全性。
jasypt[http://www.jasypt.org/],官方給出的釋意是:mysql
Jasypt is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.
simplemall項目也採用此加密組件,結合spring boot使用。國外大神Ulises Bocchio寫了一個spring boot下用的工具包,Github地址:https://github.com/ulisesbocc...,下面介紹下jasypt在spring boot的用法。git
一、引入maven依賴程序員
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter --> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>1.14</version> </dependency>
二、配置加密參數github
jasypt: encryptor: #這裏能夠理解成是加解密的時候使用的密鑰 password: your password
jasypt.encryptor.password=your password
此處密碼的生成能夠經過兩種方式生成,寫main函數生成和直接採用jar命令方式。本處採用main函數的方式,此代碼位於account-serv的test包中。web
package com.simplemall.account.test; import org.jasypt.encryption.StringEncryptor; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.simplemall.account.AccountServApplication; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringBootTest(classes = AccountServApplication.class) public class Jasyptest { @Autowired StringEncryptor encryptor; @Test public void getPass() { String result = encryptor.encrypt("root"); System.out.println(result); Assert.assertTrue(result.length() > 0); } }
三、升級application.properties/yml中相應的配置項redis
#mysql database config spring.datasource.url=jdbc:mysql://localhost:3306/micro_account?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull #use jasypt to encrypt username/password spring.datasource.username=root spring.datasource.password=root spring.datasource.driverClassName=com.mysql.jdbc.Driver
#mysql database config spring.datasource.url=jdbc:mysql://localhost:3306/micro_account?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull #use jasypt to encrypt username/password spring.datasource.username=ENC(BnBr3/idF0PH9nd20A9BXw==) spring.datasource.password=ENC(BnBr3/idF0PH9nd20A9BXw==) spring.datasource.driverClassName=com.mysql.jdbc.Driver
至此,配置完成,效果就如你在simplemall源碼中看到的那樣,針對配置文件中相關屬性作了一次安全升級。spring
源碼:https://github.com/backkoms/s...sql
擴展閱讀:安全
基於SpringCloud的Microservices架構實戰案例-序篇
基於SpringCloud的Microservices架構實戰案例-架構拆解