Java 學習記錄131 — 員工管理系統專案練習-Configure MySQL and Encrypt password

張小雄
Aug 2, 2022

--

承上篇

若不想把密碼存明文的話,想要把密碼加密的話

(這是個練習專案,不想弄的話可以直接跳過)

可以使用 Jasypt,並添加下面設定

打開 Maven 添加,並重新運行 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>2.0.0</version>
</dependency>

打開 application.properties 添加

spring.datasource.url=jdbc:mysql://localhost:3306/employee_management_system?useSSL=false
spring.datasource.username=數據庫帳號
spring.datasource.password=ENC(加密後密碼)
jasypt.encryptor.password=加密參數
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialectspring.jpa.hibernate.ddl-auto = update

線上取得加密密碼

左邊是加密,右邊是解密,使用左邊

Enter plain text to Encrypt:輸入密碼

Select Type of Encryption:選第二個

Secret Key To Be Used While Encryption:加密參數

輸入完成點 Encrypt

Encrypted String:把這裡出現的字串,複製貼上到 spring.datasource.password=ENC(貼在此處)

打開 SpringbootBackendApplication.java

添加 @EnableEncryptableProperties

@SpringBootApplication
@EnableEncryptableProperties
public class SpringbootBackendApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootBackendApplication.class, args);
}
}

接著運行,若沒出現 bug 就代表加密成功

但這樣其實也沒有百分之百安全

若對方也知道使用的是 Jasypt 的話

用線上網頁右邊即可有機會解密

為了防止其他人用加密參數解密

可以把加密參數那行刪掉

透過 Intellij 來添加至 VM參數

方法:點 Intellij 的右上角,找到運行 RUN鍵

點左邊的長框框,點 Edit Confriguration

找到 VM 那欄填入 -Djasypt.encryptor.password=加密參數

若沒看到 VM 欄位,點選 Modify option 找到 Java 點 Add VM options

密碼加密教學

我爬文還有一種方法是用服務器的環境變量來設定

參考文章(最後一段)

--

--

張小雄
張小雄

Written by 張小雄

記錄成為軟體工程師的過程

No responses yet