当前最新版本为3.0.0 但我没有跑起来 本文使用2.1.2实现 官网文档
添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
测试类
public class JasyptTest {
private final String salt = "salt";
/**
* 加密算法 3.0.0前默认算法为PBEWithMD5AndDES 3.0.0及其后默认算法为PBEWITHHMACSHA512ANDAES_256
*/
private final String algorithm = "PBEWithMD5AndDES";
@Test
public void testEncrypt() {
// jar包路径和password包含空格或其它特殊字符时需使用双引号包括
// java -cp D:\apache-maven\repository\org\jasypt\jasypt\1.9.3\jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=123456 password=salt algorithm=PBEWithMD5AndDES
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm(algorithm);
config.setPassword(salt); // 盐值
standardPBEStringEncryptor.setConfig(config);
String plainText = "123456"; // 密码明文
String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
System.out.println(encryptedText);
}
@Test
public void testDecrypt() {
// java -cp D:\apache-maven\repository\org\jasypt\jasypt\1.9.3\jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="UQYWKlRt8B8xR5S0qK/W1w==" password=salt algorithm=PBEWithMD5AndDES
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm(algorithm);
config.setPassword(salt); // 盐值
standardPBEStringEncryptor.setConfig(config);
System.out.println(standardPBEStringEncryptor.decrypt("z/DToUyute3CJDZc22bN9w=="));
System.out.println(standardPBEStringEncryptor.decrypt("UQYWKlRt8B8xR5S0qK/W1w=="));
System.out.println(standardPBEStringEncryptor.decrypt("qMayX003HCjXkp8wsstiqQ=="));
}
}
盐值直接放在配置文件中相当于无效 因此可放在环境变量或环境属性中
环境变量为操作系统层面只可读不可写 环境属性为jvm层面可读可写
// 获取环境属性
System.getProperty("test")
// test环境属性不存在时返回默认值default
System.getProperty("test", "default")
// 在运行时设置系统属性
System.setProperty("test", "value");
// 运行app.jar时 将此应用test属性设为value
java -jar app.jar -Dtest=value
// 获取所有环境变量返回一个只读map 修改map会报错UnsupportedOperationException
System.getenv()
// 获取key为test的环境变量
System.getenv("test")
在spring-boot配置文件中使用${key}的方式取值会自动获取环境变量和环境属性的值
配置springboot 需配置@EnableAutoConfiguration但@SpringBootApplication中已包含
jasypt:
encryptor:
# 获取参数名为JASYPT的当前系统的环境变量或命令行参数(java -jar xxxx.jar JASYPT=abcd)
# 使用命令行直接指定盐值 java -jar xxxx.jar --jasypt.encryptor.password=abcd
# JASYPT作为盐值 JASYPT获取不到时使用abcd作为值
password: ${JASYPT:abcd}
algorithm: PBEWithMD5AndDES
# 使用ENC解密配置文件 ENC()前后不能有其它字符 否则不会解析
baidu-ak: ENC(F454f8a5efe5e577997931cc01de3974)
测试controller
@Controller
public class TestController {
@Value("${baidu-ak}")
private String baiduAk;
@GetMapping("test")
public String test() {
return baiduAk;
}
}