Google Code Prettify

2022年7月6日 星期三

jasypt 加解密

 在 application.yml 中如果有資料庫連線設定,可能會如下:

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://127.0.0.1:3306/AUTH
  4. username: root
  5. password: ENC(wwCYqJ+PMxrCAY0aPs8v91/oykkFVyux)
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. jpa:
  8. database-platform: org.hibernate.dialect.MySQLDialect
上面密碼的部份是用 jasypt 加密,通常不會在設定檔直接寫明碼。那麼,怎麼初始化 jasypt 函式庫呢? 
  1. build.gradle
    1. implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4'
    加入如上 jar 檔。
  2. application.yml
    1. jasypt:
    2. encryptor:
    3. password: ${JASYPT_ENCRYPTOR_PASSWORD}
    4. algorithm: PBEWithMD5AndDES
    5. iv-generator-classname: org.jasypt.iv.NoIvGenerator
    ${JASYPT_ENCRYPTOR_PASSWORD} 會從環境變數取得加解密的 key,要注意最後一行,在 jasypt-spring-boot-starter 2.x 版不需要這個設定,到 3.x 版才需要。
  3. @EnableEncryptableProperties
    1. @EnableEncryptableProperties
    2. @SpringBootApplication
    3. public class DemoSecurityApplication {
    4.  
    5. public static void main(String[] args) {
    6. SpringApplication.run(DemoSecurityApplication.class, args);
    7. }
    8. }
    在 @SpringBootApplication 或 @Configuration 所在的 class 上加上 @EnableEncryptableProperties 啟用 jasypt。

沒有留言:

張貼留言