第一步:引入依赖
<!-- jasypt加密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
第二步:启动类注解
@SpringBootApplication
@EnableEncryptableProperties
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
第三步:yml配置
# Jasypt加密配置
jasypt:
encryptor:
#生产环境非此密钥
password: 1234567890
#指定解密算法
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
第四步:生成密文
@Test
void test() throws InterruptedException {
System.out.println(encrypt("root", "1234567890"));
}
public static String encrypt(String password, String factor) {
//加密工具
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//加密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
//秘钥
config.setPassword(factor);
//应用配置
encryptor.setConfig(config);
//加密
return encryptor.encrypt(password);
}
第五步:将第四步生成的密文通过ENC()包裹
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: ENC(4agwjbpTuk8qGGKaco0Rsg==)
url: jdbc:mysql://127.0.0.1:3306/dms?useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai
username: ENC(Pfydgw/yIGmEvj2rUBlRDQ==)