SpringBoot项目集成jasypt,想要对配置文件中数据库或redis的密码等敏感信息进行加密时。
添加依赖:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
然后写个main方法
public static void main(String[] args) throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
standardPBEStringEncryptor.setPassword("31e1ea1269204fc1a2102f40d9b7a33a");
standardPBEStringEncryptor.setIvGenerator(new NoIvGenerator());
String root = standardPBEStringEncryptor.encrypt("root");
System.out.println(root);
}
然后在配置文件中配置
然后就报错了:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'spring.datasource.username' to java.lang.String:
Reason: Failed to bind properties under 'spring.datasource.username' to java.lang.String
Action:
Update your application's configuration
两种解决办法:
第一种,依赖版本降低
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
jasypt3.0.0及以上版本默认加密方式为PBEWITHHMACSHA512ANDAES_256 ,但是2.1.2不支持启动参数注入
第二个方法:
加密的main方法:
public static void main(String[] args) throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
standardPBEStringEncryptor.setAlgorithm("PBEWithMD5AndDES");
standardPBEStringEncryptor.setPassword("31e1ea1269204fc1a2102f40d9b7a33a");
standardPBEStringEncryptor.setIvGenerator(new NoIvGenerator());
String root = standardPBEStringEncryptor.encrypt("root");
System.out.println(root);
}
配置文件里多加一个配置:
jasypt:
encryptor:
password: 31e1ea1269204fc1a2102f40d9b7a33a
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
或者直接用默认的
加密的main方法
public static void main(String[] args) throws Exception {
System.setProperty("jasypt.encryptor.password","31e1ea1269204fc1a2102f40d9b7a33a");
DefaultLazyEncryptor defaultLazyEncryptor = new DefaultLazyEncryptor(new StandardEnvironment());
String root = defaultLazyEncryptor.encrypt("root");
System.out.println(root);
}
配置文件:
jasypt:
encryptor:
password: 31e1ea1269204fc1a2102f40d9b7a33a
照样可以解决问题。
小弟才疏学浅,只能知其然,不能知其所以然,有知道问题原因的大佬可以留言。
如果对你有帮助,给个赞吧,谢谢!