SpringBoot敏感配置加密:Jasypt

背景

  • 對於配置中的密碼(DB, MQ, Redis等),甚至賬號,在生產環境下存明文,不安全,不專業,不合適。

  • 一把插着鑰匙的鎖,能說它是安全的嗎?

操作流程

關於Jasypt實現對配置項的加密,網絡上已經有很多這方面的資料,這裏簡要描述下步驟。

  1. 引入依賴
<dependency>
  <groupId>com.github.ulisesbocchio</groupId>
  <artifactId>jasypt-spring-boot-starter</artifactId>
  <version>1.18</version>
</dependency>
  1. 生成密文
  • 如果計算機上有項目用過Jasypt的,那麼在maven的倉庫目錄下會有Jasypt的jar包。如果本地倉庫沒有,先下載jar包。在jar包所在目錄下打開cmd命令行,鍵入java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="root" password=you-guess algorithm=PBEWithMD5AndDES
    2020-05-23-jasypt-encypt.png最下面輸出的qN66aPx0SrcFulrPfmMXOw==是密文,在接下來要放入配置文件。
  1. 修改已有的配置

在已有的明文配置文件中,修改Jasypt密碼相關配置。

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&useSSL=false
    username: root
    password: ENC(qN66aPx0SrcFulrPfmMXOw==)

# 配置日誌
logging:
  level:
    root: info
    com.heartsuit.dao: trace
  pattern:
    console: '%p%m%n'

# 加密密鑰
jasypt:
  encryptor:
    password: you-guess

上面的修改主要有:
2020-05-23-jasypt-config.pngNote: 生成的密文要用ENC()包起來,這是Jasypt的要求。

  1. 測試修改後的配置

略(按照上述配置,應一切正常~~)

Note: 需要注意的是,用於生成加密後的密碼的密鑰不可放在配置文件或者代碼中,加密密鑰jasypt.encryptor.password=you-guess可以對密文解密。因此,上述配置若在團隊內可見,沒什麼影響,但是如果配置文件萬一被放到了公網上,相當於把鑰匙插在鎖上,白加密了。。在生產環境下,建議去掉加密密鑰配置:

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&useSSL=false
    username: root
    password: ENC(qN66aPx0SrcFulrPfmMXOw==)

# 配置日誌
logging:
  level:
    root: info
    com.heartsuit.dao: trace
  pattern:
    console: '%p%m%n'

僅去掉了:jasypt.encryptor.password=you-guess,這裏jasypt.encryptor.password=you-guess可以有兩種傳入方式:

  • 通過服務啓動參數
java -jar xxx.jar --jasypt.encryptor.password=you-guess
  • 通過系統環境變量

這個可以通過Idea IDE傳入(開發環境),或者實際的系統環境變量傳入(生產環境)。

Jasypt的加密與解密

通過Jasypt命令行的方式生產密文密碼後,可以用Jasypt提供的API進行解密,當然,也可以用API的方式來完成加密。

  • 加密與解密
@Component
public class StringEncryptDecrypt {

    @Autowired
    StringEncryptor encryptor;

    public String encrypt(String plainText) {
        // Encrypt
        String encrypted = encryptor.encrypt(plainText);
        System.out.println("Encrypted: " + encrypted);
        return encrypted;
    }

    public String decrypt(String encrypted) {
        // Decrypt
        String decrypted = encryptor.decrypt(encrypted);
        System.out.println("Decrypted: " + decrypted);
        return decrypted;
    }
}

總結

實現對配置文件敏感數據的加密,網上資源很多,但一定要注意安全性,不可以把公鑰共開配置在文件中;還是開頭那句話:

一把插着鑰匙的鎖,能說它是安全的嗎?

Source Code: Github

Reference: https://github.com/ulisesbocchio/jasypt-spring-boot


If you have any questions or any bugs are found, please feel free to contact me.

Your comments and suggestions are welcome!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章