在 Spring Cloud 配置服务器中,我实现了一个自定义 TextEncryptor 来使用我自己的加密算法加密和解密属性(我需要像这样),并且我制作了一个 TextEncryptorLocator 的 bean 来公开我自己的 TextEncryptor 作为加密和解密的基础。
使用 Spring 配置服务器端点加密/解密时成功运行:
curl localhost:8888/encrypt -s -d mypassword
682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
curl localhost:8888/decrypt -s -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
mypassword
但是当我存储类似的属性时
org.prop={密码}682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
它不使用我的自定义 TextEncryptor 进行解密,它简单地返回此:
{
"name": "cclient",
"profiles": [
"dev"
],
"label": null,
"version": null,
"state": null,
"propertySources": [
{
"name": "classpath:/config-repo/cclient/application-dev.properties",
"source": {
"org.prop": "682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda"
}
}
]
}
我所做的是:
public class MyTextEncryptor implements TextEncryptor {
private final static String secret = "A_SECRET_FOR_ENCRYPTION_AND_DECRYPTION" ;
@Override
public String encrypt(String text) {
// my encryption algorithm based on my secret
return "encrypted text";
}
@Override
public String decrypt(String encryptedText) {
// my encryption algorithm based on my secret
return "decrypted text";
}
}
@Bean
@Primary
public TextEncryptorLocator textEncryptorLocator() {
return new TextEncryptorLocator() {
@Override
public TextEncryptor locate(Map<String, String> keys) {
return new MyTextEncryptor();
}
};
}
@EnableConfigServer
@SpringBootApplication
public class CServerApplication {
public static void main(String[] args) {
SpringApplication.run(CServerApplication.class, args);
}
}
和我的 bootstrap.properties :
spring.application.name=cclient
spring.config.import=optional:configserver:http://localhost:8888
spring.cloud.config.name=application
spring.cloud.config.label=latest
好吧,在花了几个小时并检查 Github 中的 spring-cloud-config 源代码之后,我终于找到了答案,它是: 我们应该使用新的 TextEncryptorLocator 重新定义 CipherEnvironmentEncryptor bean,它使用 MyTextEncryptor 并将其设为 Primarry 所以我添加了这些行并且它有效
@Bean
@Primary
public CipherEnvironmentEncryptor cipherEnvironmentEncryptor(TextEncryptorLocator textEncryptorLocator)
{
return new CipherEnvironmentEncryptor(textEncryptorLocator);
}