java - Spring Boot如何在属性文件中隐藏密码

标签 java spring spring-boot

Spring Boot 使用属性文件,至少默认情况下,密码是纯文本的。是否有可能以某种方式隐藏/解密这些?

最佳答案

您可以使用 Jasypt 来加密属性,因此您可以拥有这样的属性:

db.password=ENC(XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=)

Jasypt 允许您使用不同的算法加密您的属性,一旦您获得放入 ENC(...) 的加密属性。例如,您可以使用终端通过 Jasypt 以这种方式加密:

encrypted-pwd$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="contactspassword" password=supersecretz algorithm=PBEWithMD5AndDES

----ENVIRONMENT-----------------

Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.45-b08



----ARGUMENTS-------------------

algorithm: PBEWithMD5AndDES
input: contactspassword
password: supersecretz



----OUTPUT----------------------

XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=

要使用 Spring Boot 轻松配置它,您可以使用它的启动器 jasypt-spring-boot-starter组 ID com.github.ulisesbocchio

请记住,您需要使用与加密属性相同的密码来启动您的应用程序。所以,你可以这样启动你的应用:

mvn -Djasypt.encryptor.password=supersecretz spring-boot:run

或者使用环境变量(感谢 spring boot 宽松绑定(bind)):

export JASYPT_ENCRYPTOR_PASSWORD=supersecretz
mvn spring-boot:run

您可以查看以下链接了解更多详情:

https://www.ricston.com/blog/encrypting-properties-in-spring-boot-with-jasypt-spring-boot/

要在您的应用程序中使用您的加密属性,只需像往常一样使用它,使用您喜欢的任何一种方法(Spring Boot 具有魔力,无论如何属性必须在类路径中):

使用@Value注解

@Value("${db.password}")
private String password;

或者使用环境

@Autowired
private Environment environment;

public void doSomething(Environment env) {
    System.out.println(env.getProperty("db.password"));
}

更新:对于生产环境,避免在命令行中暴露密码,因为您可以使用 ps 查询进程,使用 history 查询之前的命令等。你可以:

  • 像这样创建一个脚本:touch setEnv.sh
  • 编辑 setEnv.sh 以导出 JASYPT_ENCRYPTOR_PASSWORD 变量

    #!/bin/bash

    export JASYPT_ENCRYPTOR_PASSWORD=supersecretz

  • 使用 执行文件。 setEnv.sh
  • 使用 mvn spring-boot:run &
  • 在后台运行应用
  • 删除文件setEnv.sh
  • 使用以下命令取消设置之前的环境变量:unset JASYPT_ENCRYPTOR_PASSWORD

关于java - Spring Boot如何在属性文件中隐藏密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37404703/

相关文章:

java - SwingWorker + JTable : how to change the code so that there was no error?

java - IlleagalMonitorStateException 当我试图运行这个程序时

java - java.util.Calendar 线程是否安全?

java - Spring上下文引用java

java - 提交带有选择和文本字段作为禁用和隐藏字段的表单。值未正确存储

java - 无法在输入字段中显示 JSTL 值 - Spring MVC

spring - Spring请求映射的路径参数中的String :. +是什么

spring-boot - 如何在 Spring-boot 中为 Rest 调用编写 webSockets?

java - Spring安全用户详细信息: org. springframework.security.authentication.DisabledException

Spring Boot : Testing the Service layer