GitHub地址: https://github.com/ulisesbocchio/jasypt-spring-boot
maven依赖
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
以下依赖需要加@EnableEncryptableProperties注解
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot</artifactId> <version>2.1.0</version> </dependency>
Jasypt Spring Boot 为 Spring Boot 项目中的属性源(property sources)提供加密支持。
有三种方法可以在项目中集成 jasypt-spring-boot:
-
如果 Spring Boot 项目中使用了 @SpringBootApplication 或者 @EnableAutoConfiguration ,在项目里添加jasypt-spring-boot-starter 依赖会自动对项目中整个属性(包括系统属性、环境属性、命令行参数、application.properties, yaml)启动加密。
-
如果项目里没有使用 @SpringBootApplication 或者 @EnableAutoConfiguration ,可以手动在 Configuration 类上添加注解 @EnableEncryptableProperties ,来在整个环境的属性启用属性加密。
-
如果想指定加密文件,可以使用 @EncryptablePropertySource 指定单个属性源。
简单点说就是 如果springboot项目mven依赖引入starter带则不用加@EnableEncryptableProperties , 引入<artifactId>jasypt-spring-boot-starter</artifactId>则需要加@EnableEncryptableProperties注解
yml配置文件
jasypt:
encryptor:
password: e!Jd&ljyJ^e4I5oU #随便定义
datasource: driver-class-name: com.mysql.jdbc.Driver url: ENC(EFwaxIyXCXYwJo0tP0jY9jD1MfXLFJNIYG8kRpTLZGskQYrnfMrazE7APFfYWUSzySGQFqk66tP9/sJMuJJrZCpm36HRiSU53vT42/K/Z8KH2rCfSFw8zhPIVltH5FPfCAP9fJbJhwwScwCwbGXegthu5RpSgaE8cRIXt8E=) username: ENC(kEbiaqGlnNvRy7RKHhg==) password: ENC(4AG83a7fTXnmN5CCXVltrN0bWHv)
加解密工具,单元测试
@Resource StringEncryptor encryptor; @Test public void jacketEncrypt() { //加密 String mongodb = encryptor.encrypt("mongodb://用户名:密码@IP地址:端口/库名"); String url = encryptor.encrypt("jdbc:mysql://IP地址:端口/库名?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true"); String name = encryptor.encrypt("用户名"); String password = encryptor.encrypt("密码"); System.out.println("url 密文: " + url); System.out.println("mongodb 密文: " + mongodb); System.out.println("name 密文: " + name); System.out.println("password 密文: " + password); //解密 String decrypt1 = encryptor.decrypt(name); String mongodb1 = encryptor.decrypt(mongodb); String decrypt2 = encryptor.decrypt(password); System.out.println(mongodb1 + "------------" + decrypt2); /*// 加密 BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); textEncryptor.setPassword("cShoiltAiro"); String newPassword = textEncryptor.encrypt("mongodb://lywater"); System.out.println(newPassword); // 解密 BasicTextEncryptor textEncryptor2 = new BasicTextEncryptor(); textEncryptor2.setPassword("cShoiltAiro"); String oldPassword = textEncryptor2.decrypt(newPassword); System.out.println(oldPassword); System.out.println("--------------------------");*/ }