1、pom文件导入依赖
<!-- yml密码加密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
2、对密码加密
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.Test;
public class JasyptTest {
//加密
@Test
public void testEncrypt() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
// 加密的算法(默认的)
config.setAlgorithm("PBEWithMD5AndDES");
// 加密的密钥,自己填写
config.setPassword("htl");
standardPBEStringEncryptor.setConfig(config);
//密码(未加密)
String plainText = "123456";
String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
System.out.println(encryptedText);
}
//解密
@Test
public void testDe() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("htl");
standardPBEStringEncryptor.setConfig(config);
//加密后的密码
String encryptedText = "UXavnIi3he8znD2ZJk/4yQ==";
String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
System.out.println(plainText);
}
}
3、yml文件添加:
jasypt:
encryptor:
# 你的秘钥
password: htl
4、加密后的密码要放到 ENC() 里面
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/001project
username: root
password: ENC(GNIfWMjZMce08rqqnPoOZBx8T3yVNd81)
5、启动类添加 @EnableEncryptableProperties 注解
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication()
@MapperScan("com.yunshe.mapper")
@EnableEncryptableProperties //开启加密注解
public class ProjectApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
PS:发博客,仅仅是当作学习的笔记~