- 导入包
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.14</version>
</dependency>
2.配置加密秘钥(application.properties)和开启数据库加密(@EnableEncryptableProperties
)
#jasypt加密的密匙(正式环境中为确保安全把秘钥写在代码中,和要加密的密码分开)
#jasypt.encryptor.password=pcitc
@EnableAutoConfiguration
@SpringBootApplication
@EnableSwagger2//swagger api
@EnableEncryptableProperties//启动数据库加密
public class Application {
public static void main(String[] args) {
try {
//代码中配置秘钥
System.setProperty("jasypt.encryptor.password", "pcitc");
SpringApplication.run(Application.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 编写密码加密工具类
package util;
import org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI;
public class EncryptorTest {
public static void main(String[] args) {
String[] s = new String[2];
s[0] = "input=ythx";//要加密的字符串,写在=后面
s[1] = "password=pcitc";//秘钥,和项目中的jasypt.encryptor.password保持一致,不然密码解析会报错org.jasypt.exceptions.EncryptionOperationNotPossibleException
//s[2] = "algorithm=PBEWithMD5AndDES";//加密算法
JasyptPBEStringEncryptionCLI.main(s);
}
}
- 其他注意事项
- 高版本(2.1.0)的Jasypt启动时会报错,找不到org.springframework.boot.context.propertie.PlaceholdersResolver
- 加密解密的秘钥要确保一样
- 确保电脑中有 jce(密码扩展无限制权限策略文件)
如果没有去这里下载:
https://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
解压后将两个jar文件放到JDK的\jre\lib\security文件夹内