gpt4 book ai didi

Micronaut 解密属性值

转载 作者:行者123 更新时间:2023-12-04 13:39:05 29 4
gpt4 key购买 nike

我想从 搬家spring micronaut .一些属性值为 encrypted ,我们目前正在使用 spring-boot-jasypt ,如下所述,以帮助 decrypt注入(inject) 时的属性值spring 应用。

但是,我还没有找到在 中添加属性加密器的方法。 micronaut 框架让我做同样的事情。有没有人知道如何在 中做到这一点? micronaut ?

https://www.baeldung.com/spring-boot-jasypt

最佳答案

以下方法对我有用。创建 @Context注释 Singleton这将在所有其他 bean 之前创建。创建时Environment已初始化并加载所有配置属性。接下来查找所有以定义加密值的特殊前缀开头的属性。使用解密值创建新的属性源并将其放入 Environment如新 PropertySource .
代码:

@Context
@Singleton
@Requires(property = "JASYPT_ENCRYPTOR_PASSWORD")
@Slf4j
public class JasyptConfigurationPropertiesDecryptor implements BeanInitializedEventListener<Environment> {
private static final String PREFIX = "ENC(";

public JasyptConfigurationPropertiesDecryptor(DefaultEnvironment env, @Value("${JASYPT_ENCRYPTOR_PASSWORD}") String encPassword) {
log.info("JasyptBootstrapDecryptor started");
processConfigurationProperties(env, encPassword);
}

public void processConfigurationProperties(DefaultEnvironment env, String encPassword) {
StandardPBEStringEncryptor encryptor = encryptor(encPassword);
Map<String, Object> all = env.getAllProperties(StringConvention.RAW, MapFormat.MapTransformation.FLAT);
Map<String, Object> decrypted = all.entrySet().stream()
.filter(entry -> entry.getValue().toString().startsWith(PREFIX))
.collect(collector(encryptor));

env.addPropertySource(MapPropertySource.of("decrypted", decrypted));
}

private StandardPBEStringEncryptor encryptor(String encPassword) {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword(encPassword);
encryptor.setStringOutputType("base64");
encryptor.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
encryptor.setIvGenerator(new RandomIvGenerator());
return encryptor;
}

@Nonnull
private Collector<Map.Entry<String, Object>, ?, Map<String, Object>> collector(StandardPBEStringEncryptor encryptor) {
return Collectors.toMap(Map.Entry::getKey, entry -> decrypt(entry, encryptor));
}

private String decrypt(Map.Entry<String, Object> entry, StandardPBEStringEncryptor encryptor) {
log.info("Decrypt \"{}\" configuration property", entry.getKey());
String encrypted = entry.getValue().toString().substring(PREFIX.length(), entry.getValue().toString().length() - 1);
return encryptor.decrypt(encrypted);
}

@Override
public Environment onInitialized(BeanInitializingEvent<Environment> event) {
return event.getBean();
}


}

关于Micronaut 解密属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59869960/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com