springboot3加密配置文件的值

实现方案:自定义加密配置处理器

1.新增一个自定义处理器的类

@Component
public class EncryptedPropertyProcessor implements EnvironmentPostProcessor {
    public static final String NACOS_DECRYPT_SECRET_KEY = "LgZOYR7vaBFzihJt";
    private static final String ENCRYPTED_PREFIX = "encrypted:";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment,
                                       SpringApplication application) {
        Map<String, Object> decryptedProperties = new HashMap<>();

        for (PropertySource<?> propertySource : environment.getPropertySources()) {
            if (propertySource instanceof EnumerablePropertySource) {
                processPropertySource((EnumerablePropertySource<?>) propertySource, decryptedProperties);
            }
        }

        if (!decryptedProperties.isEmpty()) {
            environment.getPropertySources()
                    .addFirst(new MapPropertySource("decryptedProperties", decryptedProperties));
        }
    }

    private void processPropertySource(EnumerablePropertySource<?> propertySource,
                                       Map<String, Object> decryptedProperties) {
        for (String propertyName : propertySource.getPropertyNames()) {
            Object value = propertySource.getProperty(propertyName);
            if (value instanceof String && ((String) value).startsWith(ENCRYPTED_PREFIX)) {
                String encryptedValue = ((String) value).substring(ENCRYPTED_PREFIX.length());
                try {
                    String decryptValue = new String(Aes.decrypt(Aes.hexString2Bytes(encryptedValue), NACOS_DECRYPT_SECRET_KEY), "utf-8");
                    decryptedProperties.put(propertyName, decryptValue);
                } catch (Exception e) {
                    throw new RuntimeException("Failed to decrypt property: " + propertyName, e);
                }
            }
        }
    }

加解密方式可自行封住方法,比较灵活

2. 注册处理器

在 src/main/resources/META-INF/spring.factories 中添加:

org.springframework.boot.env.EnvironmentPostProcessor=com.yourpackage.EncryptedPropertyProcessor

重启项目后会根据处理器类覆盖解密后的yml配置的值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茂林修竹丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值