SpringBoot集成Jasypt对yml配置文件进行加密和解密
在 Spring Boot 中集成 Jasypt
- 添加 Jasypt 依赖
在 pom.xml 文件中添加 Jasypt 依赖:
下面展示一些 内联代码片。
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
- 生成密文代码工具类
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
public class JasyptUtil {
private final static String SECRECT = "KghwgKzLvucm";
private final static String ALGORITHM = "PBEWithMD5AndDES";
public static String encrypt(String text){
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm(ALGORITHM);
config.setPassword(SECRECT);
standardPBEStringEncryptor.setConfig(config);
return standardPBEStringEncryptor.encrypt(text);
}
public static String decrypt(String text) {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm(ALGORITHM);
config.setPassword(SECRECT);
standardPBEStringEncryptor.setConfig(config);
return standardPBEStringEncryptor.decrypt(text);
}
}
- yml加密配置(jasypt配置一定要放最上面)
jasypt:
encryptor:
password:
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
spring:
datasource:
url: ENC(加密后 xxx)
username: ENC(加密后 xxx)
password: ENC(加密后 xxx)
driver-class-name: com.mysql.cj.jdbc.Driver
- 运行项目
在idea中运行,需要通过VM options设置
