【问题标题】:Loading decrypted Password with Jasypt in Spring Boot在 Spring Boot 中使用 Jasypt 加载解密的密码
【发布时间】:2021-12-02 03:59:48
【问题描述】:

我正在尝试使用 Spring Boot 设置 Jasypt 工作流程。如this Tutorial 中所述,我添加了所需的依赖项:

<dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot-starter</artifactId>
        <version>3.0.4</version>
</dependency>

用:加密密码:

mvn jasypt:encrypt-value -Djasypt.encryptor.password=javatechie -Djasypt.plugin.value=Password

创建了一个encrypted.properties并将加密的密码放入其中:

secret.property=ENC(nrmZtkF7T0kjG/VodDvBw93Ct8EgjCAaskygdq8PHapYFnlX6WsTwZZOxWInq+i)

注释了我的主类:

@SpringBootApplication
@EnableEncryptableProperties
@PropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

在另一个类中我尝试加载解密后的值:

@Component
public class MyOtherClass {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyOtherClass.class);

    @Value("${secret.property}")
    String secret;

    public MyOtherClass() {
        LOGGER.info("PW: " + secret);
    }
}

但我只是得到:

PW: null

当我将值更改为不存在的东西时:

@Value("${abc.def}")
String secret;

我得到了预期的错误:

java.lang.IllegalArgumentException:无法解析值“${abc.def}”中的占位符“abc.def”

所以好像找到了我的实际值secret.property,但是为什么是null呢?

【问题讨论】:

  • 您能否确保您的encrypted.properties 文件已正确加载?我的意思是我看不到任何带有@PropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties") 的@Configuration。尝试放置一些虚拟键值并将其放入您的组件中。
  • 检查日志是否有任何 Jasypt 异常。
  • @sushant:在日志中显示:o.s.c.e.PropertySourcesPropertyResolver : Found key 'secret.property' in PropertySource 'environmentProperties' with value of type String。但值仍然是null
  • @KumarAshutosh:@PropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties") 在我的Main.class 中。
  • 您正在访问 bean 中的注入属性。 Spring首先实例化bean,然后注入值。您可以尝试访问构造函数之外的值,例如 bean 方法。

标签: java spring spring-boot encryption jasypt


【解决方案1】:

您正在访问构造函数中的注入属性。这不起作用,因为这里 Spring 将实例化 bean,然后注入属性。因此,如果您在构造函数中访问该属性,您将获得注入前的默认值null。如果你想访问构造函数中的属性,那么你可以像这样使用构造函数注入:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyOtherClass {
    private static final Logger LOGGER = 
                      LoggerFactory.getLogger(MyOtherClass.class);

    String secret;

    @Autowired
    public MyOtherClass(@Value("${secret.property}") String secret) {
        LOGGER.info("PW: " + secret);
        this.secret = secret;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2020-03-07
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    相关资源
    最近更新 更多