springboot 配置 jasypt加密,應用於配置檔案資料庫密碼加密形式展現
阿新 • • 發佈:2022-05-20
1.pom.xml匯入對應的包
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <build> <plugins> <plugin> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-maven-plugin</artifactId> <version>3.0.3</version> </plugin> </plugins> </build>
2.第二步:加鹽(三種方式)
1..yml中 一般是本地開發的時候
jasypt: encryptor: password: xxxxx
在環境變數中配置 JASYPT_ENCRYPTOR_PASSWORD =xxx (xxx根據自己的金鑰設定)
2.在Program arguments 中設定 --jasypt.encryptor.password=xxx 一般是在正式顯示採用這種方式,誰也不知道你的金鑰是多少
3.在vm arguments 中設定 -Djasypt.encryptor.password=xxx 一般是在正式顯示採用這種方式,誰也不知道你的金鑰是多少
第三步:編寫測試
package com.org; import org.jasypt.encryption.StringEncryptor; 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; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class EncryptorTest { @Autowired private StringEncryptor encryptor; @Test public void encry() { String username = encryptor.encrypt("UserName"); String password = encryptor.encrypt("Password"); System.out.println(username); //獲取加密的name 7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu 在DB配置中替換 System.out.println(password); //獲取加密的password 3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b 在DB配置中替換 } }
第四步:替換DB配置資訊
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://xx.x.x.xx:3306/zxxxx username: ENC(7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu) password: ENC(3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b)
到這一步就OK了,如果需要自定義密文的前後綴,可如下設定:
jasypt: encryptor: property: prefix: "ENC@[" suffix: "]"
如果以上配置不能使用的時候可以在啟動類加上註解
@EnableEncryptableProperties
datasource 程式碼獲取如下
@Configuration @Order(3) public class DataSourceConfig { //@Primary @Bean("datasource") //@Qualifier("datasource") @ConfigurationProperties(prefix = "datasource.datasource") public DataSource defaultDataSource() { return DataSourceBuilder.create().build(); } }
測試環境或者線上環境啟動命令如下 在你的明令上新增上這個
-Djasypt.encryptor.password='xxxx'