本文代碼 https://gitee.com/tothis/spring-boot-record/tree/master/jasypt
當前最新版本爲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;
}
}