你是否還是這樣,簡單粗暴的把數(shù)據(jù)庫用戶名掌唾、密碼等敏感信息寫在配置文件中放前?那你又是否曾經(jīng)考慮過其中的安全性問題?
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false
username: root
password: 123456
如果有的話糯彬,那下面來看看凭语,如何通過使用 Jasypt Spring Boot ,以更加優(yōu)雅的方式來規(guī)避這種操作撩扒。
- 相關(guān)依賴
<dependencies>
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
- 完善配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&tinyInt1isBit=false
# 對應(yīng)用戶名 root 似扔,密碼 123456
username: ENC[KHRM9dKY8KykzzYbt8rRZQ==]
password: ENC[RWmQMxlcukotJAb36PrKSA==]
jasypt:
encryptor:
# 任意的隨機(jī)字符串均可
password: SBPstLlrFzXW01Okb62R95qvpj4J83Dn
property:
# 自定義屬性規(guī)則,默認(rèn)前綴是“ENC(”,后綴為“)”
prefix: "ENC["
suffix: "]"
留意到上面這段配置的用戶名和密碼是 ENC[xxx]
這種格式的虫几,其中 ENC[]
是自定義配置的锤灿,這也是 Jasypt 能正常識別待解密數(shù)據(jù)的規(guī)則,那其中的加密串又是從哪來的呢辆脸?
當(dāng)然是運(yùn)算出來的但校。最簡單的配置,開發(fā)者只需要再補(bǔ)充完 jasypt.encryptor.password=xxx
屬性即可(同上啡氢,還支持使用 DER状囱、PEM 這種證書的 private/public keys 加解密方式),具體的生成代碼在下方:
@Slf4j
@SpringBootApplication
@EnableEncryptableProperties
public class JasyptSpringBootApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(JasyptSpringBootApplication.class, args);
JasyptSpringBootApplication application = context.getBean(JasyptSpringBootApplication.class);
// 這里可以將明文(用戶名倘是、密碼)轉(zhuǎn)換成相應(yīng)密文
application.jasypt("root");
application.jasypt("123456");
// 不過程序最后還是通過明文信息進(jìn)行數(shù)據(jù)庫連接
HikariDataSource hikariDataSource = (HikariDataSource) context.getBean(DataSource.class);
log.info("DB username: {} , password: {}", hikariDataSource.getUsername(), hikariDataSource.getUsername());
}
@Resource
private StringEncryptor stringEncryptor;
public void jasypt(String text) {
// 即使是相同明文亭枷,但這里每次生成的都是不同的密文
String encryptedText = stringEncryptor.encrypt(text.trim());
String decryptedText = stringEncryptor.decrypt(encryptedText);
log.info("ORIGINAL: {} ; ENCRYPTED: {} ; DECRYPTED: {}", text, encryptedText, decryptedText);
}
}
相關(guān)鏈接
jasypt-spring-boot
jasypt-spring-boot-samples
示例源碼
歡迎關(guān)注我的個人公眾號:超級碼里奧
如果這對您有幫助,歡迎點贊和分享搀崭,轉(zhuǎn)載請注明出處