1.pom文件增加依賴 <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.5</version> </de ...
1.pom文件增加依賴
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2.修改啟動類增加StringEncryptor實現
jasypt密碼可以放到配置文件或者啟動命令中,與其這樣不如直接寫到代碼里
@Primary
@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("xxxx");//這裡改成你的密碼
config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
return encryptor;
}
註意:上面的@Primary 註解必須加上,覆蓋預設實現。
3.本地寫一個加密類,對你要加密的敏感信息加密
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class JasyptTest {
public static void main(String[] args) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("xxxx");//改成你的密碼
config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
String originStr = "xxxx" ;//原始字元串
String encStr = encryptor.encrypt(originStr);
System.out.println("originStr encrypt is {}"+ encStr);//加密後的字元串,這個貼到配置文件中
System.out.println("originStr is {}"+ encryptor.decrypt(encStr));//驗證一下解密
}
}
4.修改配置文件
將加密後的信息用前面用 ENC( ) 包起來
例如:
原始配置:
spring.datascoure.password=yourpassword
改成:
spring.datascoure.password=ENC(JL2t1CZpj+cTQ30IFKu0lkoZCVpYbVIhLm1MRbBpaNI])
(完)
參考:
[1] https://zhuanlan.zhihu.com/p/480828512
[2] https://github.com/ulisesbocchio/jasypt-spring-boot
source: https://wangxuan.me/tech/2023/11/23/use-jasypt-to-encrypt-configs.html