配置文件配置信息与SpringCloud框架源码EnvironmentDecryptApplicationInitializer起冲突
程序员文章站
2022-06-09 15:00:43
...
问题描述:
配置文件需要配置数据库加密密码,采用RSA加密算法,但是统一需要 加{cipher}{rsa}前缀,不加前缀前启动正常。加了前缀后并且已经在代码里边处理替换掉前缀但是仍然报错:
java.lang.IllegalStateException: Cannot decrypt: key=spring.datasource.sydev.password
at org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.decrypt(EnvironmentDecryptApplicationInitializer.java:298)
at org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.lambda$decrypt$0(EnvironmentDecryptApplicationInitializer.java:276)
at java.util.LinkedHashMap.replaceAll(LinkedHashMap.java:694)
at org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.decrypt(EnvironmentDecryptApplicationInitializer.java:271)
at org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.decrypt(EnvironmentDecryptApplicationInitializer.java:196)
at org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.initialize(EnvironmentDecryptApplicationInitializer.java:130)
at org.springframework.cloud.bootstrap.BootstrapApplicationListener$DelegatingEnvironmentDecryptApplicationInitializer.initialize(BootstrapApplicationListener.java:441)
at org.springframework.boot.SpringApplication.applyInitializers(SpringApplication.java:626)
at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:370)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at com.ztesoft.SmartServiceApplication.main(SmartServiceApplication.java:38)
Caused by: java.lang.UnsupportedOperationException: No decryption for FailsafeTextEncryptor. Did you configure the keystore correctly?
at org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration$FailsafeTextEncryptor.decrypt(EncryptionBootstrapConfiguration.java:165)
at org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.decrypt(EnvironmentDecryptApplicationInitializer.java:283)
... 10 common frames omitted
解决办法:
查看bug提示的EnvironmentDecryptApplicationInitializer源码,发现他是springcloud内置的加密解密方法,打断点定位到如下方法:
于是查看ENCRYPTED_PROPERTY_PREFIX:
what?
刚好跟配置文件的配置密码前缀冲突,所以思路是重写下改类,重写的方式时包路径形同,记住需要启动的服务都需要重写一遍,因为这个是springcloud里边的,类加载在自己服务之前,所以你自己只在代码截取还不能起作用,都还没类加载到你代码就崩了
第一步:
在需要启动服务的的java文件夹下服务重写下类,新建下包和class:
第二步:
修改源码的ENCRYPTED_PROPERTY_PREFIX为其他任意值,尽量复杂一点避免以后冲突:
第二步:重写下源码的decrypt方法,替换下前缀
private void decrypt(Map<String, Object> properties) {
properties.replaceAll((key, value) -> {
String valueString = value.toString();
if (!valueString.startsWith(ENCRYPTED_PROPERTY_PREFIX)) {
return valueString.replace(RSA_PRE_FIX, "");
}
return decrypt(key, valueString);
});
}
第三步:在自己代码逻辑里边,调用加密方法的地方替换下前缀,......
上一篇: 乌发食物让你的头发越来越黑